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。

feat: 让 cindy_helper 可查看会话排队消息 (#2804)

Chris Zhangc7e87448da3d
diff --git a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
index 7f1a6dd4fd..c4a644bd45 100644
--- a/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
+++ b/apps/desktop/src/main/__tests__/mobileClientPromptNote.test.ts
@@ -301,11 +301,13 @@ describe('stripMainOnlySendOpts(直连路径消毒)', () => {
.toEqual({ messageUuid: 'u' });
});
- it('剥掉客户端伪造的 generation,但保留待 IPC 校验的 clear token', () => {
+ it('剥掉客户端伪造的 generation 与 turn 身份,但保留待 IPC 校验的 clear token', () => {
expect(
stripMainOnlySendOpts({
expectedClearBoundaryMs: 123,
expectedInputGeneration: 77,
+ expectedTurnSession: { forged: true },
+ expectedTurnGeneration: 88,
messageUuid: 'u',
}),
).toEqual({ expectedClearBoundaryMs: 123, messageUuid: 'u' });
diff --git a/apps/desktop/src/main/agent-island/__tests__/service.test.ts b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
index 58814a974f..c9983fa816 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -553,6 +553,174 @@ describe('AgentIslandService native publishing', () => {
);
});
+ it('exposes the canonical snapshot and emits per-session transition edges', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: {
+ failed: false,
+ headless: true,
+ publish: () => true,
+ suspend: () => undefined,
+ },
+ });
+ const transitions = vi.fn();
+ const unsubscribe = service.subscribeSessionActivity(transitions);
+
+ service.setEnabled(false);
+ service.handleUserPrompt(
+ {
+ sessionId: 'canonical',
+ agentKind: 'codex',
+ },
+ 'run tests',
+ );
+ service.handleSessionMetadataPatch('canonical', {
+ title: '🚧#2804 会话控制面 · 待bot',
+ });
+
+ const canonicalSnapshot = service.getSessionActivitySnapshot('canonical');
+ expect(canonicalSnapshot).toMatchObject({
+ sessionId: 'canonical',
+ phase: 'running',
+ recordStatus: 'active',
+ currentActionSummary: '正在处理新消息',
+ source: 'live',
+ workflow: {
+ key: 'awaiting-bot',
+ label: '待bot',
+ waitingOn: 'automation',
+ },
+ });
+ expect(canonicalSnapshot).not.toHaveProperty('compactDetail');
+ expect(JSON.stringify(canonicalSnapshot)).not.toContain('run tests');
+ expect(transitions).toHaveBeenNthCalledWith(1, expect.objectContaining({
+ sessionId: 'canonical',
+ previous: null,
+ current: expect.objectContaining({ phase: 'running' }),
+ changedAtMs: expect.any(Number),
+ }));
+ expect(transitions).toHaveBeenLastCalledWith(expect.objectContaining({
+ sessionId: 'canonical',
+ previous: expect.objectContaining({ workflow: null }),
+ current: expect.objectContaining({
+ workflow: expect.objectContaining({ key: 'awaiting-bot' }),
+ }),
+ }));
+
+ service.resetRuntimeState();
+ expect(transitions).toHaveBeenLastCalledWith(expect.objectContaining({
+ sessionId: 'canonical',
+ previous: expect.objectContaining({ phase: 'running' }),
+ current: null,
+ }));
+
+ unsubscribe();
+ transitions.mockClear();
+ service.handleUserPrompt({ sessionId: 'after-unsubscribe', agentKind: 'codex' }, 'continue');
+ expect(transitions).not.toHaveBeenCalled();
+ });
+
+ it('resets the canonical turn start time when a completed session starts again', async () => {
+ vi.useFakeTimers();
+ try {
+ const { AgentIslandService } = await import('../service.js');
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: {
+ failed: false,
+ headless: true,
+ publish: () => true,
+ suspend: () => undefined,
+ },
+ });
+ const meta = { sessionId: 'reused', agentKind: 'codex' as const };
+
+ vi.setSystemTime(1_000);
+ service.handleUserPrompt(meta, 'first');
+ expect(service.getSessionActivitySnapshot(meta.sessionId)?.startedAtMs).toBe(1_000);
+ service.handleAgentEvent(meta, doneEvent());
+
+ vi.setSystemTime(2_000);
+ service.handleUserPrompt(meta, 'second');
+ expect(service.getSessionActivitySnapshot(meta.sessionId)).toMatchObject({
+ phase: 'running',
+ startedAtMs: 2_000,
+ lastActivityAtMs: 2_000,
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('resets the canonical turn start time when a new turn is first observed from an agent event', async () => {
+ vi.useFakeTimers();
+ try {
+ const { AgentIslandService } = await import('../service.js');
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: {
+ failed: false,
+ headless: true,
+ publish: () => true,
+ suspend: () => undefined,
+ },
+ });
+ const meta = { sessionId: 'event-reused', agentKind: 'codex' as const };
+
+ vi.setSystemTime(1_000);
+ service.handleUserPrompt(meta, 'first');
+ service.handleAgentEvent(meta, doneEvent());
+
+ vi.setSystemTime(2_000);
+ service.handleAgentEvent(meta, {
+ type: 'status',
+ source: 'codex',
+ data: { isRunning: true, status: 'Thinking...' },
+ });
+ expect(service.getSessionActivitySnapshot(meta.sessionId)).toMatchObject({
+ phase: 'running',
+ startedAtMs: 2_000,
+ lastActivityAtMs: 2_000,
+ });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('does not emit a canonical transition for display-only detail changes', async () => {
+ vi.useFakeTimers();
+ try {
+ vi.setSystemTime(1_000);
+ const { AgentIslandService } = await import('../service.js');
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: {
+ failed: false,
+ headless: true,
+ publish: () => true,
+ suspend: () => undefined,
+ },
+ });
+ const transitions = vi.fn();
+ service.subscribeSessionActivity(transitions);
+ service.setEnabled(false);
+
+ service.handleUserPrompt({ sessionId: 'detail-only', agentKind: 'codex' }, 'first body');
+ expect(transitions).toHaveBeenCalledTimes(1);
+ transitions.mockClear();
+
+ service.handleUserPrompt({ sessionId: 'detail-only', agentKind: 'codex' }, 'second body');
+ expect(service.getSessionActivitySnapshot('detail-only')).toMatchObject({
+ phase: 'running',
+ currentActionSummary: '正在处理新消息',
+ });
+ expect(transitions).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('replays current compact activity for late sessions subscribers', async () => {
const { AgentIslandService } = await import('../service.js');
const service = new AgentIslandService({
diff --git a/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.ts b/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.ts
index 078ce41ce5..66959770a1 100644
--- a/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/sessionActivityRelay.test.ts
@@ -10,8 +10,16 @@ function activity(
return {
sessionId,
phase: 'running',
+ recordStatus: 'active',
compactDetail,
+ startedAtMs: 1,
+ lastActivityAtMs: 1,
+ currentActionSummary: compactDetail,
attention: false,
+ workflow: null,
+ turnGeneration: null,
+ gracefulStopState: 'none',
+ source: 'live',
...patch,
};
}
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index 93471f3a99..01a12a4659 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -10,6 +10,11 @@ import {
} from '@cindy/maker-core';
import type { SchedulerEvent } from '@cindy/maker-scheduler';
import { BRAND_NAME } from '@cindy/maker-shared/branding';
+import {
+ projectSessionActivity,
+ type SessionActivitySnapshot,
+ type SessionActivityTransition,
+} from '@cindy/maker-shared/session-activity';
import { isDefaultDraftSessionTitle } from '@cindy/maker-shared/session-title';
import {
isProductTurnCompletionTailEvent,
@@ -52,6 +57,7 @@ import {
type AgentIslandDisplayState,
type AgentIslandPillSnapshot,
type AgentIslandSessionActivity,
+ type AgentIslandSessionSnapshot,
type AgentIslandDisplayTarget,
type AgentIslandMascotSkin,
type AgentIslandStrings,
@@ -220,12 +226,64 @@ export function getAgentIslandService(): AgentIslandService | null {
return serviceSingleton;
}
+function sessionActivitySnapshotsEqual(
+ left: AgentIslandSessionActivity,
+ right: AgentIslandSessionActivity,
+): boolean {
+ return left.sessionId === right.sessionId
+ && left.phase === right.phase
+ && left.currentTurnActive === right.currentTurnActive
+ && left.recordStatus === right.recordStatus
+ && left.startedAtMs === right.startedAtMs
+ && left.lastActivityAtMs === right.lastActivityAtMs
+ && left.currentActionSummary === right.currentActionSummary
+ && left.interactionKind === right.interactionKind
+ && left.attention === right.attention
+ && left.workflow?.key === right.workflow?.key
+ && left.workflow?.label === right.workflow?.label
+ && left.workflow?.waitingOn === right.workflow?.waitingOn
+ && left.turnGeneration === right.turnGeneration
+ && left.gracefulStopState === right.gracefulStopState
+ && left.source === right.source;
+}
+
+function safeSessionActionSummary(snapshot: AgentIslandSessionSnapshot): string {
+ if (snapshot.phase === 'needs-interaction') {
+ if (snapshot.interactionKind === 'permission') return '等待权限确认';
+ if (snapshot.interactionKind === 'ask_user_question') return '等待用户回答';
+ if (snapshot.interactionKind === 'plan_review') return '等待计划确认';
+ if (snapshot.interactionKind === 'plugin_setup') return '等待插件配置';
+ return '等待用户确认';
+ }
+ if (snapshot.phase === 'completed') return '运行已正常结束';
+ if (snapshot.phase === 'error') return '运行出错';
+ const latestKind = snapshot.activityLines.at(-1)?.kind;
+ if (latestKind === 'tool') return '正在运行工具';
+ if (latestKind === 'assistant') return '正在生成回复';
+ if (latestKind === 'user') return '正在处理新消息';
+ return '正在运行';
+}
+
+function canonicalSessionActivity(
+ activity: AgentIslandSessionActivity,
+): SessionActivitySnapshot {
+ const { compactDetail: _compactDetail, ...snapshot } = activity;
+ return {
+ ...snapshot,
+ workflow: snapshot.workflow ? { ...snapshot.workflow } : null,
+ };
+}
+
/**
* Owns Agent Island display arbitration in main. Rendering is macOS-native:
* the Swift/AppKit helper owns the system-level panel, shape, shadow and hover
* tracking while TypeScript owns product state and session prioritization.
*/
export class AgentIslandService {
+ private readonly sessionActivityListeners = new Set<
+ (transition: SessionActivityTransition) => void
+ >();
+ private sessionActivitySubscriptionCursor = new Map<string, AgentIslandSessionActivity>();
private readonly state = createAgentIslandState();
private readonly nativeHost: AgentIslandNativeRenderer;
private readonly headless: boolean;
@@ -570,6 +628,7 @@ export class AgentIslandService {
this.clearSilencedRunTimer(runId);
}
resetAgentIslandState(this.state);
+ this.emitSessionActivityTransitions([], Date.now());
this.metadataCache.clear();
this.metadataLoading.clear();
this.lastSoundDisplayState = null;
@@ -1399,17 +1458,78 @@ export class AgentIslandService {
*/
private buildSessionActivityPayload(): AgentIslandSessionActivity[] {
return buildAllSessionActivitySnapshots(this.state).map((s) => ({
- sessionId: s.sessionId,
+ ...projectSessionActivity({
+ sessionId: s.sessionId,
+ recordStatus: 'active',
+ title: s.title,
+ source: 'live',
+ livePhase: s.phase,
+ startedAtMs: s.startedAt,
+ lastActivityAtMs: s.lastActivityAt,
+ currentActionSummary: safeSessionActionSummary(s),
+ interactionKind: s.interactionKind,
+ attention: s.attention,
+ }),
phase: s.phase,
- compactDetail: s.compactDetail,
interactionKind: s.interactionKind,
- attention: s.attention,
+ compactDetail: s.compactDetail,
}));
}
+ /** Read the same canonical snapshot used by sidebar and device-list relays. */
+ getSessionActivitySnapshot(sessionId: string): SessionActivitySnapshot | null {
+ const activity = this.buildSessionActivityPayload()
+ .find((item) => item.sessionId === sessionId);
+ return activity ? canonicalSessionActivity(activity) : null;
+ }
+
+ /**
+ * Subscribe to canonical activity transitions. Future Bot consumers attach here;
+ * this service remains unaware of Bot/runtime implementations.
+ */
+ subscribeSessionActivity(
+ listener: (transition: SessionActivityTransition) => void,
+ ): () => void {
+ this.sessionActivityListeners.add(listener);
+ return () => this.sessionActivityListeners.delete(listener);
+ }
+
+ private emitSessionActivityTransitions(
+ list: readonly AgentIslandSessionActivity[],
+ changedAtMs: number,
+ ): void {
+ const next = new Map(list.map((snapshot) => [snapshot.sessionId, snapshot]));
+ const sessionIds = new Set([
+ ...this.sessionActivitySubscriptionCursor.keys(),
+ ...next.keys(),
+ ]);
+ for (const sessionId of sessionIds) {
+ const previous = this.sessionActivitySubscriptionCursor.get(sessionId) ?? null;
+ const current = next.get(sessionId) ?? null;
+ if (previous && current && sessionActivitySnapshotsEqual(previous, current)) continue;
+ for (const listener of this.sessionActivityListeners) {
+ try {
+ listener({
+ sessionId,
+ previous: previous ? canonicalSessionActivity(previous) : null,
+ current: current ? canonicalSessionActivity(current) : null,
+ changedAtMs,
+ });
+ } catch (error) {
+ log.warn('session activity listener failed', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ }
+ }
+ this.sessionActivitySubscriptionCursor = next;
+ }
+
private emitSessionActivityToRenderer(): void {
const payload = this.buildSessionActivityPayload();
this.sessionActivityRelay.publish(payload);
+ this.emitSessionActivityTransitions(payload, Date.now());
this.notifySessionActivityConsumer(payload);
// 广播给所有 app content window(含「在新窗口打开」的副窗),不只主窗 —— 副窗也有侧栏、
// 也订阅同一频道,只发主窗会让副窗卡片预览停在陈旧 summary(PR #246 review)。
diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.ts
index 6289fd49c2..f0d24d45e0 100644
--- a/apps/desktop/src/main/agent-island/state.ts
+++ b/apps/desktop/src/main/agent-island/state.ts
@@ -454,7 +454,7 @@ export function applyAgentIslandUserPrompt(
if (!text) return false;
const session = getOrCreateSession(state, meta, now);
applyMeta(session, meta);
- markSessionRunning(state, session);
+ markSessionRunning(state, session, now);
session.phase = 'running';
session.interactionKind = undefined;
session.detail = '';
@@ -534,7 +534,7 @@ export function applyAgentIslandEvent(
const isRunning = data?.isRunning;
const status = typeof data?.status === 'string' ? data.status : null;
if (isRunning === true) {
- markSessionRunning(state, session);
+ markSessionRunning(state, session, now);
if (session.pendingInteractionIds.size === 0) {
session.phase = 'running';
session.interactionKind = undefined;
@@ -572,7 +572,7 @@ export function applyAgentIslandEvent(
const toolDescription = toolName
? formatIslandToolDetail(toolName, toolInput, { wording: state.toolWording }, data ?? undefined)
: firstNonEmptyString(data?.description, data?.toolDescription);
- markSessionRunning(state, session);
+ markSessionRunning(state, session, now);
if (toolUseId) {
dismissPendingInteraction(state, session, toolUseId, now, { requirePending: true });
}
@@ -685,7 +685,7 @@ export function applyAgentIslandInteractionRequest(
session.pendingInteractionIds.add(request.requestId);
session.pendingInteractionKinds.set(request.requestId, request.kind);
session.pendingInteractionDetails.set(request.requestId, detailForInteraction(request, state.toolWording));
- session.running = true;
+ markSessionRunning(state, session, now);
session.completionAllowedAfterTerminalError = false;
const activateRequest = request.kind !== 'permission' || session.permissionRequestId === null;
if (request.kind === 'permission') {
@@ -1251,7 +1251,12 @@ function updateFocusVerificationLifecycle(state: AgentIslandState, now: number):
state.pendingFocusUntil = null;
}
-function markSessionRunning(state: AgentIslandState, session: AgentIslandSessionState): void {
+function markSessionRunning(
+ state: AgentIslandState,
+ session: AgentIslandSessionState,
+ now: number,
+): void {
+ if (!session.running) session.startedAt = now;
session.running = true;
session.completedUntil = null;
session.errorUntil = null;
diff --git a/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.ts b/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.ts
index 20809aa944..eacfac27aa 100644
--- a/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.ts
+++ b/apps/desktop/src/main/localDb/__tests__/agentInputQueueSnapshotsPersistence.test.ts
@@ -1,3 +1,4 @@
+import Database from 'better-sqlite3';
import { describe, expect, it, vi } from 'vitest';
const mocks = vi.hoisted(() => ({
@@ -11,6 +12,7 @@ vi.mock('../client/current', () => ({
import {
AgentInputQueueSnapshotTooLargeError,
awaitAgentInputQueueSnapshotPersistence,
+ loadAgentInputQueueSnapshotCounts,
saveAgentInputQueueSnapshot,
} from '../agentInputQueueSnapshots.js';
import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';
@@ -123,4 +125,117 @@ describe('agent input queue snapshot durability boundary', () => {
});
expect(insert).not.toHaveBeenCalled();
});
+
+ it('counts selected snapshots in SQLite without returning payload bodies', async () => {
+ const query = vi.fn().mockResolvedValue([{ sessionId: 'session-1', itemCount: 2 }]);
+ mocks.getDbClient.mockReturnValue({ query } as never);
+
+ await expect(
+ loadAgentInputQueueSnapshotCounts(['session-1', 'session-2', 'session-1']),
+ ).resolves.toEqual({ 'session-1': 2, 'session-2': 0 });
+ expect(query).toHaveBeenCalledWith(expect.stringContaining('json_each(snapshot.payload)'), [
+ 'session-1',
+ 'session-2',
+ ]);
+ expect(query.mock.calls[0]?.[0]).not.toContain('SELECT payload');
+ });
+
+ it('matches restore de-duplication and clear-boundary filtering for cold queued counts', async () => {
+ const db = new Database(':memory:');
+ db.exec(`
+ CREATE TABLE sessions (
+ id TEXT PRIMARY KEY,
+ cleared_at INTEGER
+ );
+ CREATE TABLE agent_input_queue_snapshots (
+ session_id TEXT PRIMARY KEY,
+ payload TEXT NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE TABLE messages (
+ session_id TEXT NOT NULL,
+ client_id TEXT NOT NULL,
+ UNIQUE(session_id, client_id)
+ );
+ `);
+ const accepted = {
+ ...queued('accepted', 'client-accepted'),
+ hostAcceptedAtMs: 301,
+ };
+ const beforeClear = {
+ ...queued('before clear', 'client-before-clear'),
+ hostAcceptedAtMs: 299,
+ };
+ const missingReceipt = queued('missing receipt', 'client-missing-receipt');
+ const waiting = {
+ ...queued('waiting', 'client-waiting'),
+ hostAcceptedAtMs: 301,
+ };
+ const staleScheduler = {
+ ...queued('stale scheduler', 'client-stale-scheduler'),
+ hostAcceptedAtMs: 301,
+ origin: {
+ kind: 'scheduler' as const,
+ scheduleId: 'schedule-legacy',
+ scheduleName: 'Legacy heartbeat',
+ },
+ };
+ db.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, ?)').run(
+ 'session-crash-window',
+ 300,
+ );
+ db.prepare(
+ 'INSERT INTO agent_input_queue_snapshots (session_id, payload, updated_at) VALUES (?, ?, ?)',
+ ).run(
+ 'session-crash-window',
+ JSON.stringify([
+ accepted,
+ beforeClear,
+ missingReceipt,
+ waiting,
+ staleScheduler,
+ 'malformed legacy row',
+ ]),
+ Date.now(),
+ );
+ db.prepare('INSERT INTO messages (session_id, client_id) VALUES (?, ?)').run(
+ 'session-crash-window',
+ accepted.clientId,
+ );
+ const query = vi.fn(async <T = unknown>(sql: string, params: unknown[] = []) =>
+ db.prepare(sql).all(...params) as T[]);
+ mocks.getDbClient.mockReturnValue({ query } as never);
+
+ try {
+ await expect(
+ loadAgentInputQueueSnapshotCounts(['session-crash-window']),
+ ).resolves.toEqual({ 'session-crash-window': 1 });
+ expect(query.mock.calls[0]?.[0]).toContain('NOT EXISTS');
+ expect(query.mock.calls[0]?.[0]).toContain('FROM messages');
+ expect(query.mock.calls[0]?.[0]).toContain('session.cleared_at');
+ expect(query.mock.calls[0]?.[0]).toContain('$.hostAcceptedAtMs');
+ expect(query.mock.calls[0]?.[0]).toContain('$.origin.kind');
+ } finally {
+ db.close();
+ }
+ });
+
+ it('isolates corrupt snapshots while preserving database read failures', async () => {
+ const query = vi
+ .fn()
+ .mockResolvedValueOnce([
+ { sessionId: 'corrupt', itemCount: null },
+ { sessionId: 'healthy', itemCount: 2 },
+ ])
+ .mockRejectedValueOnce(new Error('db unavailable'));
+ mocks.getDbClient.mockReturnValue({ query } as never);
+
+ await expect(loadAgentInputQueueSnapshotCounts(['corrupt', 'healthy'])).resolves.toEqual({
+ corrupt: 0,
+ healthy: 2,
+ });
+ await expect(loadAgentInputQueueSnapshotCounts(['unavailable'])).rejects.toThrow(
+ 'db unavailable',
+ );
+ });
});
diff --git a/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts b/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts
index 50bc3ab015..bbcd11aa10 100644
--- a/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts
+++ b/apps/desktop/src/main/localDb/agentInputQueueSnapshots.ts
@@ -25,6 +25,7 @@ const log = createLogger('agent-input-queue-snapshots');
/** 单会话快照体量上限(16MB):正常队列远小于此,超限基本是多张大图的 base64。 */
const MAX_PAYLOAD_BYTES = 16 * 1024 * 1024;
+const SNAPSHOT_COUNT_QUERY_BATCH_SIZE = 200;
/** per-session 写链:只做覆盖写/删除排队保序,无读改写。 */
const _writeChains = new Map<string, Promise<void>>();
@@ -179,6 +180,89 @@ export async function loadAllQueueSnapshotPayloads(): Promise<string[]> {
return rows.map((r) => r.payload);
}
+/**
+ * Count restorable snapshot rows in SQLite without returning or parsing their message bodies in JS.
+ *
+ * The messages anti-join closes the crash window where the user row committed before the
+ * snapshot-delete write: restoreQueueSnapshot applies the same clientId de-duplication, so cold
+ * list_sessions counts cannot temporarily disagree with list_session_queue after restoration.
+ */
+export async function loadAgentInputQueueSnapshotCounts(
+ sessionIds: readonly string[],
+): Promise<Record<string, number>> {
+ const uniqueIds = [...new Set(sessionIds)];
+ const counts = Object.fromEntries(uniqueIds.map((sessionId) => [sessionId, 0]));
+ for (let offset = 0; offset < uniqueIds.length; offset += SNAPSHOT_COUNT_QUERY_BATCH_SIZE) {
+ const batch = uniqueIds.slice(offset, offset + SNAPSHOT_COUNT_QUERY_BATCH_SIZE);
+ if (batch.length === 0) continue;
+ const placeholders = batch.map(() => '?').join(', ');
+ const rows = await getDbClient().query<{
+ sessionId: string;
+ itemCount: number | null;
+ }>(
+ `SELECT snapshot.session_id AS sessionId,
+ CASE
+ WHEN json_valid(snapshot.payload) = 1 AND json_type(snapshot.payload) = 'array'
+ THEN (
+ SELECT COUNT(*)
+ FROM json_each(snapshot.payload) AS snapshot_item
+ WHERE CASE
+ WHEN snapshot_item.type = 'object'
+ THEN
+ json_type(snapshot_item.value, '$.clientId') = 'text'
+ AND length(json_extract(snapshot_item.value, '$.clientId')) > 0
+ AND json_type(snapshot_item.value, '$.text') = 'text'
+ AND json_type(snapshot_item.value, '$.persistedContent') = 'text'
+ AND json_type(snapshot_item.value, '$.chatMessage') = 'object'
+ AND json_type(snapshot_item.value, '$.createOpts') = 'object'
+ AND json_extract(snapshot_item.value, '$.createOpts.agentKind')
+ IN ('claude-code', 'codex', 'pi')
+ AND COALESCE(
+ json_extract(snapshot_item.value, '$.origin.kind'),
+ ''
+ ) <> 'scheduler'
+ ELSE 0
+ END
+ AND (
+ session.cleared_at IS NULL
+ OR (
+ json_type(snapshot_item.value, '$.hostAcceptedAtMs')
+ IN ('integer', 'real')
+ AND json_extract(snapshot_item.value, '$.hostAcceptedAtMs')
+ > session.cleared_at
+ AND json_extract(snapshot_item.value, '$.hostAcceptedAtMs')
+ <= 1.7976931348623157e308
+ )
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM messages
+ WHERE messages.session_id = snapshot.session_id
+ AND messages.client_id = json_extract(
+ snapshot_item.value,
+ '$.clientId'
+ )
+ )
+ )
+ ELSE NULL
+ END AS itemCount
+ FROM agent_input_queue_snapshots AS snapshot
+ JOIN sessions AS session ON session.id = snapshot.session_id
+ WHERE snapshot.session_id IN (${placeholders})`,
+ batch,
+ );
+ for (const row of rows) {
+ if (!Number.isSafeInteger(row.itemCount) || (row.itemCount ?? -1) < 0) {
+ // One malformed snapshot is session-local damage. Keep its fail-closed zero while
+ // preserving valid counts from the same list_sessions page; query failures still throw.
+ continue;
+ }
+ counts[row.sessionId] = row.itemCount!;
+ }
+ }
+ return counts;
+}
+
export function isRestorableQueuedMessage(value: unknown): value is AgentInputQueuedMessage {
if (!value || typeof value !== 'object') return false;
const msg = value as AgentInputQueuedMessage;
diff --git a/apps/desktop/src/main/localDb/client/__tests__/current.test.ts b/apps/desktop/src/main/localDb/client/__tests__/current.test.ts
new file mode 100644
index 0000000000..36d771d0e4
--- /dev/null
+++ b/apps/desktop/src/main/localDb/client/__tests__/current.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from 'vitest';
+
+import { isDbClientNotReadyError } from '../current.js';
+
+describe('current DbClient readiness', () => {
+ it.each([
+ new Error('DbClient not ready'),
+ new Error('localDb not ready: call ensureReady(userId) first'),
+ { code: 'HOST_NOT_READY', message: 'database owner unavailable' },
+ ])('classifies retryable database-owner gaps', (error) => {
+ expect(isDbClientNotReadyError(error)).toBe(true);
+ });
+
+ it('keeps ordinary storage failures internal', () => {
+ expect(isDbClientNotReadyError(new Error('storage read failed'))).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/localDb/client/current.ts b/apps/desktop/src/main/localDb/client/current.ts
index 47e40a16b4..35d8cbe1dc 100644
--- a/apps/desktop/src/main/localDb/client/current.ts
+++ b/apps/desktop/src/main/localDb/client/current.ts
@@ -18,6 +18,25 @@ export function getDbClient(): DbClient {
return current.client;
}
+/**
+ * Database ownership can be temporarily absent during startup, logout, and
+ * account switches. Keep every public boundary on one retryable classification
+ * while accepting the legacy localDb wording used by older call sites.
+ */
+export function isDbClientNotReadyError(error: unknown): boolean {
+ if (
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ error.code === 'HOST_NOT_READY'
+ ) {
+ return true;
+ }
+
+ const message = error instanceof Error ? error.message : String(error);
+ return /(?:localDb|DbClient) not ready/i.test(message);
+}
+
export function tryGetDbClient(): DbClient | null {
return current?.client ?? null;
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 9654511866..63a24c11b5 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentInputCoordinator } from '../agent-input-coordinator.js';
+import { rebuildSessionQueueItem } from '../sessionControlService.js';
import type {
AgentInputCoordinatorDeps,
AgentInputHostSendFailureCode,
@@ -170,6 +171,7 @@ function createHarness(opts?: {
}) {
let running = false;
let turnGeneration = 0;
+ let turnSessionIdentity: object = {};
let pendingInteraction = false;
let agentKind: AgentInputCreateOpts['agentKind'] | null = 'claude-code';
const projections: AgentInputProjection[] = [];
@@ -254,6 +256,7 @@ function createHarness(opts?: {
let hasAssistantProgressAfter:
((sessionId: string, userClientId: string) => Promise<boolean>) | null = null;
let loadQueueSnapshot: ((sessionId: string) => Promise<AgentInputQueuedMessage[]>) | null = null;
+ let loadClearBoundary: ((sessionId: string) => Promise<unknown>) | null = null;
let getPersistedClientIds:
((sessionId: string, clientIds: string[]) => Promise<Set<string>>) | undefined;
const persistQueueSnapshot =
@@ -284,6 +287,7 @@ function createHarness(opts?: {
supersedeRetriedUserTurn,
isTurnRunning: () => running,
getTurnGeneration: () => turnGeneration,
+ getTurnSessionIdentity: () => turnSessionIdentity,
reconcileTurnIdle,
hasPendingInteraction: () => pendingInteraction,
getAgentKind: () => agentKind,
@@ -317,6 +321,8 @@ function createHarness(opts?: {
onUserMessageRewritten,
emitProjection,
persistQueueSnapshot,
+ loadClearBoundary: (sessionId) =>
+ loadClearBoundary ? loadClearBoundary(sessionId) : Promise.resolve(null),
loadQueueSnapshot: (sessionId) =>
loadQueueSnapshot ? loadQueueSnapshot(sessionId) : Promise.resolve([]),
getPersistedClientIds: (sessionId, clientIds) =>
@@ -359,6 +365,12 @@ function createHarness(opts?: {
setTurnGeneration(value: number) {
turnGeneration = value;
},
+ getTurnSessionIdentity() {
+ return turnSessionIdentity;
+ },
+ setTurnSessionIdentity(value: object) {
+ turnSessionIdentity = value;
+ },
setPendingInteraction(value: boolean) {
pendingInteraction = value;
},
@@ -392,6 +404,9 @@ function createHarness(opts?: {
setLoadQueueSnapshot(fn: ((sessionId: string) => Promise<AgentInputQueuedMessage[]>) | null) {
loadQueueSnapshot = fn;
},
+ setLoadClearBoundary(fn: ((sessionId: string) => Promise<unknown>) | null) {
+ loadClearBoundary = fn;
+ },
setGetPersistedClientIds(
fn: ((sessionId: string, clientIds: string[]) => Promise<Set<string>>) | undefined,
) {
@@ -650,6 +665,48 @@ describe('AgentInputCoordinator trusted session reference snapshots', () => {
});
describe('AgentInputCoordinator send transaction', () => {
+ it('keeps a drained turn visible until vendor dispatch accepts it', async () => {
+ const h = createHarness();
+ const sid = 'inspection-pre-dispatch';
+ const gate = deferred<void>();
+ h.sendToAgent.mockImplementationOnce(async (sessionId, _message, _createOpts, sendOpts) => {
+ await gate.promise;
+ await persistQueuedUserMessage(sessionId, sendOpts);
+ h.setRunning(true);
+ return sendSuccess();
+ });
+
+ h.coordinator.enqueue(sid, makeItem('q-active', 'still preparing'));
+ await flush();
+
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([
+ expect.objectContaining({ queuedMessageId: 'q-active', position: 0, consuming: true }),
+ ]);
+
+ gate.resolve();
+ await flush();
+
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([]);
+ });
+
+ it('does not materialize coordinator state when checking an unrestored queue', async () => {
+ const h = createHarness();
+ const sid = 'inspection-unrestored';
+
+ expect(h.coordinator.getQueueInspectionIfRestored(sid)).toBeNull();
+ await h.coordinator.ensureQueueRestored(sid);
+ expect(h.coordinator.getQueueInspectionIfRestored(sid)).toEqual([]);
+ });
+
+ it('keeps live-but-unrestored queue inspection unknown without failing the whole page', () => {
+ const h = createHarness();
+ const sid = 'inspection-live-unrestored';
+ h.setRunning(true);
+ h.coordinator.enqueue(sid, makeItem('q-live', 'live'));
+
+ expect(h.coordinator.getQueueInspectionIfRestored(sid)).toBeUndefined();
+ });
+
it('silently keeps a queue head when dispatch races with an already running turn', async () => {
const h = createHarness();
const sid = 'send-session-running-race';
@@ -4878,6 +4935,196 @@ describe('AgentInputCoordinator stop and drain boundaries', () => {
});
describe('AgentInputCoordinator steer transaction', () => {
+ it('rejects a control steer when screening crosses into a new turn generation', async () => {
+ const h = createHarness();
+ const sid = 'control-steer-screening-turn-race';
+ const verdict = deferred<{ action: 'allow' }>();
+ h.setRunning(true);
+ h.setScreenUserMessage(vi.fn(() => verdict.promise));
+
+ const steerPromise = h.coordinator.steer(sid, makeItem('q-control', 'urgent'), {
+ fallbackToTurn: false,
+ expectedTurnSession: h.getTurnSessionIdentity(),
+ expectedTurnGeneration: 0,
+ });
+ await flush();
+ h.setTurnGeneration(1);
+ verdict.resolve({ action: 'allow' });
+
+ await expect(steerPromise).resolves.toBe(false);
+ expect(h.steerToAgent).not.toHaveBeenCalled();
+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();
+ expect(latestProjection(h.projections).steeringQueueClientIds).toEqual([]);
+ });
+
+ it('rejects a control steer when reference resolution crosses into a replacement Session', async () => {
+ const h = createHarness();
+ const sid = 'control-steer-reference-session-race';
+ const references = deferred<[]>();
+ const expectedSession = h.getTurnSessionIdentity();
+ h.setRunning(true);
+ h.resolveSessionReferences.mockImplementationOnce(() => references.promise);
+
+ const steerPromise = h.coordinator.steer(
+ sid,
+ makeItem('q-control', 'urgent', {
+ sessionRefs: [{ sessionId: 'referenced-session' }],
+ }),
+ {
+ fallbackToTurn: false,
+ expectedTurnSession: expectedSession,
+ expectedTurnGeneration: 0,
+ },
+ );
+ await flush();
+ h.setTurnSessionIdentity({});
+ references.resolve([]);
+
+ await expect(steerPromise).resolves.toBe(false);
+ expect(h.steerToAgent).not.toHaveBeenCalled();
+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();
+ expect(latestProjection(h.projections).steeringQueueClientIds).toEqual([]);
+ });
+
+ it('does not reconcile the replacement turn when the final identity fence rejects delivery', async () => {
+ const h = createHarness();
+ const sid = 'control-steer-final-identity-race';
+ const expectedSession = h.getTurnSessionIdentity();
+ h.setRunning(true);
+ h.steerToAgent.mockRejectedValueOnce(
+ new Error('[STALE_TURN] Session changed turns before steer delivery'),
+ );
+
+ await expect(
+ h.coordinator.steer(sid, makeItem('q-control', 'urgent'), {
+ fallbackToTurn: false,
+ expectedTurnSession: expectedSession,
+ expectedTurnGeneration: 0,
+ }),
+ ).resolves.toBe(false);
+
+ expect(h.steerToAgent).toHaveBeenCalledWith(
+ sid,
+ { type: 'user', content: 'urgent' },
+ expect.objectContaining({
+ expectedTurnSession: expectedSession,
+ expectedTurnGeneration: 0,
+ }),
+ );
+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();
+ expect(h.sendToAgent).not.toHaveBeenCalled();
+ });
+
+ it('shows a direct steer only while delivery remains reversible', async () => {
+ const h = createHarness();
+ const sid = 'inspection-direct-steer';
+ const gate = deferred<void>();
+ h.setRunning(true);
+ h.steerToAgent.mockImplementationOnce(() => gate.promise);
+
+ const steerPromise = h.coordinator.steer(sid, makeItem('q-direct', 'direct'));
+ await flush();
+
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([
+ expect.objectContaining({ queuedMessageId: 'q-direct', position: 0, consuming: true }),
+ ]);
+
+ gate.resolve();
+ await expect(steerPromise).resolves.toBe(true);
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([]);
+ });
+
+ it('keeps a queued steer in place and clears direct inspection state on failure', async () => {
+ const h = createHarness();
+ const sid = 'inspection-steer-order-and-failure';
+ const queuedGate = deferred<void>();
+ h.setRunning(true);
+ h.coordinator.enqueue(sid, makeItem('q-first', 'first'));
+ h.coordinator.enqueue(sid, makeItem('q-steer', 'steer'));
+ h.steerToAgent.mockImplementationOnce(() => queuedGate.promise);
+
+ const queuedSteer = h.coordinator.steer(sid, makeItem('q-steer', 'steer'), {
+ removeFromQueue: true,
+ });
+ await flush();
+ expect(
+ h.coordinator.getQueueInspection(sid).map((entry) => ({
+ id: entry.queuedMessageId,
+ consuming: entry.consuming,
+ })),
+ ).toEqual([
+ { id: 'q-first', consuming: false },
+ { id: 'q-steer', consuming: true },
+ ]);
+ queuedGate.resolve();
+ await expect(queuedSteer).resolves.toBe(true);
+
+ const directGate = deferred<void>();
+ h.steerToAgent.mockImplementationOnce(() => directGate.promise);
+ const directSteer = h.coordinator.steer(sid, makeItem('q-failing', 'failing'));
+ await flush();
+ expect(
+ h.coordinator
+ .getQueueInspection(sid)
+ .some((entry) => entry.queuedMessageId === 'q-failing'),
+ ).toBe(true);
+ directGate.reject(new Error('steer failed'));
+ await expect(directSteer).resolves.toBe(false);
+ expect(
+ h.coordinator
+ .getQueueInspection(sid)
+ .some((entry) => entry.queuedMessageId === 'q-failing'),
+ ).toBe(false);
+ });
+
+ it('does not leave a direct inspection row or start a fallback turn when control steer loses the active-turn race', async () => {
+ const h = createHarness();
+ const sid = 'inspection-control-steer-no-active-race';
+ h.setRunning(true);
+ h.steerToAgent.mockRejectedValueOnce(new Error('[NO_ACTIVE_TURN] Session has no active turn'));
+ h.reconcileTurnIdle.mockImplementationOnce(() => {
+ h.setRunning(false);
+ return true;
+ });
+
+ await expect(
+ h.coordinator.steer(sid, makeItem('q-control', 'urgent'), {
+ fallbackToTurn: false,
+ }),
+ ).resolves.toBe(false);
+
+ expect(h.sendToAgent).not.toHaveBeenCalled();
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([]);
+ expect(latestProjection(h.projections).steeringQueueClientIds).toEqual([]);
+ });
+
+ it('does not report a policy-blocked control steer as delivered', async () => {
+ const h = createHarness();
+ h.setScreenUserMessage(
+ vi.fn(
+ async () =>
+ ({
+ action: 'block',
+ ghostId: 'control-policy',
+ ghostName: 'Control policy',
+ reason: 'policy',
+ }) as const,
+ ),
+ );
+ const sid = 'inspection-control-steer-blocked';
+ h.setRunning(true);
+
+ await expect(
+ h.coordinator.steer(sid, makeItem('q-control-blocked', 'urgent'), {
+ fallbackToTurn: false,
+ }),
+ ).resolves.toBe(false);
+
+ expect(h.steerToAgent).not.toHaveBeenCalled();
+ expect(h.sendToAgent).not.toHaveBeenCalled();
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([]);
+ });
+
it('injects a Claude steer into the running turn without aborting it', async () => {
const h = createHarness(); // 默认 agentKind='claude-code'
const sid = 'claude-steer-same-turn';
@@ -5153,8 +5400,12 @@ describe('AgentInputCoordinator steer transaction', () => {
const steerPromise = h.coordinator.steer(sid, composer, { touchUserSend: true });
await flush();
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([
+ expect.objectContaining({ queuedMessageId: 'composer-1', consuming: true }),
+ ]);
h.coordinator.stop(sid);
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([]);
gate.reject(
new Error(
'Codex steer cancelled before acceptance; delivery uncertain (request already dispatched)',
@@ -5408,7 +5659,7 @@ describe('AgentInputCoordinator steer transaction', () => {
const ok = await h.coordinator.steer(sid, second, { removeFromQueue: true });
await flush();
- expect(ok).toBe(false);
+ expect(ok).toBe(true);
let projection = latestProjection(h.projections);
expect(projection.error).toBe('Failed to persist user message: db down');
expect(projection.recovery).toBeNull();
@@ -5437,7 +5688,7 @@ describe('AgentInputCoordinator steer transaction', () => {
const ok = await h.coordinator.steer(sid, second, { removeFromQueue: true });
await flush();
- expect(ok).toBe(false);
+ expect(ok).toBe(true);
h.coordinator.onTurnEvent(sid, 'error', 'terminal after persist failure');
await flush();
@@ -5459,7 +5710,7 @@ describe('AgentInputCoordinator steer transaction', () => {
h.coordinator.enqueue(sid, first);
await flush();
- await expect(h.coordinator.steer(sid, second, { removeFromQueue: true })).resolves.toBe(false);
+ await expect(h.coordinator.steer(sid, second, { removeFromQueue: true })).resolves.toBe(true);
await flush();
expect(h.steerToAgent).toHaveBeenCalledTimes(1);
@@ -5659,7 +5910,7 @@ describe('AgentInputCoordinator steer transaction', () => {
await persistStarted.promise;
h.coordinator.clearSession(sid);
persistFailed.resolve();
- await expect(steerPromise).resolves.toBe(false);
+ await expect(steerPromise).resolves.toBe(true);
await flush();
const projection = latestProjection(h.projections);
@@ -5900,6 +6151,353 @@ describe('AgentInputCoordinator steer transaction', () => {
expect(latestProjection(h.projections).pendingQueue.map((q) => q.clientId)).toEqual(['q-2']);
expect(mocks.createMessage).toHaveBeenCalledTimes(1);
});
+
+ it.each([
+ ['Stop', (h: ReturnType<typeof createHarness>, sid: string) => h.coordinator.stop(sid)],
+ [
+ 'session close',
+ (h: ReturnType<typeof createHarness>, sid: string) => h.coordinator.onSessionClosed(sid),
+ ],
+ ])(
+ 'persists a provider-accepted direct steer after %s clears its marker',
+ async (_boundaryName, closeBoundary) => {
+ const h = createHarness();
+ const sid = 'steer-provider-accepted-after-boundary';
+ const active = makeItem('q-1', 'active turn');
+ const composer = makeItem('composer-accepted', 'accepted after boundary');
+ const gate = deferred<void>();
+
+ h.setAgentKind('codex');
+ h.steerToAgent.mockImplementationOnce(() => gate.promise);
+
+ h.coordinator.enqueue(sid, active);
+ await flush();
+ const steerPromise = h.coordinator.steer(sid, composer, { touchUserSend: true });
+ await flush();
+
+ closeBoundary(h, sid);
+ expect(latestProjection(h.projections).steeringQueueClientIds).toEqual([]);
+
+ gate.resolve();
+ await expect(steerPromise).resolves.toBe(true);
+ await flush();
+
+ expect(mocks.createMessage).toHaveBeenNthCalledWith(
+ 2,
+ sid,
+ expect.objectContaining({
+ clientId: composer.clientId,
+ content: composer.persistedContent,
+ agentMeta: expect.objectContaining({ delivery: 'steer' }),
+ }),
+ expect.objectContaining({ shouldBroadcast: expect.any(Function) }),
+ );
+ expect(h.onUserMessageQueryable).toHaveBeenCalledWith(
+ sid,
+ expect.objectContaining({ clientId: composer.clientId }),
+ );
+ const state = (
+ h.coordinator as unknown as {
+ getState: (sessionId: string) => {
+ activeTurn: { item: AgentInputQueuedMessage | null } | null;
+ };
+ }
+ ).getState(sid);
+ expect(state.activeTurn?.item?.clientId).not.toBe(composer.clientId);
+
+ await expect(h.coordinator.steer(sid, composer)).resolves.toBe(true);
+ expect(h.steerToAgent).toHaveBeenCalledTimes(1);
+ expect(latestProjection(h.projections)).toMatchObject({
+ pendingQueue: [],
+ queuePaused: false,
+ steeringQueueClientIds: [],
+ });
+ },
+ );
+
+ it('removes a queued steer after Stop when the provider confirms acceptance late', async () => {
+ const h = createHarness();
+ const sid = 'queued-steer-provider-accepted-after-stop';
+ const active = makeItem('q-1', 'active turn');
+ const queued = makeItem('q-2', 'queued steer');
+ const gate = deferred<void>();
+
+ h.setAgentKind('codex');
+ h.steerToAgent.mockImplementationOnce(() => gate.promise);
+
+ h.coordinator.enqueue(sid, active);
+ await flush();
+ h.coordinator.enqueue(sid, queued);
+ await flush();
+ const steerPromise = h.coordinator.steer(sid, queued, { removeFromQueue: true });
+ await flush();
+
+ h.coordinator.stop(sid, { keepQueue: true, pauseQueue: true });
+ expect(latestProjection(h.projections).pendingQueue.map((item) => item.clientId)).toEqual([
+ queued.clientId,
+ ]);
+
+ gate.resolve();
+ await expect(steerPromise).resolves.toBe(true);
+ await flush();
+
+ expect(latestProjection(h.projections).pendingQueue).toEqual([]);
+ expect(mocks.createMessage).toHaveBeenNthCalledWith(
+ 2,
+ sid,
+ expect.objectContaining({
+ clientId: queued.clientId,
+ content: queued.persistedContent,
+ agentMeta: expect.objectContaining({ delivery: 'steer' }),
+ }),
+ expect.objectContaining({ shouldBroadcast: expect.any(Function) }),
+ );
+ });
+
+ it('does not let a stale steer failure clear a reused clientId in a new generation', async () => {
+ const h = createHarness();
+ const sid = 'steer-stale-generation-reused-client-id';
+ const oldTurn = makeItem('old-turn', 'old turn');
+ const newTurn = makeItem('new-turn', 'new turn');
+ const oldSteer = makeItem('reused-steer', 'old steer');
+ const newSteer = makeItem('reused-steer', 'new steer');
+ const oldGate = deferred<void>();
+ let newSteerSignal: AbortSignal | undefined;
+
+ h.setAgentKind('codex');
+ h.steerToAgent
+ .mockImplementationOnce(() => oldGate.promise)
+ .mockImplementationOnce(
+ (_sessionId, _message, sendOpts) =>
+ new Promise<void>((_resolve, reject) => {
+ newSteerSignal = sendOpts.signal;
+ if (sendOpts.signal?.aborted) {
+ reject(new Error('cancelled'));
+ return;
+ }
+ sendOpts.signal?.addEventListener('abort', () => reject(new Error('cancelled')), {
+ once: true,
+ });
+ }),
+ );
+
+ h.coordinator.enqueue(sid, oldTurn);
+ await flush();
+ const oldSteerPromise = h.coordinator.steer(sid, oldSteer, { touchUserSend: true });
+ await flush();
+
+ h.coordinator.clearSession(sid);
+ h.setRunning(false);
+ h.coordinator.enqueue(sid, newTurn);
+ await flush();
+ const newSteerPromise = h.coordinator.steer(sid, newSteer, { touchUserSend: true });
+ await flush();
+
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([
+ expect.objectContaining({
+ queuedMessageId: 'reused-steer',
+ content: 'new steer',
+ consuming: true,
+ }),
+ ]);
+ expect(newSteerSignal?.aborted).toBe(false);
+
+ oldGate.reject(new Error('[NO_ACTIVE_TURN] old generation failed late'));
+ await expect(oldSteerPromise).resolves.toBe(false);
+ await flush();
+
+ const currentState = (
+ h.coordinator as unknown as {
+ getState: (sessionId: string) => {
+ activeTurn: { item: AgentInputQueuedMessage | null } | null;
+ queueAbortPending: boolean;
+ };
+ }
+ ).getState(sid);
+ expect(currentState.activeTurn?.item?.clientId).toBe('new-turn');
+ expect(currentState.queueAbortPending).toBe(false);
+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();
+ expect(latestProjection(h.projections).steeringQueueClientIds).toEqual(['reused-steer']);
+ expect(latestProjection(h.projections).error).toBeNull();
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([
+ expect.objectContaining({
+ queuedMessageId: 'reused-steer',
+ content: 'new steer',
+ consuming: true,
+ }),
+ ]);
+ expect(newSteerSignal?.aborted).toBe(false);
+
+ h.coordinator.stop(sid);
+ await flush();
+
+ expect(newSteerSignal?.aborted).toBe(true);
+ await expect(newSteerPromise).resolves.toBe(false);
+ expect(latestProjection(h.projections).steeringQueueClientIds).toEqual([]);
+ });
+
+ it('does not let a superseded steer release a newer turn boundary in the same generation', async () => {
+ const h = createHarness();
+ const sid = 'steer-stale-request-token-reused-client-id';
+ const oldTurn = makeItem('old-turn', 'old turn');
+ const newTurn = makeItem('new-turn', 'new turn');
+ const oldSteer = makeItem('reused-steer', 'old steer');
+ const newSteer = makeItem('reused-steer', 'new steer');
+ const oldGate = deferred<void>();
+ const newGate = deferred<void>();
+
+ h.setAgentKind('codex');
+ h.steerToAgent
+ .mockImplementationOnce(() => oldGate.promise)
+ .mockImplementationOnce(() => newGate.promise);
+
+ h.coordinator.enqueue(sid, oldTurn);
+ await flush();
+ const oldSteerPromise = h.coordinator.steer(sid, oldSteer);
+ await flush();
+
+ h.coordinator.stop(sid);
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'done');
+ await flush();
+
+ h.coordinator.enqueue(sid, newTurn);
+ await flush();
+ const newSteerPromise = h.coordinator.steer(sid, newSteer);
+ await flush();
+
+ oldGate.reject(new Error('[NO_ACTIVE_TURN] superseded steer failed late'));
+ await expect(oldSteerPromise).resolves.toBe(false);
+ await flush();
+
+ const currentState = (
+ h.coordinator as unknown as {
+ getState: (sessionId: string) => {
+ activeTurn: { item: AgentInputQueuedMessage | null } | null;
+ };
+ }
+ ).getState(sid);
+ expect(currentState.activeTurn?.item?.clientId).toBe('new-turn');
+ expect(h.reconcileTurnIdle).not.toHaveBeenCalled();
+ expect(latestProjection(h.projections).steeringQueueClientIds).toEqual(['reused-steer']);
+
+ newGate.resolve();
+ await expect(newSteerPromise).resolves.toBe(true);
+ });
+
+ it('does not resurrect a delivery-uncertain steer after a same-generation replacement succeeds', async () => {
+ const h = createHarness();
+ const sid = 'steer-uncertain-superseded-same-generation';
+ const oldTurn = makeItem('old-turn', 'old turn');
+ const newTurn = makeItem('new-turn', 'new turn');
+ const oldSteer = makeItem('reused-steer', 'old steer');
+ const newSteer = makeItem('reused-steer', 'new steer');
+ const oldGate = deferred<void>();
+
+ h.setAgentKind('codex');
+ h.steerToAgent
+ .mockImplementationOnce(() => oldGate.promise)
+ .mockImplementationOnce(async () => {});
+
+ h.coordinator.enqueue(sid, oldTurn);
+ await flush();
+ const oldSteerPromise = h.coordinator.steer(sid, oldSteer);
+ await flush();
+
+ const generationBeforeStop = (
+ h.coordinator as unknown as {
+ getState: (sessionId: string) => { generation: number };
+ }
+ ).getState(sid).generation;
+ h.coordinator.stop(sid);
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'done');
+ await flush();
+
+ h.coordinator.enqueue(sid, newTurn);
+ await flush();
+ await expect(h.coordinator.steer(sid, newSteer)).resolves.toBe(true);
+ await flush();
+
+ oldGate.reject(
+ new Error(
+ 'Codex steer cancelled before acceptance; delivery uncertain (request already dispatched)',
+ ),
+ );
+ await expect(oldSteerPromise).resolves.toBe(false);
+ await flush();
+
+ const state = (
+ h.coordinator as unknown as {
+ getState: (sessionId: string) => {
+ generation: number;
+ activeTurn: { item: AgentInputQueuedMessage | null } | null;
+ };
+ }
+ ).getState(sid);
+ expect(state.generation).toBe(generationBeforeStop);
+ expect(state.activeTurn?.item?.text).toBe('new steer');
+ expect(latestProjection(h.projections)).toMatchObject({
+ pendingQueue: [],
+ queuePaused: false,
+ steeringQueueClientIds: [],
+ error: null,
+ });
+ });
+
+ it('cleans only the rejected steer when another request owns the same generation', async () => {
+ const h = createHarness();
+ const sid = 'steer-overlap-request-identity';
+ const active = makeItem('active-turn', 'active turn');
+ const firstSteer = makeItem('steer-a', 'first steer');
+ const secondSteer = makeItem('steer-b', 'second steer');
+ const firstGate = deferred<void>();
+
+ h.setAgentKind('codex');
+ h.steerToAgent.mockImplementationOnce(() => firstGate.promise);
+
+ h.coordinator.enqueue(sid, active);
+ await flush();
+ const firstSteerPromise = h.coordinator.steer(sid, firstSteer);
+ await flush();
+
+ const state = (
+ h.coordinator as unknown as {
+ getState: (sessionId: string) => {
+ generation: number;
+ steeringQueueClientIds: string[];
+ steeringRequestTokens: Map<string, symbol>;
+ directSteeringItems: AgentInputQueuedMessage[];
+ };
+ }
+ ).getState(sid);
+ const generation = state.generation;
+ const secondToken = Symbol('second-steer-request');
+ // Reproduce the late-callback window after a second request has acquired its own
+ // identity. Each request must settle only its clientId/token within this generation.
+ state.steeringQueueClientIds.push(secondSteer.clientId);
+ state.steeringRequestTokens.set(secondSteer.clientId, secondToken);
+ state.directSteeringItems.push(secondSteer);
+
+ firstGate.reject(new Error('first steer rejected'));
+ await expect(firstSteerPromise).resolves.toBe(false);
+ await flush();
+
+ expect(state.generation).toBe(generation);
+ expect(state.steeringQueueClientIds).toEqual([secondSteer.clientId]);
+ expect(state.steeringRequestTokens.has(firstSteer.clientId)).toBe(false);
+ expect(state.steeringRequestTokens.get(secondSteer.clientId)).toBe(secondToken);
+ expect(state.directSteeringItems.map((item) => item.clientId)).toEqual([
+ secondSteer.clientId,
+ ]);
+ expect(h.coordinator.getQueueInspection(sid)).toEqual([
+ expect.objectContaining({
+ queuedMessageId: secondSteer.clientId,
+ content: secondSteer.text,
+ consuming: true,
+ }),
+ ]);
+ });
});
describe('AgentInputCoordinator queue mutations', () => {
@@ -6185,6 +6783,57 @@ describe('AgentInputCoordinator crash-recovery queue snapshots (issue #761)', ()
expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual([]);
});
+ it('hydrates the durable clear boundary before restoring a crash snapshot', async () => {
+ const h = createHarness();
+ const sid = 'snapshot-durable-clear-boundary';
+ h.setLoadClearBoundary(async () => 2_000);
+ h.setLoadQueueSnapshot(async () => [
+ makeItem('pre-clear', 'stale', { hostAcceptedAtMs: 1_999 }),
+ makeItem('missing-receipt', 'also stale'),
+ makeItem('post-clear', 'fresh', { hostAcceptedAtMs: 2_001 }),
+ ]);
+
+ await h.coordinator.ensureQueueRestored(sid);
+ await flush();
+
+ const projection = latestProjection(h.projections);
+ expect(projection.clearBoundaryMs).toBe(2_000);
+ expect(projection.pendingQueue.map((item) => item.clientId)).toEqual(['post-clear']);
+ expect(projection.queuePaused).toBe(true);
+ expect(h.onDiscardedQueuedMessage).toHaveBeenCalledTimes(2);
+ expect(latestSnapshotClientIds(h.persistQueueSnapshot)).toEqual(['post-clear']);
+ });
+
+ it('keeps restore incomplete when the durable clear boundary cannot be read, then retries', async () => {
+ const h = createHarness();
+ const sid = 'snapshot-clear-boundary-retry';
+ let attempts = 0;
+ h.setLoadClearBoundary(async () => {
+ attempts += 1;
+ if (attempts === 1) throw new Error('session row unavailable');
+ return 3_000;
+ });
+ const loadQueueSnapshot = vi.fn(async () => [
+ makeItem('pre-clear', 'stale', { hostAcceptedAtMs: 2_999 }),
+ ]);
+ h.setLoadQueueSnapshot(loadQueueSnapshot);
+
+ await expect(h.coordinator.ensureQueueRestored(sid)).rejects.toThrow(
+ 'session row unavailable',
+ );
+ expect(h.coordinator.isQueueRestored(sid)).toBe(false);
+ expect(loadQueueSnapshot).not.toHaveBeenCalled();
+ expect(h.persistQueueSnapshot).not.toHaveBeenCalled();
+
+ await expect(h.coordinator.ensureQueueRestored(sid)).resolves.toBeUndefined();
+ await flush();
+ expect(attempts).toBe(2);
+ expect(loadQueueSnapshot).toHaveBeenCalledTimes(1);
+ expect(h.coordinator.isQueueRestored(sid)).toBe(true);
+ expect(h.coordinator.getProjection(sid).pendingQueue).toEqual([]);
+ expect(h.coordinator.getClearBoundaryMs(sid)).toBe(3_000);
+ });
+
it('restores a quiet session as a paused queue and only drains after explicit resume', async () => {
const h = createHarness();
const sid = 'snapshot-restore-paused';
@@ -7507,6 +8156,90 @@ describe('AgentInputCoordinator replaceQueuedMessage(Orca lead 排队消息修
).toBe('second-edited');
});
+ it.each([
+ ['JSON object', '{"action":"old"}', '{"action":"new"}'],
+ ['JSON array', '["old"]', '["new"]'],
+ ])(
+ 'session-origin %s 编辑后 provider 与重开历史共用新的 raw 正文',
+ async (_label, before, replacement) => {
+ const h = createHarness();
+ const sid = `replace-session-raw-${_label}`;
+ h.coordinator.enqueue(sid, makeItem('q-active', 'active'));
+ await flush();
+
+ const queued = makeItem('q-edited', before, {
+ persistedContent: before,
+ origin: {
+ kind: 'session',
+ senderSessionId: 'caller',
+ displayText: before,
+ },
+ });
+ h.coordinator.enqueue(sid, queued);
+ await flush();
+
+ expect(
+ h.coordinator.replaceQueuedMessage(
+ sid,
+ queued.clientId,
+ rebuildSessionQueueItem(queued, replacement),
+ ),
+ ).toBe(true);
+
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'done');
+ await flush();
+
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({
+ type: 'user',
+ content: replacement,
+ });
+ expect(
+ mocks.createMessage.mock.calls.find(
+ (call) => (call[1] as { clientId?: string }).clientId === queued.clientId,
+ )?.[1],
+ ).toMatchObject({
+ clientId: queued.clientId,
+ role: 'user',
+ content: replacement,
+ });
+ },
+ );
+
+ it('编辑保留主机接收时间,清空边界后的条目崩溃恢复时不会被误删', async () => {
+ const h = createHarness();
+ const sid = 'replace-after-clear';
+ await h.coordinator.ensureQueueRestored(sid);
+ h.setRunning(true);
+ h.coordinator.enqueue(sid, makeItem('q-1', 'before'));
+ await flush();
+
+ const projected = h.coordinator.getProjection(sid).pendingQueue[0];
+ const authoritative = h.coordinator.getQueueControlSnapshot(sid).pendingQueue[0];
+ expect(projected?.hostAcceptedAtMs).toBeUndefined();
+ expect(authoritative?.hostAcceptedAtMs).toEqual(expect.any(Number));
+
+ // 模拟旧调用方从脱敏投影重建整条消息。coordinator 的最终替换边界仍须
+ // 锚定首次 host receipt,避免编辑后持久化出一个无接收时间的快照。
+ expect(h.coordinator.replaceQueuedMessage(sid, 'q-1', makeItem('q-1', 'after'))).toBe(true);
+ await flush();
+ const snapshot = h.persistQueueSnapshot.mock.calls.at(-1)?.[1] ?? [];
+ const acceptedAtMs = authoritative?.hostAcceptedAtMs;
+ expect(snapshot[0]).toMatchObject({
+ clientId: 'q-1',
+ text: 'after',
+ hostAcceptedAtMs: acceptedAtMs,
+ });
+
+ const restarted = createHarness();
+ restarted.setLoadClearBoundary(async () => (acceptedAtMs ?? 1) - 1);
+ restarted.setLoadQueueSnapshot(async () => snapshot);
+ await restarted.coordinator.ensureQueueRestored(sid);
+ expect(restarted.coordinator.getProjection(sid).pendingQueue).toEqual([
+ expect.objectContaining({ clientId: 'q-1', text: 'after' }),
+ ]);
+ });
+
it('拒绝身份漂移与不存在的条目', async () => {
const h = createHarness();
const sid = 'replace-guards';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
index 1c76a9832a..b661c06a44 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/orcaTeamService.test.ts
@@ -198,7 +198,11 @@ function createDeps(overrides: Partial<OrcaTeamServiceDeps> = {}) {
} satisfies DispatchWorkerMessageResult;
}),
sendAutoBridgeToLead: vi.fn(async () => ({ accepted: true })),
- getSessionQueueSnapshot: vi.fn(async () => ({ pendingQueue: [], steeringClientIds: [] })),
+ getSessionQueueSnapshot: vi.fn(async () => ({
+ pendingQueue: [],
+ steeringClientIds: [],
+ consumingClientIds: [],
+ })),
removeQueuedMessage: vi.fn(() => true),
replaceQueuedMessage: vi.fn(() => true),
log: {
@@ -1559,6 +1563,7 @@ describe('OrcaTeamService worker queued message control', () => {
queuedItem('q-sched', { kind: 'scheduler', scheduleId: 's1', scheduleName: 'beat' }),
],
steeringClientIds: ['q-user'],
+ consumingClientIds: ['q-user'],
})),
});
@@ -1600,6 +1605,7 @@ describe('OrcaTeamService worker queued message control', () => {
getSessionQueueSnapshot: vi.fn(async () => ({
pendingQueue: [queuedItem('q-lead', leadOrigin)],
steeringClientIds: [],
+ consumingClientIds: [],
})),
replaceQueuedMessage,
});
@@ -1643,6 +1649,7 @@ describe('OrcaTeamService worker queued message control', () => {
queuedItem('q-consuming', leadOrigin),
],
steeringClientIds: ['q-consuming'],
+ consumingClientIds: ['q-consuming'],
})),
removeQueuedMessage,
replaceQueuedMessage,
@@ -1679,6 +1686,7 @@ describe('OrcaTeamService worker queued message control', () => {
getSessionQueueSnapshot: vi.fn(async () => ({
pendingQueue: [queuedItem('q-lead', leadOrigin)],
steeringClientIds: [],
+ consumingClientIds: [],
})),
removeQueuedMessage,
});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionActivityProjection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionActivityProjection.test.ts
new file mode 100644
index 0000000000..75e200ecb2
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionActivityProjection.test.ts
@@ -0,0 +1,141 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { projectSessionActivity } from '@cindy/maker-shared/session-activity';
+import {
+ createSessionActivityReader,
+ type PersistedSessionActivityFacts,
+} from '../sessionActivityProjection.js';
+
+function facts(
+ patch: Partial<PersistedSessionActivityFacts> = {},
+): PersistedSessionActivityFacts {
+ return {
+ status: 'active',
+ title: '任务',
+ startedAt: null,
+ endedAt: null,
+ clearedAt: null,
+ ...patch,
+ };
+}
+
+function setup(opts?: {
+ live?: ReturnType<typeof projectSessionActivity> | null;
+ persisted?: PersistedSessionActivityFacts | null;
+ terminal?: { status: 'error'; createdAt?: number };
+}) {
+ const deps = {
+ getLiveSnapshot: vi.fn(() => opts?.live ?? null),
+ getPersistedFacts: vi.fn(async () =>
+ opts && 'persisted' in opts ? (opts.persisted ?? null) : facts(),
+ ),
+ getLatestTerminal: vi.fn(async () => opts?.terminal),
+ };
+ return { deps, read: createSessionActivityReader(deps) };
+}
+
+describe('canonical session activity reader', () => {
+ it('uses the live Agent Island snapshot without consulting cold storage', async () => {
+ const live = projectSessionActivity({
+ sessionId: 'live',
+ recordStatus: 'active',
+ source: 'live',
+ livePhase: 'needs-interaction',
+ startedAtMs: 10,
+ lastActivityAtMs: 20,
+ currentActionSummary: '等待用户确认',
+ attention: true,
+ });
+ const { deps, read } = setup({ live });
+
+ await expect(read('live')).resolves.toBe(live);
+ expect(deps.getPersistedFacts).not.toHaveBeenCalled();
+ expect(deps.getLatestTerminal).not.toHaveBeenCalled();
+ });
+
+ it('projects a durable normal completion, record lifecycle and title workflow', async () => {
+ const { read } = setup({
+ persisted: facts({
+ status: 'archived',
+ title: '🚧#2804 会话控制面 · 待bot',
+ startedAt: 100,
+ endedAt: 200,
+ }),
+ });
+
+ await expect(read('completed')).resolves.toMatchObject({
+ sessionId: 'completed',
+ recordStatus: 'archived',
+ phase: 'completed',
+ source: 'persisted',
+ startedAtMs: 100,
+ lastActivityAtMs: 200,
+ currentActionSummary: '上次运行已正常结束',
+ attention: false,
+ workflow: {
+ key: 'awaiting-bot',
+ label: '待bot',
+ waitingOn: 'automation',
+ },
+ });
+ });
+
+ it('projects an error terminal without exposing its persisted body', async () => {
+ const { deps, read } = setup({
+ persisted: facts({ startedAt: 100, endedAt: 150, clearedAt: 80 }),
+ terminal: { status: 'error', createdAt: 175 },
+ });
+
+ await expect(read('failed')).resolves.toMatchObject({
+ phase: 'error',
+ lastActivityAtMs: 175,
+ currentActionSummary: '上次运行出错',
+ attention: true,
+ });
+ expect(deps.getLatestTerminal).toHaveBeenCalledWith('failed', 80);
+ });
+
+ it('marks a started turn beyond every durable close boundary as interrupted', async () => {
+ const { read } = setup({
+ persisted: facts({ startedAt: 300, endedAt: 200, clearedAt: 250 }),
+ });
+
+ await expect(read('interrupted')).resolves.toMatchObject({
+ phase: 'error',
+ startedAtMs: 300,
+ lastActivityAtMs: 300,
+ currentActionSummary: '上次运行未正常结束',
+ attention: true,
+ });
+ });
+
+ it('does not resurrect terminal state from before the clear boundary', async () => {
+ const { deps, read } = setup({
+ persisted: facts({
+ status: 'deleted',
+ title: '任务 · 等待外部系统',
+ startedAt: 100,
+ endedAt: 150,
+ clearedAt: 200,
+ }),
+ });
+
+ await expect(read('cleared')).resolves.toMatchObject({
+ recordStatus: 'deleted',
+ phase: 'idle',
+ attention: false,
+ currentActionSummary: null,
+ workflow: { key: 'title:等待外部系统' },
+ });
+ expect(deps.getLatestTerminal).toHaveBeenCalledWith('cleared', 200);
+ });
+
+ it('fails closed to an idle fallback when the session row disappears', async () => {
+ const { read } = setup({ persisted: null });
+ await expect(read('missing')).resolves.toMatchObject({
+ sessionId: 'missing',
+ phase: 'idle',
+ source: 'fallback',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts
new file mode 100644
index 0000000000..8134e83ad6
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionControlService.test.ts
@@ -0,0 +1,405 @@
+import { describe, expect, it, vi } from 'vitest';
+import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
+
+import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';
+import {
+ createSessionControlService,
+ rebuildSessionQueueItem,
+ sessionQueueOriginForDispatcher,
+} from '../sessionControlService.js';
+
+function deferred<T>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ const promise = new Promise<T>((res) => {
+ resolve = res;
+ });
+ return { promise, resolve };
+}
+
+function item(origin?: AgentInputQueuedMessage['origin']): AgentInputQueuedMessage {
+ return {
+ clientId: 'queued-1',
+ text: 'before',
+ persistedContent: 'before',
+ model: 'model',
+ effort: 'medium',
+ permissionMode: 'default',
+ workingDir: '/repo',
+ chatMessage: { clientId: 'queued-1', role: 'user', content: 'before' },
+ createOpts: {
+ agentKind: 'codex',
+ workingDir: '/repo',
+ model: 'model',
+ effort: 'medium',
+ permissionMode: 'default',
+ },
+ ...(origin ? { origin } : {}),
+ };
+}
+
+function setup(opts?: {
+ exists?: boolean;
+ live?: boolean;
+ running?: boolean;
+ steerSupported?: boolean;
+ steerAccepted?: boolean;
+ queueItem?: AgentInputQueuedMessage;
+}) {
+ const activity: SessionActivitySnapshot = {
+ sessionId: 'target',
+ phase: 'running' as const,
+ recordStatus: 'active' as const,
+ attention: false,
+ workflow: null,
+ source: 'live' as const,
+ startedAtMs: 1,
+ lastActivityAtMs: 2,
+ currentActionSummary: '正在思考',
+ turnGeneration: null,
+ gracefulStopState: 'none' as const,
+ };
+ const control = {
+ active: true,
+ turnGeneration: 3,
+ activeToolCount: 0,
+ pendingInteractionCount: 0,
+ gracefulStopState: 'none' as const,
+ };
+ const live = {
+ agentKind: 'codex' as const,
+ capabilities: { sameTurnSteer: { supported: opts?.steerSupported ?? true } },
+ isTurnRunning: vi.fn(() => opts?.running ?? true),
+ getTurnGeneration: vi.fn(() => 3),
+ requestGracefulStop: vi.fn(async () => ({
+ status: 'waiting-for-safe-point' as const,
+ turnGeneration: 3,
+ })),
+ getTurnControlSnapshot: vi.fn(() => control),
+ };
+ const getLiveSession = vi.fn<() => typeof live | null>(() =>
+ opts?.live === false ? null : live,
+ );
+ const queueItem =
+ opts?.queueItem ??
+ item({
+ kind: 'session',
+ senderSessionId: 'caller',
+ displayText: 'before',
+ });
+ const deps = {
+ sessionExists: vi.fn(async () => opts?.exists ?? true),
+ getLiveSession,
+ getSessionActivitySnapshot: vi.fn(async () => activity),
+ assertExternalInputAllowed: vi.fn(async () => undefined),
+ createQueuedMessage: vi.fn(
+ async ({
+ queuedMessageId,
+ callerSessionId,
+ message,
+ }: {
+ queuedMessageId: string;
+ callerSessionId: string;
+ message: string;
+ }) => ({
+ ...item({ kind: 'session', senderSessionId: callerSessionId, displayText: message }),
+ clientId: queuedMessageId,
+ chatMessage: { clientId: queuedMessageId, role: 'user' as const, content: message },
+ }),
+ ),
+ steerQueuedMessage: vi.fn(async () => opts?.steerAccepted ?? true),
+ getQueueSnapshot: vi.fn(async () => ({ pendingQueue: [queueItem], consumingClientIds: [] })),
+ replaceQueuedMessage: vi.fn(() => true),
+ removeQueuedMessage: vi.fn(() => true),
+ createId: vi.fn(() => 'steer-1'),
+ };
+ return { deps, live, service: createSessionControlService(deps) };
+}
+
+describe('session control domain service', () => {
+ it('marks ordinary send_to_session queue rows with the dispatcher identity', () => {
+ expect(
+ sessionQueueOriginForDispatcher({
+ dispatcherSessionId: 'caller',
+ message: 'follow-up',
+ }),
+ ).toEqual({
+ kind: 'session',
+ senderSessionId: 'caller',
+ displayText: 'follow-up',
+ });
+ const explicit = { kind: 'scheduler' as const, scheduleId: 's', scheduleName: 'nightly' };
+ expect(
+ sessionQueueOriginForDispatcher({
+ dispatcherSessionId: 'caller',
+ message: 'follow-up',
+ explicitOrigin: explicit,
+ }),
+ ).toBe(explicit);
+ });
+
+ it('shares queue lifecycle while enforcing sender ownership and preserving identity', async () => {
+ const { deps, service } = setup();
+ await expect(
+ service.updateQueuedMessage({
+ callerSessionId: 'caller',
+ targetSessionId: 'target',
+ queuedMessageId: 'queued-1',
+ message: 'after',
+ }),
+ ).resolves.toEqual({ ok: true, queuedMessageId: 'queued-1' });
+ expect(deps.replaceQueuedMessage).toHaveBeenCalledWith(
+ 'target',
+ 'queued-1',
+ expect.objectContaining({
+ clientId: 'queued-1',
+ text: 'after',
+ origin: expect.objectContaining({ displayText: 'after' }),
+ }),
+ );
+
+ const foreign = setup({
+ queueItem: item({ kind: 'session', senderSessionId: 'other', displayText: 'before' }),
+ });
+ await expect(
+ foreign.service.cancelQueuedMessage({
+ callerSessionId: 'caller',
+ targetSessionId: 'target',
+ queuedMessageId: 'queued-1',
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'NOT_AUTHORIZED' });
+ expect(foreign.deps.removeQueuedMessage).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['plain text', 'before', 'replacement'],
+ ['JSON object', '{"action":"old"}', '{"action":"new"}'],
+ ['JSON array', '["old"]', '["new"]'],
+ ])(
+ 'replaces session-origin %s as raw provider and persisted history text',
+ async (_label, before, replacement) => {
+ const queued = item({
+ kind: 'session',
+ senderSessionId: 'caller',
+ displayText: before,
+ });
+ queued.text = before;
+ queued.persistedContent = before;
+ queued.chatMessage.content = before;
+ const { deps, service } = setup({ queueItem: queued });
+
+ await expect(
+ service.updateQueuedMessage({
+ callerSessionId: 'caller',
+ targetSessionId: 'target',
+ queuedMessageId: 'queued-1',
+ message: replacement,
+ }),
+ ).resolves.toEqual({ ok: true, queuedMessageId: 'queued-1' });
+
+ expect(deps.replaceQueuedMessage).toHaveBeenCalledWith(
+ 'target',
+ 'queued-1',
+ expect.objectContaining({
+ text: replacement,
+ persistedContent: replacement,
+ chatMessage: expect.objectContaining({ content: replacement }),
+ origin: expect.objectContaining({ displayText: replacement }),
+ }),
+ );
+ },
+ );
+
+ it('keeps renderer composer envelopes intact when rebuilding a non-session queue item', () => {
+ const queued = item();
+ queued.persistedContent = JSON.stringify({
+ text: 'before',
+ images: [{ fileId: 'image-1' }],
+ files: [{ name: 'notes.txt', path: '/repo/notes.txt' }],
+ });
+
+ const updated = rebuildSessionQueueItem(queued, 'replacement');
+
+ expect(JSON.parse(updated.persistedContent)).toEqual({
+ text: 'replacement',
+ images: [{ fileId: 'image-1' }],
+ files: [{ name: 'notes.txt', path: '/repo/notes.txt' }],
+ slashCommandRanges: [],
+ });
+ });
+
+ it('steers only a live supported turn and never falls back after a terminal race', async () => {
+ const { deps, live, service } = setup();
+ await expect(
+ service.steerSession({
+ callerSessionId: 'caller',
+ targetSessionId: 'target',
+ message: 'urgent',
+ }),
+ ).resolves.toEqual({ ok: true, queuedMessageId: 'steer-1' });
+ expect(deps.assertExternalInputAllowed).toHaveBeenCalledWith('target');
+ expect(deps.createQueuedMessage).toHaveBeenCalledWith({
+ callerSessionId: 'caller',
+ targetSessionId: 'target',
+ queuedMessageId: 'steer-1',
+ message: 'urgent',
+ });
+ expect(deps.steerQueuedMessage).toHaveBeenCalledWith(
+ 'target',
+ expect.objectContaining({ clientId: 'steer-1' }),
+ { session: live, turnGeneration: 3 },
+ );
+
+ await expect(
+ setup({ running: false }).service.steerSession({
+ callerSessionId: 'caller',
+ targetSessionId: 'target',
+ message: 'urgent',
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'NO_ACTIVE_TURN' });
+ await expect(
+ setup({ steerSupported: false }).service.steerSession({
+ callerSessionId: 'caller',
+ targetSessionId: 'target',
+ message: 'urgent',
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'UNSUPPORTED_CAPABILITY' });
+
+ const raced = setup({ steerAccepted: false });
+ raced.live.isTurnRunning.mockReturnValueOnce(true).mockReturnValueOnce(false);
+ await expect(
+ raced.service.steerSession({
+ callerSessionId: 'caller',
+ targetSessionId: 'target',
+ message: 'urgent',
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'NO_ACTIVE_TURN' });
+ });
+
+ it('rejects when the original turn changes while the control message is being built', async () => {
+ const generationRace = setup();
+ const generationGate = deferred<AgentInputQueuedMessage>();
+ generationRace.deps.createQueuedMessage.mockImplementationOnce(() => generationGate.promise);
+ const generationResult = generationRace.service.steerSession({
+ callerSessionId: 'caller',
+ targetSessionId: 'target',
+ message: 'urgent',
+ });
+ while (generationRace.deps.createQueuedMessage.mock.calls.length === 0) {
+ await Promise.resolve();
+ }
+ generationRace.live.getTurnGeneration.mockReturnValue(4);
+ generationGate.resolve(item());
+ await expect(generationResult).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'NO_ACTIVE_TURN',
+ });
+ expect(generationRace.deps.steerQueuedMessage).not.toHaveBeenCalled();
+
+ const replacementRace = setup();
+ const replacement = {
+ ...replacementRace.live,
+ isTurnRunning: vi.fn(() => true),
+ getTurnGeneration: vi.fn(() => 3),
+ };
+ replacementRace.deps.createQueuedMessage.mockImplementationOnce(async () => {
+ replacementRace.deps.getLiveSession.mockReturnValue(replacement);
+ return item();
+ });
+ await expect(
+ replacementRace.service.steerSession({
+ callerSessionId: 'caller',
+ targetSessionId: 'target',
+ message: 'urgent',
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'NO_ACTIVE_TURN' });
+ expect(replacementRace.deps.steerQueuedMessage).not.toHaveBeenCalled();
+ });
+
+ it('merges canonical activity with live stop control without hard-abort semantics', async () => {
+ const { live, service } = setup();
+ await expect(service.stopSessionTurn({ targetSessionId: 'target' })).resolves.toEqual({
+ ok: true,
+ status: 'waiting-for-safe-point',
+ turnGeneration: 3,
+ });
+ expect(live.requestGracefulStop).toHaveBeenCalledOnce();
+ await expect(service.getSessionRuntime({ targetSessionId: 'target' })).resolves.toEqual({
+ ok: true,
+ runtime: expect.objectContaining({
+ phase: 'running',
+ currentActionSummary: '正在思考',
+ turnGeneration: 3,
+ gracefulStopState: 'none',
+ }),
+ });
+
+ const offline = setup();
+ offline.deps.getLiveSession.mockReturnValue(null);
+ offline.deps.getSessionActivitySnapshot.mockResolvedValue({
+ sessionId: 'target',
+ phase: 'completed',
+ recordStatus: 'archived',
+ startedAtMs: 1,
+ lastActivityAtMs: 2,
+ currentActionSummary: '上次运行已正常结束',
+ attention: false,
+ workflow: null,
+ turnGeneration: null,
+ gracefulStopState: 'none',
+ source: 'persisted',
+ });
+ await expect(offline.service.stopSessionTurn({ targetSessionId: 'target' })).resolves.toEqual({
+ ok: true,
+ status: 'no-active-turn',
+ });
+ await expect(offline.service.getSessionRuntime({ targetSessionId: 'target' })).resolves.toEqual(
+ {
+ ok: true,
+ runtime: expect.objectContaining({
+ phase: 'completed',
+ recordStatus: 'archived',
+ turnGeneration: null,
+ gracefulStopState: 'none',
+ }),
+ },
+ );
+ });
+
+ it('prefers an in-memory live session when persisted metadata is unavailable', async () => {
+ const { deps, live, service } = setup();
+ deps.sessionExists.mockRejectedValue(new Error('localDb not ready'));
+
+ await expect(service.stopSessionTurn({ targetSessionId: 'target' })).resolves.toEqual({
+ ok: true,
+ status: 'waiting-for-safe-point',
+ turnGeneration: 3,
+ });
+ expect(live.requestGracefulStop).toHaveBeenCalledOnce();
+ expect(deps.sessionExists).not.toHaveBeenCalled();
+ });
+
+ it('preserves metadata read failures when no live session can prove the target exists', async () => {
+ const { deps, service } = setup({ live: false });
+ const storageError = new Error('storage unavailable');
+ deps.sessionExists.mockRejectedValue(storageError);
+
+ await expect(service.stopSessionTurn({ targetSessionId: 'target' })).rejects.toBe(storageError);
+ });
+
+ it('returns NOT_FOUND before reading mutable target state', async () => {
+ const { deps, service } = setup({ exists: false, live: false });
+ await expect(
+ service.cancelQueuedMessage({
+ callerSessionId: 'caller',
+ targetSessionId: 'gone',
+ queuedMessageId: 'queued-1',
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'NOT_FOUND' });
+ await expect(service.stopSessionTurn({ targetSessionId: 'gone' })).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'NOT_FOUND',
+ });
+ expect(deps.getQueueSnapshot).not.toHaveBeenCalled();
+ expect(deps.getLiveSession).toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionQueueControl.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionQueueControl.test.ts
new file mode 100644
index 0000000000..4c79954689
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionQueueControl.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';
+import { createSessionQueueControlService } from '../sessionQueueControl.js';
+
+function queued(clientId = 'queued-1'): AgentInputQueuedMessage {
+ return {
+ clientId,
+ text: 'before',
+ persistedContent: 'before',
+ model: 'model',
+ effort: 'medium',
+ permissionMode: 'default',
+ workingDir: '/repo',
+ chatMessage: { clientId, role: 'user', content: 'before' },
+ createOpts: {
+ agentKind: 'pi',
+ workingDir: '/repo',
+ model: 'model',
+ effort: 'medium',
+ permissionMode: 'default',
+ },
+ };
+}
+
+describe('session queue control service', () => {
+ it('shares authorization, content rebuild and atomic replace for update', async () => {
+ const item = queued();
+ const replaceQueuedMessage = vi.fn(() => true);
+ const service = createSessionQueueControlService({
+ getSnapshot: vi.fn(async () => ({ pendingQueue: [item], consumingClientIds: [] })),
+ replaceQueuedMessage,
+ removeQueuedMessage: vi.fn(() => true),
+ });
+
+ await expect(
+ service.update({
+ sessionId: 'session-1',
+ queuedMessageId: item.clientId,
+ message: 'after',
+ authorize: () => ({ ok: true }),
+ rebuild: (entry, message) => ({
+ ...entry,
+ text: message,
+ persistedContent: message,
+ chatMessage: { ...entry.chatMessage, content: message },
+ }),
+ }),
+ ).resolves.toEqual({ ok: true, queuedMessageId: item.clientId });
+ expect(replaceQueuedMessage).toHaveBeenCalledWith(
+ 'session-1',
+ item.clientId,
+ expect.objectContaining({ text: 'after', persistedContent: 'after' }),
+ );
+ });
+
+ it('rejects consuming and unauthorized rows before mutation', async () => {
+ const item = queued();
+ const replaceQueuedMessage = vi.fn(() => true);
+ const removeQueuedMessage = vi.fn(() => true);
+ const consuming = createSessionQueueControlService({
+ getSnapshot: vi.fn(async () => ({
+ pendingQueue: [item],
+ consumingClientIds: [item.clientId],
+ })),
+ replaceQueuedMessage,
+ removeQueuedMessage,
+ });
+ await expect(
+ consuming.cancel({
+ sessionId: 'session-1',
+ queuedMessageId: item.clientId,
+ authorize: () => ({ ok: true }),
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MESSAGE_CONSUMING' });
+
+ const unauthorized = createSessionQueueControlService({
+ getSnapshot: vi.fn(async () => ({ pendingQueue: [item], consumingClientIds: [] })),
+ replaceQueuedMessage,
+ removeQueuedMessage,
+ });
+ await expect(
+ unauthorized.cancel({
+ sessionId: 'session-1',
+ queuedMessageId: item.clientId,
+ authorize: () => ({ ok: false, message: 'not yours' }),
+ }),
+ ).resolves.toEqual({ ok: false, errorCode: 'NOT_AUTHORIZED', message: 'not yours' });
+ expect(replaceQueuedMessage).not.toHaveBeenCalled();
+ expect(removeQueuedMessage).not.toHaveBeenCalled();
+ });
+
+ it('reclassifies a replace/remove race as consuming when dispatch won', async () => {
+ const item = queued();
+ const getSnapshot = vi
+ .fn()
+ .mockResolvedValueOnce({ pendingQueue: [item], consumingClientIds: [] })
+ .mockResolvedValueOnce({ pendingQueue: [], consumingClientIds: [item.clientId] });
+ const service = createSessionQueueControlService({
+ getSnapshot,
+ replaceQueuedMessage: vi.fn(() => false),
+ removeQueuedMessage: vi.fn(() => false),
+ });
+ await expect(
+ service.cancel({
+ sessionId: 'session-1',
+ queuedMessageId: item.clientId,
+ authorize: () => ({ ok: true }),
+ }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'MESSAGE_CONSUMING' });
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionQueueInspection.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionQueueInspection.test.ts
new file mode 100644
index 0000000000..6523ff0001
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionQueueInspection.test.ts
@@ -0,0 +1,225 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { AgentInputQueuedMessage } from '../../../shared/agentInputQueue.js';
+import {
+ projectSessionQueueForInspection,
+ resolveSessionQueueCounts,
+ type SessionQueueCountDeps,
+ type SessionQueueInspectionEntry,
+} from '../sessionQueueInspection.js';
+
+function queuedItem(
+ clientId: string,
+ overrides: Partial<AgentInputQueuedMessage> = {},
+): AgentInputQueuedMessage {
+ return {
+ clientId,
+ text: `text-${clientId}`,
+ persistedContent: `text-${clientId}`,
+ model: 'gpt-5.6',
+ effort: 'medium',
+ permissionMode: 'bypassPermissions',
+ workingDir: '/repo',
+ chatMessage: {
+ clientId,
+ role: 'user',
+ content: `text-${clientId}`,
+ createdAt: '2026-08-16T01:02:03.000Z',
+ },
+ createOpts: {
+ agentKind: 'codex',
+ workingDir: '/repo',
+ model: 'gpt-5.6',
+ },
+ ...overrides,
+ };
+}
+
+function inspectionEntry(queuedMessageId: string): SessionQueueInspectionEntry {
+ return {
+ queuedMessageId,
+ position: 0,
+ source: 'user',
+ sourceLabel: null,
+ enqueuedAtMs: null,
+ content: queuedMessageId,
+ consuming: false,
+ };
+}
+
+describe('projectSessionQueueForInspection', () => {
+ it('projects user, Orca, scheduler and session entries without leaking unrelated queue fields', () => {
+ const result = projectSessionQueueForInspection(
+ [
+ queuedItem('q-orca', {
+ hostAcceptedAtMs: Date.parse('2026-08-16T01:02:04.000Z'),
+ origin: { kind: 'orca', senderLabel: 'Worker', displayText: 'raw worker update' },
+ }),
+ queuedItem('q-user'),
+ queuedItem('q-scheduler', {
+ chatMessage: {
+ clientId: 'q-scheduler',
+ role: 'user',
+ content: 'scheduled',
+ createdAt: 'not-a-date',
+ },
+ origin: { kind: 'scheduler', scheduleId: 's-1', scheduleName: 'PR sweep' },
+ }),
+ queuedItem('q-session', {
+ origin: {
+ kind: 'session',
+ senderSessionId: 'sender-session',
+ displayText: 'safe session summary',
+ },
+ }),
+ ],
+ ['q-user'],
+ );
+
+ expect(result).toEqual([
+ {
+ queuedMessageId: 'q-orca',
+ position: 0,
+ source: 'orca',
+ sourceLabel: 'Worker',
+ enqueuedAtMs: Date.parse('2026-08-16T01:02:04.000Z'),
+ content: 'raw worker update',
+ consuming: false,
+ },
+ {
+ queuedMessageId: 'q-user',
+ position: 1,
+ source: 'user',
+ sourceLabel: null,
+ enqueuedAtMs: Date.parse('2026-08-16T01:02:03.000Z'),
+ content: 'text-q-user',
+ consuming: true,
+ },
+ {
+ queuedMessageId: 'q-scheduler',
+ position: 2,
+ source: 'scheduler',
+ sourceLabel: 'PR sweep',
+ enqueuedAtMs: null,
+ content: 'text-q-scheduler',
+ consuming: false,
+ },
+ {
+ queuedMessageId: 'q-session',
+ position: 3,
+ source: 'session',
+ sourceLabel: 'sender-session',
+ enqueuedAtMs: Date.parse('2026-08-16T01:02:03.000Z'),
+ content: 'safe session summary',
+ consuming: false,
+ },
+ ]);
+ });
+
+ it('keeps pre-dispatch and direct-steer items visible, ordered, and deduplicated', () => {
+ const active = queuedItem('q-active');
+ const direct = queuedItem('q-direct');
+ const pending = queuedItem('q-pending');
+
+ const result = projectSessionQueueForInspection([pending, direct], ['q-direct'], active, [
+ direct,
+ ]);
+
+ expect(
+ result.map(({ queuedMessageId, position, consuming }) => ({
+ queuedMessageId,
+ position,
+ consuming,
+ })),
+ ).toEqual([
+ { queuedMessageId: 'q-active', position: 0, consuming: true },
+ { queuedMessageId: 'q-direct', position: 1, consuming: true },
+ { queuedMessageId: 'q-pending', position: 2, consuming: false },
+ ]);
+ });
+
+ it('uses live counts when restored and lightweight persisted counts otherwise', async () => {
+ const loadPersistedCounts = vi.fn<SessionQueueCountDeps['loadPersistedCounts']>(
+ async () => ({ cold: 3, raced: 4 }),
+ );
+ let racedIsLive = false;
+ const getLiveQueue = vi.fn<SessionQueueCountDeps['getLiveQueue']>((sessionId) => {
+ if (sessionId === 'live') return [inspectionEntry('live-1'), inspectionEntry('live-2')];
+ if (sessionId === 'raced' && racedIsLive) return [inspectionEntry('raced-live')];
+ return null;
+ });
+ loadPersistedCounts.mockImplementationOnce(async (sessionIds) => {
+ expect(sessionIds).toEqual(['cold', 'raced']);
+ racedIsLive = true;
+ return { cold: 3, raced: 4 };
+ });
+
+ await expect(
+ resolveSessionQueueCounts(['live', 'cold', 'raced', 'live'], {
+ getLiveQueue,
+ loadPersistedCounts,
+ }),
+ ).resolves.toEqual({ live: 2, cold: 3, raced: 1 });
+ });
+
+ it('isolates a live session whose queue has not finished restoring', async () => {
+ const loadPersistedCounts = vi.fn<SessionQueueCountDeps['loadPersistedCounts']>(
+ async () => ({ cold: 3 }),
+ );
+
+ await expect(
+ resolveSessionQueueCounts(['live-unrestored', 'cold', 'live'], {
+ getLiveQueue: (sessionId) => {
+ if (sessionId === 'live-unrestored') return undefined;
+ if (sessionId === 'live') return [inspectionEntry('live-1')];
+ return null;
+ },
+ loadPersistedCounts,
+ }),
+ ).resolves.toEqual({ 'live-unrestored': 0, cold: 3, live: 1 });
+ expect(loadPersistedCounts).toHaveBeenCalledWith(['cold']);
+ });
+
+ it('isolates one live queue inspection failure without dropping healthy sessions', async () => {
+ const loadPersistedCounts = vi.fn<SessionQueueCountDeps['loadPersistedCounts']>(
+ async () => ({ cold: 3 }),
+ );
+
+ await expect(
+ resolveSessionQueueCounts(['broken-live', 'cold', 'healthy-live'], {
+ getLiveQueue: (sessionId) => {
+ if (sessionId === 'broken-live') throw new Error('coordinator unavailable');
+ if (sessionId === 'healthy-live') return [inspectionEntry('healthy-live-1')];
+ return null;
+ },
+ loadPersistedCounts,
+ }),
+ ).resolves.toEqual({ 'broken-live': 0, cold: 3, 'healthy-live': 1 });
+ expect(loadPersistedCounts).toHaveBeenCalledWith(['cold']);
+ });
+
+ it('does not reuse a persisted count when the live recheck fails after the DB read', async () => {
+ let reads = 0;
+ await expect(
+ resolveSessionQueueCounts(['raced-broken'], {
+ getLiveQueue: () => {
+ reads += 1;
+ if (reads === 1) return null;
+ throw new Error('live restore failed');
+ },
+ loadPersistedCounts: async () => ({ 'raced-broken': 4 }),
+ }),
+ ).resolves.toEqual({ 'raced-broken': 0 });
+ });
+
+ it('propagates persisted count failures instead of reporting zero', async () => {
+ await expect(
+ resolveSessionQueueCounts(['cold'], {
+ getLiveQueue: () => null,
+ loadPersistedCounts: async () => {
+ throw new Error('snapshot unavailable');
+ },
+ }),
+ ).rejects.toThrow('snapshot unavailable');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index fbb2b281a3..cc2b06bbae 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -65,6 +65,10 @@ import {
RECOVERY_CHECKPOINT_MARKER,
type RecoveryContextSnapshot,
} from './recoveryCoordinator.js';
+import {
+ projectSessionQueueForInspection,
+ type SessionQueueInspectionEntry,
+} from './sessionQueueInspection.js';
const log = createLogger('maker-input-coordinator');
const SESSION_RUNNING_RETRY_DELAY_MS = 250;
@@ -198,6 +202,10 @@ export interface AgentInputSendOpts {
expectedClearBoundaryMs?: number | null;
/** Main-owned input generation captured before async preparation. */
expectedInputGeneration?: number;
+ /** Main-owned Session identity for a control-plane same-turn steer. */
+ expectedTurnSession?: object;
+ /** Main-owned maker-core turn generation for a control-plane same-turn steer. */
+ expectedTurnGeneration?: number;
persistUserMessage?: {
clientId: string;
content: string;
@@ -260,6 +268,8 @@ export interface AgentInputCoordinatorDeps {
isTurnRunning: (sessionId: string) => boolean;
/** maker-core turn 代号;steer 跨 await 后据此验证仍属于开始时的同一 vendor turn。 */
getTurnGeneration?: (sessionId: string) => number | null;
+ /** maker-core Session object identity; control-plane steer uses it to reject session reuse. */
+ getTurnSessionIdentity?: (sessionId: string) => object | null;
/**
* Reconcile the host's live session/tracker view after an abort or a
* maker-core NO_ACTIVE_TURN. The event-driven tracker can stay stale when a
@@ -477,12 +487,14 @@ export interface AgentInputCoordinatorDeps {
/**
* 排队输入崩溃恢复(issue #761)。persistQueueSnapshot:队列内容变化时覆盖写
* 快照(items 为空 = 删行),实现方自行 fire-and-forget + 保序,绝不阻塞派发;
- * loadQueueSnapshot:ensureQueueRestored 懒恢复时读回。两者要么都注入要么都不注入。
+ * loadClearBoundary:ensureQueueRestored 恢复快照前先水合 durable /clear 边界;
+ * loadQueueSnapshot:随后读回快照。生产侧三者一起注入,任一读取失败都保持未恢复态。
*/
persistQueueSnapshot?: (
sessionId: string,
items: AgentInputQueuedMessage[],
) => void | Promise<void>;
+ loadClearBoundary?: (sessionId: string) => Promise<unknown>;
loadQueueSnapshot?: (sessionId: string) => Promise<AgentInputQueuedMessage[]>;
getPersistedClientIds?: (sessionId: string, clientIds: string[]) => Promise<Set<string>>;
}
@@ -544,6 +556,10 @@ interface SessionInputState {
pendingQueue: AgentInputQueuedMessage[];
pendingCompacts: PendingCompactRequest[];
steeringQueueClientIds: string[];
+ /** Identity of the currently owned steer transaction for each visible clientId. */
+ steeringRequestTokens: Map<string, symbol>;
+ /** Direct composer steers have no pendingQueue row while delivery is still reversible. */
+ directSteeringItems: AgentInputQueuedMessage[];
queuePaused: boolean;
/**
* 当前 queuePaused 是否来自崩溃快照恢复(restoreQueueSnapshot 的静默会话分支),
@@ -635,6 +651,8 @@ function createInitialInputState(
pendingQueue: [],
pendingCompacts: [],
steeringQueueClientIds: [],
+ steeringRequestTokens: new Map(),
+ directSteeringItems: [],
queuePaused: false,
queuePausedByRestore: false,
queueExpanded: false,
@@ -713,6 +731,11 @@ function isNoActiveTurnError(err: unknown): boolean {
return /\[NO_ACTIVE_TURN\]|no active .*turn|has no active turn/i.test(msg);
}
+function isStaleTurnError(err: unknown): boolean {
+ const msg = err instanceof Error ? err.message : String(err);
+ return /\[STALE_TURN\]/i.test(msg);
+}
+
/**
* steer 投递结果不确定(maker-core 的两类特征串):ack 超时 'did not acknowledge
* within',或 Stop/close 赢在 ack 返回前的 post-send abort 'delivery uncertain'。
@@ -840,6 +863,15 @@ function sendFailureLogFields(result: AgentInputSendFailure): Record<string, unk
export class AgentInputCoordinator {
private readonly states = new Map<string, SessionInputState>();
private readonly steerAbortControllers = new Map<string, Map<string, AbortController>>();
+ /**
+ * Stop clears visible steer markers before the provider promise necessarily settles. Retain
+ * the latest request identity until every older request with the same clientId has settled so
+ * a cancelled request cannot regain ownership after a replacement request has already won.
+ */
+ private readonly steerRequestLineages = new Map<
+ string,
+ Map<string, { latestToken: symbol; unsettledTokens: Set<symbol> }>
+ >();
/**
* One clear/stop-scoped cancellation boundary per session generation. The
* vendor adapters can spend time converting attachments after the final
@@ -881,6 +913,9 @@ export class AgentInputCoordinator {
for (const state of this.states.values()) {
if (state.pendingQueue.length > 0) texts.push(JSON.stringify(state.pendingQueue));
if (state.activeTurn?.item) texts.push(JSON.stringify(state.activeTurn.item));
+ if (state.directSteeringItems.length > 0) {
+ texts.push(JSON.stringify(state.directSteeringItems));
+ }
if (state.recovery) texts.push(JSON.stringify(state.recovery));
}
return texts;
@@ -890,6 +925,44 @@ export class AgentInputCoordinator {
return this.toProjection(sessionId, this.getState(sessionId));
}
+ /**
+ * Main-only control snapshot. Queue mutation services need the authoritative
+ * item rather than the renderer/device-link projection: projected rows omit
+ * host receipts and trusted reference context that edits must either retain
+ * or deliberately invalidate while rebuilding the message.
+ */
+ getQueueControlSnapshot(
+ sessionId: string,
+ ): Pick<AgentInputProjection, 'pendingQueue' | 'steeringQueueClientIds'> {
+ const state = this.getState(sessionId);
+ return {
+ pendingQueue: [...state.pendingQueue],
+ steeringQueueClientIds: [...state.steeringQueueClientIds],
+ };
+ }
+
+ /** Main-only inspection view for cindy_helper; never crosses renderer/device-link IPC. */
+ getQueueInspection(sessionId: string): SessionQueueInspectionEntry[] {
+ const state = this.getState(sessionId);
+ return this.projectQueueInspection(state);
+ }
+
+ /** Cold sessions return null for SQLite counting; live-but-unrestored sessions stay unknown. */
+ getQueueInspectionIfRestored(
+ sessionId: string,
+ ): SessionQueueInspectionEntry[] | null | undefined {
+ if (!this.isQueueRestored(sessionId)) {
+ // A cold session can be counted directly from SQLite. Once live state exists, however,
+ // combining it with an unread snapshot without clientIds could double-count or omit rows.
+ if (this.states.has(sessionId)) {
+ return undefined;
+ }
+ return null;
+ }
+ const state = this.states.get(sessionId);
+ return state ? this.projectQueueInspection(state) : [];
+ }
+
/**
* Capture/check the session input generation around IPC-side async
* preparation. clearSession replaces the state and increments this value;
@@ -973,6 +1046,18 @@ export class AgentInputCoordinator {
private async restoreQueueSnapshot(sessionId: string): Promise<void> {
const preState = this.getState(sessionId);
const preGeneration = preState.generation;
+ if (this.deps.loadClearBoundary) {
+ try {
+ const clearedAt = await this.deps.loadClearBoundary(sessionId);
+ this.observeClearBoundary(sessionId, clearedAt);
+ } catch (err) {
+ log.warn('load queue clear boundary failed; will retry on next entry', {
+ sessionId,
+ error: errorMessage(err),
+ });
+ throw err;
+ }
+ }
let items: AgentInputQueuedMessage[];
try {
items = (await this.deps.loadQueueSnapshot!(sessionId)).map(
@@ -1613,8 +1698,23 @@ export class AgentInputCoordinator {
async steer(
sessionId: string,
item: AgentInputQueuedMessage,
- opts?: { removeFromQueue?: boolean; touchUserSend?: boolean },
+ opts?: {
+ removeFromQueue?: boolean;
+ touchUserSend?: boolean;
+ /** 控制面插话不允许在 turn 结束竞态下退化成下一轮普通输入。 */
+ fallbackToTurn?: boolean;
+ /** 控制面初检捕获的 live Session 对象,防 session id 被新实例复用。 */
+ expectedTurnSession?: object;
+ /** 控制面初检捕获的 maker-core turn generation。 */
+ expectedTurnGeneration?: number;
+ },
): Promise<boolean> {
+ const matchesExpectedTurn = () =>
+ (opts?.expectedTurnSession === undefined ||
+ this.deps.getTurnSessionIdentity?.(sessionId) === opts.expectedTurnSession) &&
+ (opts?.expectedTurnGeneration === undefined ||
+ this.deps.getTurnGeneration?.(sessionId) === opts.expectedTurnGeneration);
+ if (!matchesExpectedTurn()) return false;
const state = this.getState(sessionId);
// Capture the clear boundary before any screening/reference/steer await. The
// live state may advance when `/clear` wins the race; this turn must retain
@@ -1697,6 +1797,7 @@ export class AgentInputCoordinator {
}
if (!this.isTurnSteerable(sessionId, state)) {
+ if (opts?.fallbackToTurn === false) return false;
this.fallbackPreparedAsTurn(sessionId, item, opts?.removeFromQueue === true);
if (opts?.touchUserSend) this.touchUserSend(sessionId);
return true;
@@ -1708,6 +1809,11 @@ export class AgentInputCoordinator {
const messageUuid = crypto.randomUUID();
const createdAt = new Date().toISOString();
const steerGeneration = state.generation;
+ const steerRequestToken = this.beginSteerRequest(sessionId, item.clientId);
+ const finishSteerRequest = (result: boolean): boolean => {
+ this.settleSteerRequest(sessionId, item.clientId, steerRequestToken);
+ return result;
+ };
// steer ack 期间原 turn 可能先收到 terminal 事件并清掉 activeTurn。owner 是本次
// 注入开始时就已确定的 vendor-turn 身份,必须在 await 前快照,不能等 ack 后再从
// 可能已经清空的 activeTurn 读取。
@@ -1718,6 +1824,13 @@ export class AgentInputCoordinator {
if (!state.steeringQueueClientIds.includes(item.clientId)) {
state.steeringQueueClientIds.push(item.clientId);
}
+ state.steeringRequestTokens.set(item.clientId, steerRequestToken);
+ if (!steersStoredQueueItem) {
+ state.directSteeringItems = [
+ ...state.directSteeringItems.filter((entry) => entry.clientId !== item.clientId),
+ item,
+ ];
+ }
const steerAbort = new AbortController();
const inputBoundarySignal = this.getInputAbortSignal(sessionId, steerGeneration);
this.registerSteerAbortController(sessionId, item.clientId, steerAbort);
@@ -1735,18 +1848,38 @@ export class AgentInputCoordinator {
item,
);
const cur = this.getState(sessionId);
- if (!cur.steeringQueueClientIds.includes(item.clientId)) {
+ const ownsCurrentRequest = this.isCurrentSteerRequest(
+ cur,
+ item.clientId,
+ steerGeneration,
+ steerRequestToken,
+ );
+ if (
+ !ownsCurrentRequest ||
+ !matchesExpectedTurn()
+ ) {
// stop/close/clearSession 赢在筛查期间:steer 事务已被取消,静默放弃。
- this.clearSteerAbortController(sessionId, item.clientId);
- return false;
+ if (
+ ownsCurrentRequest &&
+ this.clearSteeringMarker(cur, item.clientId, {
+ generation: steerGeneration,
+ token: steerRequestToken,
+ })
+ ) {
+ this.clearDirectSteeringItem(cur, item.clientId);
+ this.emit(sessionId);
+ }
+ this.clearSteerAbortController(sessionId, item.clientId, steerAbort);
+ return finishSteerRequest(false);
}
if (verdict.action === 'block') {
// 拦截即终态:不注入、不落库,气泡由 onUserMessageBlocked 广播降级;
// 返回 true(已处置),renderer 不再回滚重试。
- this.clearSteerAbortController(sessionId, item.clientId);
- cur.steeringQueueClientIds = cur.steeringQueueClientIds.filter(
- (id) => id !== item.clientId,
- );
+ this.clearSteerAbortController(sessionId, item.clientId, steerAbort);
+ this.clearSteeringMarker(cur, item.clientId, {
+ generation: steerGeneration,
+ token: steerRequestToken,
+ });
if (opts?.removeFromQueue) {
cur.pendingQueue = cur.pendingQueue.filter((q) => q.clientId !== item.clientId);
this.removePendingCompactWaitClientId(cur, item.clientId);
@@ -1758,7 +1891,9 @@ export class AgentInputCoordinator {
this.deps.onDiscardedQueuedMessage?.(sessionId, item);
this.emit(sessionId);
this.scheduleDrain(sessionId, 'steer-ghost-blocked');
- return true;
+ // 普通 UI steer 的 true 表示“已处置”,避免 renderer 把被策略拦截的内容
+ // 重新入队;控制面要求严格的 same-turn 投递结果,不能把 blocked 报成成功。
+ return finishSteerRequest(opts?.fallbackToTurn === false ? false : true);
}
if (verdict.action === 'rewrite') {
// 与 drain 的 rewrite 同构:JSON-aware 只换 text 字段并保留附件信封;
@@ -1783,6 +1918,20 @@ export class AgentInputCoordinator {
try {
const referenceContexts = await this.resolveReferenceContexts(item);
+ if (!matchesExpectedTurn()) {
+ const latest = this.getState(sessionId);
+ if (
+ this.clearSteeringMarker(latest, item.clientId, {
+ generation: steerGeneration,
+ token: steerRequestToken,
+ })
+ ) {
+ this.clearDirectSteeringItem(latest, item.clientId);
+ this.emit(sessionId);
+ }
+ this.clearSteerAbortController(sessionId, item.clientId, steerAbort);
+ return finishSteerRequest(false);
+ }
item.persistedContent = attachSessionReferenceMetadata(
item.persistedContent,
referenceContexts,
@@ -1793,18 +1942,54 @@ export class AgentInputCoordinator {
signal: AbortSignal.any([inputBoundarySignal, steerAbort.signal]),
expectedClearBoundaryMs: steerClearBoundaryMs,
expectedInputGeneration: steerGeneration,
+ ...(opts?.expectedTurnSession !== undefined
+ ? { expectedTurnSession: opts.expectedTurnSession }
+ : {}),
+ ...(opts?.expectedTurnGeneration !== undefined
+ ? { expectedTurnGeneration: opts.expectedTurnGeneration }
+ : {}),
// 同 drain:steer 投递也在入队时的 async context 之外。
...(item.fromMobileClient ? { fromMobileClient: true } : {}),
});
} catch (err) {
- this.clearSteerAbortController(sessionId, item.clientId);
const latest = this.getState(sessionId);
- const markerStillPresent = latest.steeringQueueClientIds.includes(item.clientId);
- latest.steeringQueueClientIds = latest.steeringQueueClientIds.filter(
- (id) => id !== item.clientId,
- );
+ if (latest.generation !== steerGeneration) {
+ // clearSession owns the replacement state. The old callback may only release its own
+ // controller; it must not alter the replacement generation or Stop boundary.
+ this.clearSteerAbortController(sessionId, item.clientId, steerAbort);
+ log.info('ignoring stale steer completion after input generation changed', {
+ sessionId,
+ clientId: item.clientId,
+ steerGeneration,
+ currentGeneration: latest.generation,
+ });
+ return finishSteerRequest(false);
+ }
+ const markerStillPresent = this.clearSteeringMarker(latest, item.clientId, {
+ generation: steerGeneration,
+ token: steerRequestToken,
+ });
+ this.clearSteerAbortController(sessionId, item.clientId, steerAbort);
+
+ if (isStaleTurnError(err)) {
+ if (markerStillPresent) {
+ this.clearDirectSteeringItem(latest, item.clientId);
+ this.emit(sessionId);
+ }
+ return finishSteerRequest(false);
+ }
if (isNoActiveTurnError(err)) {
+ if (!markerStillPresent) {
+ // Stop/close owns the abort boundary after clearing this marker. Its token-guarded
+ // reconciliation path is the only code allowed to release that lock.
+ log.info('steer no-active-turn after marker cancelled (stop/close raced)', {
+ sessionId,
+ clientId: item.clientId,
+ });
+ this.emit(sessionId);
+ return finishSteerRequest(false);
+ }
// maker-core 权威判定无活跃 turn — 先让 host 校准可能 stale 的 busy
// tracker, 否则下面 fallback / drain 仍会被假忙挡住 (见 deps 注释)。
this.deps.reconcileTurnIdle?.(sessionId);
@@ -1820,23 +2005,19 @@ export class AgentInputCoordinator {
});
this.onTurnEvent(sessionId, 'done');
}
- if (!markerStillPresent) {
- log.info('steer no-active-turn after marker cancelled (stop/close raced)', {
- sessionId,
- clientId: item.clientId,
- });
- this.releaseAbortLockAndDrain(sessionId, 'steer-no-active-cancelled');
- this.emit(sessionId);
- return false;
- }
log.info('steer fallback to normal turn dispatch (no active turn)', {
sessionId,
clientId: item.clientId,
});
+ if (opts?.fallbackToTurn === false) {
+ this.clearDirectSteeringItem(latest, item.clientId);
+ this.emit(sessionId);
+ return finishSteerRequest(false);
+ }
this.emit(sessionId);
this.fallbackPreparedAsTurn(sessionId, item, opts?.removeFromQueue === true);
if (opts?.touchUserSend) this.touchUserSend(sessionId);
- return true;
+ return finishSteerRequest(true);
}
log.warn('steer hard failure', {
@@ -1870,11 +2051,18 @@ export class AgentInputCoordinator {
// 不确定投递的保护性暂停必须由用户显式处置,不许新输入静默放行。
latest.queuePausedByRestore = false;
}
- } else if (isSteerDeliveryUncertainError(err) && latest.generation === steerGeneration) {
+ } else if (
+ isSteerDeliveryUncertainError(err) &&
+ latest.generation === steerGeneration &&
+ (steerVendorTurnGeneration === null ||
+ this.deps.getTurnGeneration?.(sessionId) === steerVendorTurnGeneration) &&
+ this.isLatestSteerRequest(sessionId, item.clientId, steerRequestToken)
+ ) {
// Stop/close 赢在 ack 返回前(marker 已被 stop 清):RPC 已发出,结果同样
// 不确定,消息必须有落点(尤其 composer 入口无队列行的场景,review #939
- // 第四轮)。物化进暂停队列交用户处置。generation 守卫:clearSession 是
- // 用户显式重置,不把消息塞回已清空的会话。
+ // 第四轮)。只有本请求仍是该 clientId 的最新身份时才物化;同 generation
+ // 内的后续请求一旦取代它,迟到结果不得复活旧消息或暂停新队列。
+ // generation 守卫:clearSession 是用户显式重置,不把消息塞回已清空的会话。
this.prependQueueHeadIfMissing(latest, item);
latest.queuePaused = true;
// 同上:不确定投递的保护性暂停,不许新输入静默放行。
@@ -1886,22 +2074,73 @@ export class AgentInputCoordinator {
}
this.emit(sessionId);
this.scheduleDrain(sessionId, 'steer-hard-failure');
- return false;
+ return finishSteerRequest(false);
}
- this.clearSteerAbortController(sessionId, item.clientId);
-
const accepted = this.getState(sessionId);
- if (!accepted.steeringQueueClientIds.includes(item.clientId)) {
- log.warn(
- 'steer accepted by agent but marker already cancelled (stop/close raced); dropping',
- {
+ const ownsCurrentSteerMarker = this.isCurrentSteerRequest(
+ accepted,
+ item.clientId,
+ steerGeneration,
+ steerRequestToken,
+ );
+ if (!ownsCurrentSteerMarker) {
+ this.clearSteerAbortController(sessionId, item.clientId, steerAbort);
+ if (
+ accepted.generation !== steerGeneration ||
+ accepted.clearBoundaryMs !== steerClearBoundaryMs
+ ) {
+ // Provider acceptance is still irreversible, so report success instead of inviting a
+ // duplicate retry. A concurrent clear owns the replacement generation and intentionally
+ // prevents the accepted row from being reintroduced into cleared history.
+ log.info('steer accepted after session clear; preserving cleared replacement state', {
sessionId,
clientId: item.clientId,
- },
- );
+ steerGeneration,
+ currentGeneration: accepted.generation,
+ });
+ return finishSteerRequest(true);
+ }
+
+ // Stop/close clears the visible marker and direct item before the provider promise must
+ // settle. A resolved provider call has crossed the irreversible boundary nonetheless:
+ // persist it and remember the clientId without rebuilding activeTurn or releasing the
+ // Stop/close boundary that now owns the session lifecycle.
+ this.clearDirectSteeringItem(accepted, item.clientId);
+ this.rememberEnqueuedClientId(accepted, item.clientId);
+ if (opts?.removeFromQueue) {
+ accepted.pendingQueue = accepted.pendingQueue.filter(
+ (queued) => queued.clientId !== item.clientId,
+ );
+ this.removePendingCompactWaitClientId(accepted, item.clientId);
+ accepted.queueEditLocks = accepted.queueEditLocks.filter((id) => id !== item.clientId);
+ if (accepted.pendingQueue.length === 0) accepted.queuePaused = false;
+ }
+ const detachedAcceptedTurn: ActiveTurn = {
+ item,
+ delivery: 'steer',
+ messageUuid,
+ createdAt,
+ generation: steerGeneration,
+ clearBoundaryMs: steerClearBoundaryMs,
+ persisted: false,
+ persisting: true,
+ sendStarted: true,
+ dispatchLifecycle: 'dispatched',
+ pendingTerminalEvent: null,
+ continuationOwnerClientId: null,
+ };
+ const persisted = await this.persistAcceptedUserMessage(sessionId, detachedAcceptedTurn);
+ if (opts?.touchUserSend && persisted === 'persisted') this.touchUserSend(sessionId);
+ log.info('steer accepted after marker cancellation; persisted without reopening boundary', {
+ sessionId,
+ clientId: item.clientId,
+ persisted,
+ });
this.emit(sessionId);
- return false;
+ return finishSteerRequest(true);
}
+ this.clearDirectSteeringItem(accepted, item.clientId);
+ this.clearSteerAbortController(sessionId, item.clientId, steerAbort);
// steerToAgent has crossed the irreversible delivery boundary. Keep the
// clientId known even if the subsequent user-row persistence or terminal
// event fails, otherwise an ACK-loss retry can inject the same text twice.
@@ -1948,20 +2187,29 @@ export class AgentInputCoordinator {
const persisted = await this.persistAcceptedUserMessage(sessionId, accepted.activeTurn);
const settled = this.getState(sessionId);
let releasedSteerMarker = false;
- if (settled.generation === steerGeneration) {
- const remainingSteeringClientIds = settled.steeringQueueClientIds.filter(
- (id) => id !== item.clientId,
- );
- releasedSteerMarker =
- remainingSteeringClientIds.length !== settled.steeringQueueClientIds.length;
+ if (
+ this.isCurrentSteerRequest(
+ settled,
+ item.clientId,
+ steerGeneration,
+ steerRequestToken,
+ )
+ ) {
+ releasedSteerMarker = this.clearSteeringMarker(settled, item.clientId, {
+ generation: steerGeneration,
+ token: steerRequestToken,
+ });
if (releasedSteerMarker) {
- settled.steeringQueueClientIds = remainingSteeringClientIds;
this.emit(sessionId);
}
}
if (persisted !== 'persisted') {
if (releasedSteerMarker) this.scheduleDrain(sessionId, 'steer-persistence-settled');
- return false;
+ // Provider 已确认接收后就是不可逆投递边界。落库失败仍保留上面的 sticky
+ // error,但不能向调用方报告“未投递”诱导它用新 clientId 重发,造成模型
+ // 在同一 turn 内消费两份。accepted clientId 已在 rememberEnqueuedClientId
+ // 登记,原 id 的幂等重试也会直接收口。
+ return finishSteerRequest(true);
}
if (opts?.touchUserSend) this.touchUserSend(sessionId);
// 已投递收口(review #939 第二轮 P1):steer ack 可能与 turn 终态乱序——
@@ -2000,7 +2248,7 @@ export class AgentInputCoordinator {
this.clearSessionRunningRetry(accepted);
}
this.scheduleDrain(sessionId, 'steer-accepted');
- return true;
+ return finishSteerRequest(true);
}
stop(
@@ -2062,7 +2310,7 @@ export class AgentInputCoordinator {
const abortBoundaryToken = Symbol('agent-input-abort-boundary');
const abortBoundaryGeneration = state.generation;
state.abortBoundaryToken = abortBoundaryToken;
- state.steeringQueueClientIds = [];
+ this.clearAllSteeringMarkers(state);
state.queueExpanded = false;
this.emit(sessionId);
@@ -2526,8 +2774,8 @@ export class AgentInputCoordinator {
}
/**
- * 整条排队消息原位替换(main 侧受信调用方专用;当前唯一消费者是 Orca lead 的
- * 「修改排队消息」工具)。与 updateText / updateContent 的差别:替换体由调用方
+ * 整条排队消息原位替换(main 侧受信调用方专用;Orca lead 与会话控制面共用)。
+ * 与 updateText / updateContent 的差别:替换体由调用方
* 全量构造 —— orca 条目的 text / persistedContent / origin.displayText 之间存在
* 派发格式耦合(formatAgentMessage / formatOrcaCommunicationMessage),必须由
* dispatcher 侧按原格式重建,coordinator 不理解也不该理解该格式。
@@ -2545,8 +2793,17 @@ export class AgentInputCoordinator {
if (state.steeringQueueClientIds.includes(clientId)) return false;
const index = state.pendingQueue.findIndex((q) => q.clientId === clientId);
if (index < 0) return false;
+ const current = state.pendingQueue[index];
+ if (!current) return false;
+ // The receipt is stamped by this host at first acceptance and is not part
+ // of public projections. Never let an edit erase or forge the clear/restart
+ // recovery boundary even if a future caller accidentally rebuilds from a
+ // projected row again.
+ const replacement = { ...next };
+ if (current.hostAcceptedAtMs === undefined) delete replacement.hostAcceptedAtMs;
+ else replacement.hostAcceptedAtMs = current.hostAcceptedAtMs;
const nextQueue = [...state.pendingQueue];
- nextQueue[index] = next;
+ nextQueue[index] = replacement;
state.pendingQueue = nextQueue;
this.emit(sessionId);
return true;
@@ -2903,18 +3160,70 @@ export class AgentInputCoordinator {
}
state.queueAbortPending = false;
state.abortBoundaryToken = null;
- state.steeringQueueClientIds = [];
+ this.clearAllSteeringMarkers(state);
this.emit(sessionId);
return;
}
state.activeTurn = null;
state.queueAbortPending = false;
state.abortBoundaryToken = null;
- state.steeringQueueClientIds = [];
+ this.clearAllSteeringMarkers(state);
this.emit(sessionId);
if (releasedAbortLock) this.scheduleDrain(sessionId, 'session-closed-abort-boundary');
}
+ private projectQueueInspection(state: SessionInputState): SessionQueueInspectionEntry[] {
+ const activeItem =
+ state.activeTurn?.item && !isActiveTurnDispatched(state.activeTurn)
+ ? state.activeTurn.item
+ : null;
+ return projectSessionQueueForInspection(
+ state.pendingQueue,
+ state.steeringQueueClientIds,
+ activeItem,
+ state.directSteeringItems,
+ );
+ }
+
+ private isCurrentSteerRequest(
+ state: SessionInputState,
+ clientId: string,
+ generation: number,
+ token: symbol,
+ ): boolean {
+ return state.generation === generation && state.steeringRequestTokens.get(clientId) === token;
+ }
+
+ private clearSteeringMarker(
+ state: SessionInputState,
+ clientId: string,
+ expected?: { generation: number; token: symbol },
+ ): boolean {
+ if (
+ expected &&
+ !this.isCurrentSteerRequest(state, clientId, expected.generation, expected.token)
+ ) {
+ return false;
+ }
+ const existed = state.steeringQueueClientIds.includes(clientId);
+ state.steeringQueueClientIds = state.steeringQueueClientIds.filter((id) => id !== clientId);
+ state.steeringRequestTokens.delete(clientId);
+ this.clearDirectSteeringItem(state, clientId);
+ return existed;
+ }
+
+ private clearDirectSteeringItem(state: SessionInputState, clientId: string): void {
+ state.directSteeringItems = state.directSteeringItems.filter(
+ (item) => item.clientId !== clientId,
+ );
+ }
+
+ private clearAllSteeringMarkers(state: SessionInputState): void {
+ state.steeringQueueClientIds = [];
+ state.steeringRequestTokens.clear();
+ state.directSteeringItems = [];
+ }
+
private getState(sessionId: string): SessionInputState {
let state = this.states.get(sessionId);
if (!state) {
@@ -4117,9 +4426,7 @@ export class AgentInputCoordinator {
this.abandonActiveTurnRecoveryForUserAction(state);
this.clearErrorUnlessQueueHeadBlocked(state, item.clientId);
state.queuePaused = false;
- state.steeringQueueClientIds = state.steeringQueueClientIds.filter(
- (id) => id !== item.clientId,
- );
+ this.clearSteeringMarker(state, item.clientId);
state.queueEditLocks = state.queueEditLocks.filter((id) => id !== item.clientId);
this.movePreparedItemToQueueFront(state, item, removeFromQueue);
this.emit(sessionId);
@@ -4312,9 +4619,14 @@ export class AgentInputCoordinator {
byClientId.set(clientId, controller);
}
- private clearSteerAbortController(sessionId: string, clientId: string): void {
+ private clearSteerAbortController(
+ sessionId: string,
+ clientId: string,
+ expectedController?: AbortController,
+ ): void {
const byClientId = this.steerAbortControllers.get(sessionId);
if (!byClientId) return;
+ if (expectedController && byClientId.get(clientId) !== expectedController) return;
byClientId.delete(clientId);
if (byClientId.size === 0) this.steerAbortControllers.delete(sessionId);
}
@@ -4329,6 +4641,39 @@ export class AgentInputCoordinator {
this.steerAbortControllers.delete(sessionId);
}
+ private beginSteerRequest(sessionId: string, clientId: string): symbol {
+ const token = Symbol('agent-input-steer-request');
+ let byClientId = this.steerRequestLineages.get(sessionId);
+ if (!byClientId) {
+ byClientId = new Map();
+ this.steerRequestLineages.set(sessionId, byClientId);
+ }
+ const existing = byClientId.get(clientId);
+ if (existing) {
+ existing.latestToken = token;
+ existing.unsettledTokens.add(token);
+ } else {
+ byClientId.set(clientId, { latestToken: token, unsettledTokens: new Set([token]) });
+ }
+ return token;
+ }
+
+ private isLatestSteerRequest(sessionId: string, clientId: string, token: symbol): boolean {
+ return this.steerRequestLineages.get(sessionId)?.get(clientId)?.latestToken === token;
+ }
+
+ private settleSteerRequest(sessionId: string, clientId: string, token: symbol): void {
+ const byClientId = this.steerRequestLineages.get(sessionId);
+ const lineage = byClientId?.get(clientId);
+ if (!byClientId || !lineage) return;
+ lineage.unsettledTokens.delete(token);
+ // Keep latestToken as a tombstone while an older callback is still pending. Otherwise a
+ // replacement that settles first would make the old request look current again.
+ if (lineage.unsettledTokens.size > 0) return;
+ byClientId.delete(clientId);
+ if (byClientId.size === 0) this.steerRequestLineages.delete(sessionId);
+ }
+
private touchUserSend(sessionId: string, atMs?: number): void {
void touchUserSendInDb(sessionId, atMs).catch((err) => {
log.warn('touchUserSend failed', { sessionId, error: errorMessage(err) });
diff --git a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts
index b27a381d61..d08d18c1dd 100644
--- a/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts
+++ b/apps/desktop/src/main/maker-ipc/mobileClientPromptNote.ts
@@ -144,6 +144,8 @@ export function stripMainOnlySendOpts(sendOpts: unknown): unknown {
if (
!('fromMobileClient' in opts) &&
!('expectedInputGeneration' in opts) &&
+ !('expectedTurnSession' in opts) &&
+ !('expectedTurnGeneration' in opts) &&
!('inputAbortSignal' in opts) &&
!('signal' in opts)
) {
@@ -152,6 +154,8 @@ export function stripMainOnlySendOpts(sendOpts: unknown): unknown {
const {
fromMobileClient: _ignoredMobile,
expectedInputGeneration: _ignoredGeneration,
+ expectedTurnSession: _ignoredTurnSession,
+ expectedTurnGeneration: _ignoredTurnGeneration,
inputAbortSignal: _ignoredAbortSignal,
signal: _ignoredSignal,
...rest
diff --git a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
index d3db595d18..d109e1cac2 100644
--- a/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
+++ b/apps/desktop/src/main/maker-ipc/orcaTeamService.ts
@@ -8,6 +8,7 @@ import type {
CollabDispatchSuccessOutcome,
} from './collabSendOutcome.js';
import { rebuildQueuedOrcaLeadMessage } from './orcaInterAgentDispatcher.js';
+import { createSessionQueueControlService } from './sessionQueueControl.js';
/**
* OrcaTeamService 只接管已存在 worker 的派活、释放、归档与 auto-bridge。
@@ -220,6 +221,7 @@ export interface OrcaTeamServiceDeps {
getSessionQueueSnapshot(sessionId: string): Promise<{
pendingQueue: AgentInputQueuedMessage[];
steeringClientIds: string[];
+ consumingClientIds: string[];
}>;
/** 从队列移除一条排队消息;实现方必须走 coordinator.remove(带 discard settle)。返回是否真的移除。 */
removeQueuedMessage(sessionId: string, clientId: string): boolean;
@@ -301,6 +303,17 @@ export function findFocusTargetWorker<
export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamService {
const autoBridge = new Map<string, AutoBridgeState>();
+ const queueControl = createSessionQueueControlService({
+ getSnapshot: async (sessionId) => {
+ const snapshot = await deps.getSessionQueueSnapshot(sessionId);
+ return {
+ pendingQueue: snapshot.pendingQueue,
+ consumingClientIds: snapshot.consumingClientIds,
+ };
+ },
+ replaceQueuedMessage: deps.replaceQueuedMessage,
+ removeQueuedMessage: deps.removeQueuedMessage,
+ });
/** Per-worker transition tails serialize dispatch reservations against implicit done acknowledgement. */
const workerTransitionTails = new Map<string, Promise<void>>();
/** Active dispatch count stays positive from pre-resume reservation through host dispatch settlement. */
@@ -828,51 +841,6 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
return 'user';
}
- /**
- * update / cancel 共用的目标定位与权限校验:worker 归属(resolveWorkerRef)→
- * 条目存在 → 必须是 lead 自己的 orca 条目(用户 / scheduler 排队消息绝不可动)→
- * 未进入 steering 投递。全部通过才返回条目与 link。
- */
- async function resolveLeadQueuedMessage(params: {
- callerLeadSessionId: string;
- workerRef: string;
- queuedMessageId: string;
- }): Promise<
- | { ok: true; link: OrcaWorkerLinkSnapshot; entry: AgentInputQueuedMessage }
- | { ok: false; errorCode: WorkerQueuedMessageFailureCode; message: string }
- > {
- const found = await resolveWorkerRef(params.callerLeadSessionId, params.workerRef);
- if (!found.ok) {
- return found.errorCode === 'NOT_FOUND'
- ? { ok: false, errorCode: 'WORKER_NOT_FOUND', message: `worker ${params.workerRef} not found` }
- : { ok: false, errorCode: 'INTERNAL', message: found.message };
- }
- const snapshot = await deps.getSessionQueueSnapshot(found.worker.sessionId);
- const entry = snapshot.pendingQueue.find((item) => item.clientId === params.queuedMessageId);
- if (!entry) {
- return {
- ok: false,
- errorCode: 'QUEUED_MESSAGE_NOT_FOUND',
- message: `queued message ${params.queuedMessageId} not found — it may have been dispatched or cancelled already`,
- };
- }
- if (entry.origin?.kind !== 'orca') {
- return {
- ok: false,
- errorCode: 'NOT_LEAD_MESSAGE',
- message: `queued message ${params.queuedMessageId} was not sent by the lead; user/scheduler queued messages cannot be modified`,
- };
- }
- if (snapshot.steeringClientIds.includes(entry.clientId)) {
- return {
- ok: false,
- errorCode: 'MESSAGE_CONSUMING',
- message: `queued message ${params.queuedMessageId} is being delivered and can no longer be modified`,
- };
- }
- return { ok: true, link: found.link, entry };
- }
-
async function listWorkerQueuedMessages(params: {
callerLeadSessionId: string;
workerRef: string;
@@ -896,7 +864,7 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
position: index,
source,
content,
- consuming: snapshot.steeringClientIds.includes(item.clientId),
+ consuming: snapshot.consumingClientIds.includes(item.clientId),
};
});
return {
@@ -913,31 +881,36 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
queuedMessageId: string;
message: string;
}): Promise<WorkerQueuedMessageControlResult> {
- if (params.message.trim().length === 0) {
- return { ok: false, errorCode: 'INVALID_ARGS', message: 'message must not be empty' };
- }
- const resolved = await resolveLeadQueuedMessage(params);
- if (!resolved.ok) return resolved;
- const next = rebuildQueuedOrcaLeadMessage(resolved.entry, params.message, resolved.link.workerId);
- const replaced = deps.replaceQueuedMessage(
- resolved.link.workerSessionId,
- params.queuedMessageId,
- next,
- );
- if (!replaced) {
- // resolve 与 replace 之间的窄竞态:条目刚被 drain 取走 / steering 挡住。
- return {
- ok: false,
- errorCode: 'QUEUED_MESSAGE_NOT_FOUND',
- message: `queued message ${params.queuedMessageId} was consumed before the update could apply`,
- };
+ const found = await resolveWorkerRef(params.callerLeadSessionId, params.workerRef);
+ if (!found.ok) {
+ return found.errorCode === 'NOT_FOUND'
+ ? {
+ ok: false,
+ errorCode: 'WORKER_NOT_FOUND',
+ message: `worker ${params.workerRef} not found`,
+ }
+ : { ok: false, errorCode: 'INTERNAL', message: found.message };
}
+ const controlled = await queueControl.update({
+ sessionId: found.worker.sessionId,
+ queuedMessageId: params.queuedMessageId,
+ message: params.message,
+ authorize: (entry) =>
+ entry.origin?.kind === 'orca'
+ ? { ok: true }
+ : {
+ ok: false,
+ message: `queued message ${params.queuedMessageId} was not sent by the lead; user/scheduler queued messages cannot be modified`,
+ },
+ rebuild: (entry, message) => rebuildQueuedOrcaLeadMessage(entry, message, found.worker.id),
+ });
+ if (!controlled.ok) return mapWorkerQueueControlFailure(controlled);
deps.log.info('orca lead updated queued worker message', {
- workerId: resolved.link.workerId,
- workerSessionId: resolved.link.workerSessionId,
+ workerId: found.worker.id,
+ workerSessionId: found.worker.sessionId,
queuedMessageId: params.queuedMessageId,
});
- return { ok: true, workerId: resolved.link.workerId, queuedMessageId: params.queuedMessageId };
+ return { ok: true, workerId: found.worker.id, queuedMessageId: params.queuedMessageId };
}
async function cancelWorkerQueuedMessage(params: {
@@ -945,26 +918,50 @@ export function createOrcaTeamService(deps: OrcaTeamServiceDeps): OrcaTeamServic
workerRef: string;
queuedMessageId: string;
}): Promise<WorkerQueuedMessageControlResult> {
- const resolved = await resolveLeadQueuedMessage(params);
- if (!resolved.ok) return resolved;
- // coordinator.remove 内部触发 onDiscardedQueuedMessage → dispatcher 丢弃该
- // clientId 的 accepted 暂存回调,与 Stop 清队列共用同一条 settle 路径
- // (架构文档「queued accepted 也要同样结算」不变量);queued 未 accepted,
- // 无运行副作用需要回滚。
- const removed = deps.removeQueuedMessage(resolved.link.workerSessionId, params.queuedMessageId);
- if (!removed) {
- return {
- ok: false,
- errorCode: 'QUEUED_MESSAGE_NOT_FOUND',
- message: `queued message ${params.queuedMessageId} was consumed before the cancel could apply`,
- };
+ const found = await resolveWorkerRef(params.callerLeadSessionId, params.workerRef);
+ if (!found.ok) {
+ return found.errorCode === 'NOT_FOUND'
+ ? {
+ ok: false,
+ errorCode: 'WORKER_NOT_FOUND',
+ message: `worker ${params.workerRef} not found`,
+ }
+ : { ok: false, errorCode: 'INTERNAL', message: found.message };
}
+ // coordinator.remove 仍负责 discard settle;公共 service 只统一定位、授权与竞态分类。
+ const controlled = await queueControl.cancel({
+ sessionId: found.worker.sessionId,
+ queuedMessageId: params.queuedMessageId,
+ authorize: (entry) =>
+ entry.origin?.kind === 'orca'
+ ? { ok: true }
+ : {
+ ok: false,
+ message: `queued message ${params.queuedMessageId} was not sent by the lead; user/scheduler queued messages cannot be modified`,
+ },
+ });
+ if (!controlled.ok) return mapWorkerQueueControlFailure(controlled);
deps.log.info('orca lead cancelled queued worker message', {
- workerId: resolved.link.workerId,
- workerSessionId: resolved.link.workerSessionId,
+ workerId: found.worker.id,
+ workerSessionId: found.worker.sessionId,
queuedMessageId: params.queuedMessageId,
});
- return { ok: true, workerId: resolved.link.workerId, queuedMessageId: params.queuedMessageId };
+ return { ok: true, workerId: found.worker.id, queuedMessageId: params.queuedMessageId };
+ }
+
+ function mapWorkerQueueControlFailure(failure: {
+ ok: false;
+ errorCode: string;
+ message: string;
+ }): WorkerQueuedMessageControlResult {
+ return {
+ ok: false,
+ errorCode:
+ failure.errorCode === 'NOT_AUTHORIZED'
+ ? 'NOT_LEAD_MESSAGE'
+ : (failure.errorCode as WorkerQueuedMessageFailureCode),
+ message: failure.message,
+ };
}
async function closeWorkerSessionBestEffort(sessionId: string, owner: string): Promise<void> {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 4da2ac984c..11f86f6a2d 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -143,6 +143,15 @@ import {
} from '../computer-permission-guide/window.js';
import { parseComputerPermissionGrantRequest } from '../computer-permission-guide/request.js';
import { shouldUseComputerPermissionGuide } from './computerPermissionGuideEligibility.js';
+import {
+ resolveSessionQueueCounts,
+ type SessionQueueInspectionEntry,
+} from './sessionQueueInspection.js';
+import {
+ createSessionControlService,
+ sessionQueueOriginForDispatcher,
+} from './sessionControlService.js';
+import { readCanonicalSessionActivity } from './sessionActivityProjection.js';
import {
listAtBrowserTabs,
parseAtContextCatalogRequest,
@@ -157,11 +166,15 @@ import {
import * as imageCacheStore from '../imageCacheStore.js';
import * as cindyChatAttachments from '../cindy-media/chatAttachments.js';
import { materializeGeneratedImage } from '../cindy-media/generatedMedia.js';
-import { getDbClient } from '../localDb/client/current.js';
+import {
+ getDbClient,
+ isDbClientNotReadyError,
+} from '../localDb/client/current.js';
import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';
import {
awaitAgentInputQueueSnapshotPersistence,
loadAgentInputQueueSnapshot,
+ loadAgentInputQueueSnapshotCounts,
saveAgentInputQueueSnapshot,
} from '../localDb/agentInputQueueSnapshots.js';
import {
@@ -1446,6 +1459,8 @@ type SendToSessionInternalResult =
wakeKind: 'resumed' | 'already-active' | 'created' | 'queued';
targetTitle: string | null;
targetLastUserSendAt: string | null;
+ /** jump 排队时的可寻址句柄;直发 / create 时省略。 */
+ queuedMessageId?: string;
/** create + useWorktree 成功时为新 session 的 worktree 绝对路径;其余情况 undefined。 */
worktreePath?: string | null;
model?: string;
@@ -1476,6 +1491,93 @@ type SendToSessionInternalResult =
/** 暴露给 xdt-helper MCP provider 的协同控制面,必须复用 IPC 同源业务路径。 */
interface OrcaCollabService {
+ listSessionQueue: (sessionId: string) => Promise<
+ | { ok: true; messages: SessionQueueInspectionEntry[] }
+ | { ok: false; errorCode: 'NOT_FOUND' | 'HOST_NOT_READY' | 'INTERNAL'; message: string }
+ >;
+ listSessionQueuedCounts: (sessionIds: string[]) => Promise<
+ | { ok: true; counts: Record<string, number> }
+ | { ok: false; errorCode: 'HOST_NOT_READY' | 'INTERNAL'; message: string }
+ >;
+ updateSessionQueuedMessage: (params: {
+ callerSessionId: string;
+ targetSessionId: string;
+ queuedMessageId: string;
+ message: string;
+ }) => Promise<
+ | { ok: true; queuedMessageId: string }
+ | {
+ ok: false;
+ errorCode:
+ | 'NOT_FOUND'
+ | 'QUEUED_MESSAGE_NOT_FOUND'
+ | 'MESSAGE_CONSUMING'
+ | 'NOT_AUTHORIZED'
+ | 'INVALID_ARGS'
+ | 'HOST_NOT_READY'
+ | 'INTERNAL';
+ message: string;
+ }
+ >;
+ cancelSessionQueuedMessage: (params: {
+ callerSessionId: string;
+ targetSessionId: string;
+ queuedMessageId: string;
+ }) => Promise<
+ | { ok: true; queuedMessageId: string }
+ | {
+ ok: false;
+ errorCode:
+ | 'NOT_FOUND'
+ | 'QUEUED_MESSAGE_NOT_FOUND'
+ | 'MESSAGE_CONSUMING'
+ | 'NOT_AUTHORIZED'
+ | 'INVALID_ARGS'
+ | 'HOST_NOT_READY'
+ | 'INTERNAL';
+ message: string;
+ }
+ >;
+ steerSession: (params: {
+ callerSessionId: string;
+ targetSessionId: string;
+ message: string;
+ }) => Promise<
+ | { ok: true; queuedMessageId: string }
+ | {
+ ok: false;
+ errorCode:
+ | 'NOT_FOUND'
+ | 'NO_ACTIVE_TURN'
+ | 'UNSUPPORTED_CAPABILITY'
+ | 'INPUT_LOCKED'
+ | 'DELIVERY_FAILED'
+ | 'HOST_NOT_READY'
+ | 'INTERNAL';
+ message: string;
+ }
+ >;
+ stopSessionTurn: (params: { targetSessionId: string }) => Promise<
+ | {
+ ok: true;
+ status: 'no-active-turn' | 'waiting-for-safe-point' | 'requested' | 'unconfirmed';
+ turnGeneration?: number;
+ reason?: string;
+ }
+ | {
+ ok: false;
+ errorCode: 'NOT_FOUND' | 'UNSUPPORTED_CAPABILITY' | 'HOST_NOT_READY' | 'INTERNAL';
+ message: string;
+ }
+ >;
+ getSessionRuntime: (params: { targetSessionId: string }) => Promise<
+ | { ok: true; runtime: Awaited<ReturnType<typeof readCanonicalSessionActivity>> }
+ | {
+ ok: false;
+ errorCode: 'NOT_FOUND' | 'HOST_NOT_READY' | 'INTERNAL';
+ message: string;
+ }
+ >;
sendToSession: (params: {
/** 省略 → create 新 session;提供 → jump 到该既有 session。 */
targetSessionId?: string;
@@ -8006,6 +8108,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
createDefaults,
inheritSourcePermissionMode,
} = params;
+ const queuedOrigin = sessionQueueOriginForDispatcher({
+ dispatcherSessionId,
+ message,
+ explicitOrigin: origin,
+ });
if (!message) {
return {
ok: false,
@@ -8345,13 +8452,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
dbRow,
onAccepted,
onAcceptedRollback,
- origin,
+ origin: queuedOrigin,
});
return {
ok: true as const,
targetSessionId,
agentKind: meta.agentKind,
wakeKind: 'queued' as const,
+ queuedMessageId: qClientId,
targetTitle: dbRow.title,
targetLastUserSendAt:
dbRow.userSendAt !== null ? new Date(dbRow.userSendAt).toISOString() : null,
@@ -8394,13 +8502,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
dbRow,
onAccepted,
onAcceptedRollback,
- origin,
+ origin: queuedOrigin,
});
return {
ok: true as const,
targetSessionId,
agentKind: meta.agentKind,
wakeKind: 'queued' as const,
+ queuedMessageId: clientId,
targetTitle: dbRow.title,
targetLastUserSendAt:
dbRow.userSendAt !== null ? new Date(dbRow.userSendAt).toISOString() : null,
@@ -8518,13 +8627,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
dbRow,
onAccepted,
onAcceptedRollback,
- origin,
+ origin: queuedOrigin,
});
return {
ok: true as const,
targetSessionId,
agentKind: meta.agentKind,
wakeKind: 'queued' as const,
+ queuedMessageId: clientId,
targetTitle: dbRow.title,
targetLastUserSendAt:
dbRow.userSendAt !== null ? new Date(dbRow.userSendAt).toISOString() : null,
@@ -8616,13 +8726,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
dbRow,
onAccepted,
onAcceptedRollback,
- origin,
+ origin: queuedOrigin,
});
return {
ok: true as const,
targetSessionId,
agentKind: meta.agentKind,
wakeKind: 'queued' as const,
+ queuedMessageId: clientId,
targetTitle: dbRow.title,
targetLastUserSendAt:
dbRow.userSendAt !== null ? new Date(dbRow.userSendAt).toISOString() : null,
@@ -8953,8 +9064,34 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
onAcceptedRollback?: () => void | Promise<void>;
origin?: AgentInputQueuedMessage['origin'];
}): Promise<void> {
+ const queued = await buildSessionControlInputItem(params);
+ if (params.onAccepted) {
+ orcaInterAgentDispatcher.registerQueuedOrcaInterAgentAcceptedCallback(
+ params.clientId,
+ params.onAccepted,
+ params.onAcceptedRollback,
+ );
+ }
+ // 崩溃恢复排序:确保先读回持久化队列再追加本条(见 ensureQueueRestored)。
+ // 失败时 enqueue 照常入队(shouldQueueNewTurn 已守住不会直发)。
+ await inputCoordinator.ensureQueueRestored(params.targetSessionId).catch(() => undefined);
+ inputCoordinator.enqueue(params.targetSessionId, queued);
+ log.info('send_to_session queued while target busy', {
+ targetSessionId: params.targetSessionId,
+ clientId: params.clientId,
+ });
+ }
+
+ async function buildSessionControlInputItem(params: {
+ targetSessionId: string;
+ message: string;
+ persistedContent: string;
+ clientId: string;
+ meta: NonNullable<Awaited<ReturnType<typeof maker.getSessionMeta>>>;
+ origin?: AgentInputQueuedMessage['origin'];
+ }): Promise<AgentInputQueuedMessage> {
const createOpts = await buildCreateOptsForQueuedSession(params.targetSessionId, params.meta);
- const queued: AgentInputQueuedMessage = {
+ return {
clientId: params.clientId,
text: params.message,
persistedContent: params.persistedContent,
@@ -8972,21 +9109,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
createOpts,
...(params.origin ? { origin: params.origin } : {}),
};
- if (params.onAccepted) {
- orcaInterAgentDispatcher.registerQueuedOrcaInterAgentAcceptedCallback(
- params.clientId,
- params.onAccepted,
- params.onAcceptedRollback,
- );
- }
- // 崩溃恢复排序:确保先读回持久化队列再追加本条(见 ensureQueueRestored)。
- // 失败时 enqueue 照常入队(shouldQueueNewTurn 已守住不会直发)。
- await inputCoordinator.ensureQueueRestored(params.targetSessionId).catch(() => undefined);
- inputCoordinator.enqueue(params.targetSessionId, queued);
- log.info('send_to_session queued while target busy', {
- targetSessionId: params.targetSessionId,
- clientId: params.clientId,
- });
}
const orcaInterAgentDispatcher: OrcaInterAgentDispatcher = createOrcaInterAgentDispatcher({
@@ -9511,10 +9633,14 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
getSessionQueueSnapshot: async (sessionId) => {
// 先补崩溃恢复,保证重启后 lead 仍能看到快照恢复出的排队消息。
await inputCoordinator.ensureQueueRestored(sessionId).catch(() => undefined);
- const projection = inputCoordinator.getProjection(sessionId);
+ const snapshot = inputCoordinator.getQueueControlSnapshot(sessionId);
+ const inspection = inputCoordinator.getQueueInspection(sessionId);
return {
- pendingQueue: projection.pendingQueue,
- steeringClientIds: projection.steeringQueueClientIds,
+ pendingQueue: snapshot.pendingQueue,
+ steeringClientIds: snapshot.steeringQueueClientIds,
+ consumingClientIds: inspection
+ .filter((entry) => entry.consuming)
+ .map((entry) => entry.queuedMessageId),
};
},
removeQueuedMessage: (sessionId, clientId) => {
@@ -9801,11 +9927,111 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
});
idleReleaseWatcher.start();
+ const sessionControlService = createSessionControlService({
+ sessionExists: async (sessionId) =>
+ (await maker.getSessionMeta(sessionId)) !== null,
+ getLiveSession: (sessionId) => maker.getSession(sessionId) ?? null,
+ getSessionActivitySnapshot: readCanonicalSessionActivity,
+ assertExternalInputAllowed: assertReviewExternalInputAllowed,
+ createQueuedMessage: async ({ targetSessionId, callerSessionId, queuedMessageId, message }) => {
+ const meta = await maker.getSessionMeta(targetSessionId);
+ if (!meta) throw new Error(`session ${targetSessionId} not found`);
+ return buildSessionControlInputItem({
+ targetSessionId,
+ message,
+ persistedContent: message,
+ clientId: queuedMessageId,
+ meta,
+ origin: {
+ kind: 'session',
+ senderSessionId: callerSessionId,
+ displayText: message,
+ },
+ });
+ },
+ steerQueuedMessage: async (sessionId, item, expectedTurn) => {
+ await inputCoordinator.ensureQueueRestored(sessionId);
+ return inputCoordinator.steer(sessionId, item, {
+ touchUserSend: true,
+ fallbackToTurn: false,
+ expectedTurnSession: expectedTurn.session,
+ expectedTurnGeneration: expectedTurn.turnGeneration,
+ });
+ },
+ getQueueSnapshot: async (sessionId) => {
+ await inputCoordinator.ensureQueueRestored(sessionId);
+ if (!inputCoordinator.isQueueRestored(sessionId)) {
+ throw new Error(`queue restore incomplete for ${sessionId}`);
+ }
+ const snapshot = inputCoordinator.getQueueControlSnapshot(sessionId);
+ const consumingClientIds = inputCoordinator
+ .getQueueInspection(sessionId)
+ .filter((entry) => entry.consuming)
+ .map((entry) => entry.queuedMessageId);
+ return { pendingQueue: snapshot.pendingQueue, consumingClientIds };
+ },
+ replaceQueuedMessage: (sessionId, clientId, next) =>
+ inputCoordinator.replaceQueuedMessage(sessionId, clientId, next),
+ removeQueuedMessage: (sessionId, clientId) => {
+ if (!inputCoordinator.hasQueuedItemWhere(sessionId, (item) => item.clientId === clientId)) {
+ return false;
+ }
+ inputCoordinator.remove(sessionId, clientId);
+ return !inputCoordinator.hasQueuedItemWhere(sessionId, (item) => item.clientId === clientId);
+ },
+ createId,
+ });
+
// ─── 把 internal 业务函数发布到 module-level holder ────────────────────
// mcp-providers.ts 的 cindy_helper control deps 通过
// tryGetOrcaCollabService() 拿到这些函数引用, 让 MCP tool
// 走与 IPC handler 完全相同的业务路径。
orcaCollabServiceHolder = {
+ listSessionQueue: async (sessionId) => {
+ try {
+ const meta = await maker.getSessionMeta(sessionId);
+ if (!meta) {
+ return { ok: false, errorCode: 'NOT_FOUND', message: `session ${sessionId} not found` };
+ }
+ await inputCoordinator.ensureQueueRestored(sessionId);
+ if (!inputCoordinator.isQueueRestored(sessionId)) {
+ return { ok: false, errorCode: 'INTERNAL', message: `queue restore incomplete for ${sessionId}` };
+ }
+ return {
+ ok: true,
+ messages: inputCoordinator.getQueueInspection(sessionId),
+ };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return {
+ ok: false,
+ errorCode: isDbClientNotReadyError(err) ? 'HOST_NOT_READY' : 'INTERNAL',
+ message,
+ };
+ }
+ },
+ listSessionQueuedCounts: async (sessionIds) => {
+ try {
+ const counts = await resolveSessionQueueCounts(sessionIds, {
+ getLiveQueue: (sessionId) =>
+ inputCoordinator.getQueueInspectionIfRestored(sessionId),
+ loadPersistedCounts: loadAgentInputQueueSnapshotCounts,
+ });
+ return { ok: true, counts };
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ return {
+ ok: false,
+ errorCode: isDbClientNotReadyError(err) ? 'HOST_NOT_READY' : 'INTERNAL',
+ message,
+ };
+ }
+ },
+ updateSessionQueuedMessage: (params) => sessionControlService.updateQueuedMessage(params),
+ cancelSessionQueuedMessage: (params) => sessionControlService.cancelQueuedMessage(params),
+ steerSession: (params) => sessionControlService.steerSession(params),
+ stopSessionTurn: (params) => sessionControlService.stopSessionTurn(params),
+ getSessionRuntime: (params) => sessionControlService.getSessionRuntime(params),
sendToSession: sendToSessionInternal,
enableOrca: enableOrcaInternal,
disableOrca: disableOrcaInternal,
@@ -10284,11 +10510,33 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
): Promise<void> => {
if (typeof sessionId !== 'string') throwIpcError('INVALID_PARAMS', 'sessionId required');
await assertReviewExternalInputAllowed(sessionId);
- const sess = maker.getSession(sessionId);
- if (!sess) {
- log.warn('steer: session not running', { sessionId });
- throwIpcError('NO_ACTIVE_TURN', `Session ${sessionId} is not running`);
- }
+ const so = (sendOpts ?? {}) as {
+ messageUuid?: string;
+ userName?: string;
+ signal?: AbortSignal;
+ /** coordinator 从队列项透传的手机来源(main 构造,非 wire 输入)。 */
+ fromMobileClient?: boolean;
+ expectedClearBoundaryMs?: number | null;
+ expectedInputGeneration?: number;
+ expectedTurnSession?: object;
+ expectedTurnGeneration?: number;
+ };
+ const readCurrentSteerSession = () => {
+ const current = maker.getSession(sessionId);
+ if (!current) {
+ log.warn('steer: session not running', { sessionId });
+ throwIpcError('NO_ACTIVE_TURN', `Session ${sessionId} is not running`);
+ }
+ if (
+ (so.expectedTurnSession !== undefined && current !== so.expectedTurnSession) ||
+ (so.expectedTurnGeneration !== undefined &&
+ current.getTurnGeneration() !== so.expectedTurnGeneration)
+ ) {
+ throw new Error(`[STALE_TURN] Session ${sessionId} changed turns before steer delivery`);
+ }
+ return current;
+ };
+ let sess = readCurrentSteerSession();
log.info('steer: invoked', {
sessionId,
agentKind: sess.agentKind,
@@ -10325,19 +10573,12 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
activeAfterNormalize: sess.isTurnRunning(),
...summarizeIpcUserMessage(normalized),
});
+ sess = readCurrentSteerSession();
if (!sess.isTurnRunning()) {
throwIpcError('NO_ACTIVE_TURN', `Session ${sessionId} has no active turn`);
}
const meta = await maker.getSessionMeta(sessionId).catch(() => null);
- const so = (sendOpts ?? {}) as {
- messageUuid?: string;
- userName?: string;
- signal?: AbortSignal;
- /** coordinator 从队列项透传的手机来源(main 构造,非 wire 输入)。 */
- fromMobileClient?: boolean;
- expectedClearBoundaryMs?: number | null;
- expectedInputGeneration?: number;
- };
+ sess = readCurrentSteerSession();
// 手机说明同样只进 wire payload(steer 路径不落库用户消息,天然不污染原话)。
// 两个来源都要认:IPC 直连 steer 时 async context 在;coordinator 投递时靠透传。
const steerNote =
@@ -10356,6 +10597,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
assertCurrentInputClearBoundary(sessionId, precondition.expected);
}
assertCurrentInputGeneration(sessionId, readExpectedInputGeneration(sendOpts));
+ sess = readCurrentSteerSession();
await sess.steer(steerPayload as never, {
logTitle: meta?.title,
messageUuid: so.messageUuid,
@@ -11057,6 +11299,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
getTurnGeneration: (sessionId) =>
getStableSessionForTurnBoundary(sessionId)?.getTurnGeneration() ?? null,
+ getTurnSessionIdentity: (sessionId) => getStableSessionForTurnBoundary(sessionId) ?? null,
reconcileTurnIdle: (sessionId) => {
// steer 拿到 maker-core 权威 NO_ACTIVE_TURN、或 abort 已让 vendor 停止
// 但终态事件丢失时,都走同一条收口路径。
@@ -11300,8 +11543,11 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
getAgentIslandService()?.notifyQueueEmptied(sessionId);
},
// 排队输入崩溃恢复(issue #761):快照写入 fire-and-forget(模块内 per-session
- // 写链保序 + 失败落日志),读回由 IPC 入口的 ensureQueueRestored 懒触发。
+ // 写链保序 + 失败落日志),读回由 ensureQueueRestored 懒触发。恢复前先严格
+ // 水合 durable /clear 边界,所有入口共用,避免仅 projection 路径安全。
persistQueueSnapshot: (sessionId, items) => saveAgentInputQueueSnapshot(sessionId, items),
+ loadClearBoundary: async (sessionId) =>
+ (await getSessionRowSnapshotStrict(sessionId))?.clearedAt,
loadQueueSnapshot: (sessionId) => loadAgentInputQueueSnapshot(sessionId),
getPersistedClientIds: getPersistedInputClientIds,
});
diff --git a/apps/desktop/src/main/maker-ipc/sessionActivityProjection.ts b/apps/desktop/src/main/maker-ipc/sessionActivityProjection.ts
new file mode 100644
index 0000000000..918ec60b5c
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sessionActivityProjection.ts
@@ -0,0 +1,103 @@
+import {
+ projectSessionActivity,
+ type SessionActivitySnapshot,
+ type SessionRecordStatus,
+} from '@cindy/maker-shared/session-activity';
+import { eq } from 'drizzle-orm';
+
+import { getAgentIslandService } from '../agent-island/service.js';
+import { getDbClient } from '../localDb/client/current.js';
+import { sessions } from '../localDb/schema.js';
+import {
+ readLatestSessionTerminal,
+ type SessionTerminalHint,
+} from '../localDb/sessionTerminal.js';
+
+export interface PersistedSessionActivityFacts {
+ status: SessionRecordStatus;
+ title: string | null;
+ startedAt: number | null;
+ endedAt: number | null;
+ clearedAt: number | null;
+}
+
+export interface SessionActivityReaderDeps {
+ getLiveSnapshot(sessionId: string): SessionActivitySnapshot | null;
+ getPersistedFacts(sessionId: string): Promise<PersistedSessionActivityFacts | null>;
+ getLatestTerminal(
+ sessionId: string,
+ clearedAt: number | null,
+ ): Promise<SessionTerminalHint | undefined>;
+}
+
+/**
+ * Build a canonical reader from the existing live and durable authorities.
+ * This is a projection only: it never persists or owns another status copy.
+ */
+export function createSessionActivityReader(deps: SessionActivityReaderDeps) {
+ return async (sessionId: string): Promise<SessionActivitySnapshot> => {
+ const live = deps.getLiveSnapshot(sessionId);
+ if (live) return live;
+
+ const row = await deps.getPersistedFacts(sessionId);
+ if (!row) return projectSessionActivity({ sessionId, source: 'fallback' });
+
+ const terminal = await deps.getLatestTerminal(sessionId, row.clearedAt);
+ const visibilityBoundary = Math.max(row.endedAt ?? 0, row.clearedAt ?? 0);
+ const interrupted = row.startedAt !== null && row.startedAt > visibilityBoundary;
+ const completed =
+ row.endedAt !== null
+ && row.endedAt > (row.clearedAt ?? 0)
+ && (row.startedAt === null || row.endedAt >= row.startedAt);
+ const failed = terminal !== undefined || interrupted;
+
+ return projectSessionActivity({
+ sessionId,
+ recordStatus: row.status,
+ title: row.title,
+ source: 'persisted',
+ terminal: failed ? 'error' : completed ? 'completed' : null,
+ startedAtMs: row.startedAt,
+ lastActivityAtMs: terminal?.createdAt ?? (interrupted ? row.startedAt : row.endedAt ?? row.startedAt),
+ currentActionSummary: terminal
+ ? '上次运行出错'
+ : interrupted
+ ? '上次运行未正常结束'
+ : completed
+ ? '上次运行已正常结束'
+ : null,
+ attention: failed,
+ });
+ };
+}
+
+async function readPersistedSessionActivityFacts(
+ sessionId: string,
+): Promise<PersistedSessionActivityFacts | null> {
+ const [row] = await getDbClient()
+ .drizzle.select({
+ status: sessions.status,
+ title: sessions.title,
+ startedAt: sessions.activeTurnStartedAt,
+ endedAt: sessions.lastTurnEndedAt,
+ clearedAt: sessions.clearedAt,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ return row ?? null;
+}
+
+const readDefaultSessionActivity = createSessionActivityReader({
+ getLiveSnapshot: (sessionId) =>
+ getAgentIslandService()?.getSessionActivitySnapshot(sessionId) ?? null,
+ getPersistedFacts: readPersistedSessionActivityFacts,
+ getLatestTerminal: readLatestSessionTerminal,
+});
+
+/** Main-owned canonical activity read shared by UI-backed state and MCP probes. */
+export function readCanonicalSessionActivity(
+ sessionId: string,
+): Promise<SessionActivitySnapshot> {
+ return readDefaultSessionActivity(sessionId);
+}
diff --git a/apps/desktop/src/main/maker-ipc/sessionControlService.ts b/apps/desktop/src/main/maker-ipc/sessionControlService.ts
new file mode 100644
index 0000000000..98638f8ca2
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sessionControlService.ts
@@ -0,0 +1,277 @@
+import type {
+ AgentKind,
+ SessionGracefulStopResult,
+ SessionTurnControlSnapshot,
+} from '@cindy/maker-core';
+import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
+
+import {
+ updateQueuedMessageText,
+ type AgentInputQueuedMessage,
+} from '../../shared/agentInputQueue.js';
+import { createSessionQueueControlService } from './sessionQueueControl.js';
+
+type Failure<Code extends string> = { ok: false; errorCode: Code; message: string };
+
+export type SessionQueuedMessageControlResult =
+ | { ok: true; queuedMessageId: string }
+ | Failure<
+ | 'NOT_FOUND'
+ | 'QUEUED_MESSAGE_NOT_FOUND'
+ | 'MESSAGE_CONSUMING'
+ | 'NOT_AUTHORIZED'
+ | 'INVALID_ARGS'
+ >;
+
+export type SessionSteerResult =
+ | { ok: true; queuedMessageId: string }
+ | Failure<'NOT_FOUND' | 'NO_ACTIVE_TURN' | 'UNSUPPORTED_CAPABILITY' | 'DELIVERY_FAILED'>;
+
+export type SessionStopResult =
+ | {
+ ok: true;
+ status: 'no-active-turn' | 'waiting-for-safe-point' | 'requested' | 'unconfirmed';
+ turnGeneration?: number;
+ reason?: string;
+ }
+ | Failure<'NOT_FOUND' | 'UNSUPPORTED_CAPABILITY'>;
+
+export type SessionRuntimeResult =
+ { ok: true; runtime: SessionActivitySnapshot } | Failure<'NOT_FOUND'>;
+
+export interface SessionControlLiveSession {
+ agentKind: AgentKind;
+ capabilities: { sameTurnSteer: { supported: boolean } };
+ isTurnRunning(): boolean;
+ getTurnGeneration(): number;
+ requestGracefulStop(): Promise<SessionGracefulStopResult>;
+ getTurnControlSnapshot(): SessionTurnControlSnapshot;
+}
+
+export interface SessionSteerTurnIdentity {
+ session: SessionControlLiveSession;
+ turnGeneration: number;
+}
+
+export interface SessionControlServiceDeps {
+ sessionExists(sessionId: string): Promise<boolean>;
+ getLiveSession(sessionId: string): SessionControlLiveSession | null;
+ getSessionActivitySnapshot(sessionId: string): Promise<SessionActivitySnapshot>;
+ assertExternalInputAllowed(sessionId: string): Promise<void>;
+ createQueuedMessage(params: {
+ targetSessionId: string;
+ callerSessionId: string;
+ queuedMessageId: string;
+ message: string;
+ }): Promise<AgentInputQueuedMessage>;
+ steerQueuedMessage(
+ sessionId: string,
+ item: AgentInputQueuedMessage,
+ expectedTurn: SessionSteerTurnIdentity,
+ ): Promise<boolean>;
+ getQueueSnapshot(sessionId: string): Promise<{
+ pendingQueue: AgentInputQueuedMessage[];
+ consumingClientIds: string[];
+ }>;
+ replaceQueuedMessage(sessionId: string, clientId: string, next: AgentInputQueuedMessage): boolean;
+ removeQueuedMessage(sessionId: string, clientId: string): boolean;
+ createId(): string;
+}
+
+export function createSessionControlService(deps: SessionControlServiceDeps) {
+ const queueControl = createSessionQueueControlService({
+ getSnapshot: deps.getQueueSnapshot,
+ replaceQueuedMessage: deps.replaceQueuedMessage,
+ removeQueuedMessage: deps.removeQueuedMessage,
+ });
+
+ async function ensureTarget(sessionId: string): Promise<Failure<'NOT_FOUND'> | null> {
+ // A live Session is authoritative even when its persisted metadata is temporarily
+ // unavailable. Only a successful metadata lookup may classify the target as absent.
+ if (deps.getLiveSession(sessionId)) return null;
+ return (await deps.sessionExists(sessionId))
+ ? null
+ : { ok: false, errorCode: 'NOT_FOUND', message: `session ${sessionId} not found` };
+ }
+
+ return {
+ async updateQueuedMessage(params: {
+ callerSessionId: string;
+ targetSessionId: string;
+ queuedMessageId: string;
+ message: string;
+ }): Promise<SessionQueuedMessageControlResult> {
+ const missing = await ensureTarget(params.targetSessionId);
+ if (missing) return missing;
+ return queueControl.update({
+ sessionId: params.targetSessionId,
+ queuedMessageId: params.queuedMessageId,
+ message: params.message,
+ authorize: (item) => authorizeSessionQueueItem(item, params.callerSessionId),
+ rebuild: rebuildSessionQueueItem,
+ });
+ },
+
+ async cancelQueuedMessage(params: {
+ callerSessionId: string;
+ targetSessionId: string;
+ queuedMessageId: string;
+ }): Promise<SessionQueuedMessageControlResult> {
+ const missing = await ensureTarget(params.targetSessionId);
+ if (missing) return missing;
+ return queueControl.cancel({
+ sessionId: params.targetSessionId,
+ queuedMessageId: params.queuedMessageId,
+ authorize: (item) => authorizeSessionQueueItem(item, params.callerSessionId),
+ });
+ },
+
+ async steerSession(params: {
+ callerSessionId: string;
+ targetSessionId: string;
+ message: string;
+ }): Promise<SessionSteerResult> {
+ const missing = await ensureTarget(params.targetSessionId);
+ if (missing) return missing;
+ try {
+ await deps.assertExternalInputAllowed(params.targetSessionId);
+ } catch (error) {
+ if ((error as { code?: unknown }).code === 'UNSUPPORTED_CAPABILITY') {
+ return {
+ ok: false,
+ errorCode: 'UNSUPPORTED_CAPABILITY',
+ message: error instanceof Error ? error.message : String(error),
+ };
+ }
+ throw error;
+ }
+ const live = deps.getLiveSession(params.targetSessionId);
+ if (!live?.isTurnRunning()) {
+ return {
+ ok: false,
+ errorCode: 'NO_ACTIVE_TURN',
+ message: `session ${params.targetSessionId} has no active turn`,
+ };
+ }
+ if (!live.capabilities.sameTurnSteer.supported) {
+ return {
+ ok: false,
+ errorCode: 'UNSUPPORTED_CAPABILITY',
+ message: `agent ${live.agentKind} does not support same-turn steer`,
+ };
+ }
+ const turnGeneration = live.getTurnGeneration();
+ const queuedMessageId = deps.createId();
+ const item = await deps.createQueuedMessage({
+ ...params,
+ queuedMessageId,
+ });
+ const current = deps.getLiveSession(params.targetSessionId);
+ if (
+ current !== live ||
+ !current.isTurnRunning() ||
+ current.getTurnGeneration() !== turnGeneration
+ ) {
+ return {
+ ok: false,
+ errorCode: 'NO_ACTIVE_TURN',
+ message: `session ${params.targetSessionId} changed turns before steer was accepted`,
+ };
+ }
+ const expectedTurn = { session: live, turnGeneration };
+ const accepted = await deps.steerQueuedMessage(params.targetSessionId, item, expectedTurn);
+ if (!accepted) {
+ const latest = deps.getLiveSession(params.targetSessionId);
+ return latest === live &&
+ latest.isTurnRunning() &&
+ latest.getTurnGeneration() === turnGeneration
+ ? {
+ ok: false,
+ errorCode: 'DELIVERY_FAILED',
+ message: 'steer was not accepted at the current input boundary',
+ }
+ : {
+ ok: false,
+ errorCode: 'NO_ACTIVE_TURN',
+ message: `session ${params.targetSessionId} turn ended before steer was accepted`,
+ };
+ }
+ return { ok: true, queuedMessageId };
+ },
+
+ async stopSessionTurn(params: { targetSessionId: string }): Promise<SessionStopResult> {
+ const missing = await ensureTarget(params.targetSessionId);
+ if (missing) return missing;
+ const live = deps.getLiveSession(params.targetSessionId);
+ if (!live) return { ok: true, status: 'no-active-turn' };
+ const result = await live.requestGracefulStop();
+ if (result.status === 'unsupported') {
+ return {
+ ok: false,
+ errorCode: 'UNSUPPORTED_CAPABILITY',
+ message: `agent ${live.agentKind} does not support graceful stop`,
+ };
+ }
+ return {
+ ok: true,
+ status: result.status,
+ ...('turnGeneration' in result ? { turnGeneration: result.turnGeneration } : {}),
+ ...('reason' in result ? { reason: result.reason } : {}),
+ };
+ },
+
+ async getSessionRuntime(params: { targetSessionId: string }): Promise<SessionRuntimeResult> {
+ const missing = await ensureTarget(params.targetSessionId);
+ if (missing) return missing;
+ const activity = await deps.getSessionActivitySnapshot(params.targetSessionId);
+ const control = deps.getLiveSession(params.targetSessionId)?.getTurnControlSnapshot();
+ return {
+ ok: true,
+ runtime: {
+ ...activity,
+ turnGeneration: control?.turnGeneration ?? null,
+ gracefulStopState: control?.gracefulStopState ?? 'none',
+ },
+ };
+ },
+ };
+}
+
+export function authorizeSessionQueueItem(
+ item: AgentInputQueuedMessage,
+ callerSessionId: string,
+): { ok: true } | { ok: false; message: string } {
+ return item.origin?.kind === 'session' && item.origin.senderSessionId === callerSessionId
+ ? { ok: true }
+ : { ok: false, message: 'queued message was not sent by the current session' };
+}
+
+export function rebuildSessionQueueItem(
+ item: AgentInputQueuedMessage,
+ message: string,
+): AgentInputQueuedMessage {
+ const updated = updateQueuedMessageText(item, message);
+ if (updated.origin?.kind === 'session') {
+ // send_to_session owns raw user text, not a renderer composer envelope.
+ // A valid JSON object/array is still literal message content, so editing it
+ // must replace the persisted history row wholesale instead of merging a
+ // synthetic `text` property into the old JSON value.
+ updated.persistedContent = message;
+ updated.origin = { ...updated.origin, displayText: message };
+ }
+ return updated;
+}
+
+export function sessionQueueOriginForDispatcher(params: {
+ dispatcherSessionId?: string;
+ message: string;
+ explicitOrigin?: AgentInputQueuedMessage['origin'];
+}): AgentInputQueuedMessage['origin'] | undefined {
+ if (params.explicitOrigin) return params.explicitOrigin;
+ if (!params.dispatcherSessionId) return undefined;
+ return {
+ kind: 'session',
+ senderSessionId: params.dispatcherSessionId,
+ displayText: params.message,
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/sessionQueueControl.ts b/apps/desktop/src/main/maker-ipc/sessionQueueControl.ts
new file mode 100644
index 0000000000..cf4b544057
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sessionQueueControl.ts
@@ -0,0 +1,130 @@
+import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';
+
+export type SessionQueueControlFailureCode =
+ 'QUEUED_MESSAGE_NOT_FOUND' | 'MESSAGE_CONSUMING' | 'NOT_AUTHORIZED' | 'INVALID_ARGS';
+
+export type SessionQueueControlResult =
+ | { ok: true; queuedMessageId: string }
+ | {
+ ok: false;
+ errorCode: SessionQueueControlFailureCode;
+ message: string;
+ };
+
+export interface SessionQueueControlSnapshot {
+ pendingQueue: AgentInputQueuedMessage[];
+ consumingClientIds: string[];
+}
+
+export interface SessionQueueControlDeps {
+ getSnapshot(sessionId: string): Promise<SessionQueueControlSnapshot>;
+ replaceQueuedMessage(sessionId: string, clientId: string, next: AgentInputQueuedMessage): boolean;
+ removeQueuedMessage(sessionId: string, clientId: string): boolean;
+}
+
+export type SessionQueueAuthorization = (
+ item: AgentInputQueuedMessage,
+) => { ok: true } | { ok: false; message: string };
+
+type BaseControlParams = {
+ sessionId: string;
+ queuedMessageId: string;
+ authorize: SessionQueueAuthorization;
+};
+
+/**
+ * 排队消息控制的统一事务边界。Orca 与 cindy_helper 只提供身份策略和正文重建,
+ * 恢复后定位、consuming 拒绝、replace/remove 竞态复核都只在这里维护。
+ */
+export function createSessionQueueControlService(deps: SessionQueueControlDeps) {
+ async function resolve(
+ params: BaseControlParams,
+ ): Promise<
+ { ok: true; item: AgentInputQueuedMessage } | Exclude<SessionQueueControlResult, { ok: true }>
+ > {
+ const snapshot = await deps.getSnapshot(params.sessionId);
+ if (snapshot.consumingClientIds.includes(params.queuedMessageId)) {
+ return consumingFailure(params.queuedMessageId);
+ }
+ const item = snapshot.pendingQueue.find(
+ (candidate) => candidate.clientId === params.queuedMessageId,
+ );
+ if (!item) return missingFailure(params.queuedMessageId);
+ const authorization = params.authorize(item);
+ if (!authorization.ok) {
+ return {
+ ok: false,
+ errorCode: 'NOT_AUTHORIZED',
+ message: authorization.message,
+ };
+ }
+ return { ok: true, item };
+ }
+
+ async function classifyLostRace(
+ sessionId: string,
+ queuedMessageId: string,
+ ): Promise<Exclude<SessionQueueControlResult, { ok: true }>> {
+ const latest = await deps.getSnapshot(sessionId);
+ return latest.consumingClientIds.includes(queuedMessageId)
+ ? consumingFailure(queuedMessageId)
+ : missingFailure(queuedMessageId);
+ }
+
+ return {
+ async update(
+ params: BaseControlParams & {
+ message: string;
+ rebuild: (item: AgentInputQueuedMessage, message: string) => AgentInputQueuedMessage;
+ },
+ ): Promise<SessionQueueControlResult> {
+ if (params.message.trim().length === 0) {
+ return { ok: false, errorCode: 'INVALID_ARGS', message: 'message must not be empty' };
+ }
+ const resolved = await resolve(params);
+ if (!resolved.ok) return resolved;
+ const next = params.rebuild(resolved.item, params.message);
+ if (
+ next.clientId !== params.queuedMessageId ||
+ next.chatMessage.clientId !== params.queuedMessageId
+ ) {
+ return {
+ ok: false,
+ errorCode: 'INVALID_ARGS',
+ message: 'replacement must preserve queued message identity',
+ };
+ }
+ if (!deps.replaceQueuedMessage(params.sessionId, params.queuedMessageId, next)) {
+ return classifyLostRace(params.sessionId, params.queuedMessageId);
+ }
+ return { ok: true, queuedMessageId: params.queuedMessageId };
+ },
+
+ async cancel(params: BaseControlParams): Promise<SessionQueueControlResult> {
+ const resolved = await resolve(params);
+ if (!resolved.ok) return resolved;
+ if (!deps.removeQueuedMessage(params.sessionId, params.queuedMessageId)) {
+ return classifyLostRace(params.sessionId, params.queuedMessageId);
+ }
+ return { ok: true, queuedMessageId: params.queuedMessageId };
+ },
+ };
+}
+
+function missingFailure(queuedMessageId: string): Exclude<SessionQueueControlResult, { ok: true }> {
+ return {
+ ok: false,
+ errorCode: 'QUEUED_MESSAGE_NOT_FOUND',
+ message: `queued message ${queuedMessageId} not found — it may have been dispatched or cancelled already`,
+ };
+}
+
+function consumingFailure(
+ queuedMessageId: string,
+): Exclude<SessionQueueControlResult, { ok: true }> {
+ return {
+ ok: false,
+ errorCode: 'MESSAGE_CONSUMING',
+ message: `queued message ${queuedMessageId} is being delivered and can no longer be modified`,
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/sessionQueueInspection.ts b/apps/desktop/src/main/maker-ipc/sessionQueueInspection.ts
new file mode 100644
index 0000000000..d9c6b7acc7
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/sessionQueueInspection.ts
@@ -0,0 +1,107 @@
+/**
+ * 把 AgentInputCoordinator 的 renderer projection 压成 MCP 可见的只读队列快照。
+ * 这里刻意不返回模型、权限、附件与持久化 payload,避免诊断接口扩大数据面。
+ */
+
+import type { AgentInputQueuedMessage } from '../../shared/agentInputQueue.js';
+
+export interface SessionQueueInspectionEntry {
+ queuedMessageId: string;
+ position: number;
+ source: 'user' | 'orca' | 'scheduler' | 'session';
+ sourceLabel: string | null;
+ enqueuedAtMs: number | null;
+ content: string;
+ consuming: boolean;
+}
+
+export interface SessionQueueCountDeps {
+ /** null = cold/read SQLite; undefined = live but not safely inspectable yet. */
+ getLiveQueue: (sessionId: string) => SessionQueueInspectionEntry[] | null | undefined;
+ loadPersistedCounts: (sessionIds: readonly string[]) => Promise<Record<string, number>>;
+}
+
+export async function resolveSessionQueueCounts(
+ sessionIds: readonly string[],
+ deps: SessionQueueCountDeps,
+): Promise<Record<string, number>> {
+ const uniqueIds = [...new Set(sessionIds)];
+ const readLiveQueue = (
+ sessionId: string,
+ ): SessionQueueInspectionEntry[] | null | undefined => {
+ try {
+ return deps.getLiveQueue(sessionId);
+ } catch {
+ // A single live coordinator can be between construction and queue restore,
+ // or otherwise fail its process-local projection. Keep list_sessions useful
+ // for every other session while reporting this one conservatively as zero.
+ return undefined;
+ }
+ };
+ const unrestoredIds = uniqueIds.filter((sessionId) => readLiveQueue(sessionId) === null);
+ const persistedCounts = await deps.loadPersistedCounts(unrestoredIds);
+ return Object.fromEntries(
+ uniqueIds.map((sessionId) => {
+ // Recheck after the async DB read: a live restore/enqueue that won the race is newer.
+ const live = readLiveQueue(sessionId);
+ if (live !== null) return [sessionId, live?.length ?? 0];
+ return [sessionId, persistedCounts[sessionId] ?? 0];
+ }),
+ );
+}
+
+export function projectSessionQueueForInspection(
+ pendingQueue: readonly AgentInputQueuedMessage[],
+ steeringQueueClientIds: readonly string[],
+ activeItem: AgentInputQueuedMessage | null = null,
+ directSteeringItems: readonly AgentInputQueuedMessage[] = [],
+): SessionQueueInspectionEntry[] {
+ const consumingIds = new Set(steeringQueueClientIds);
+ const seen = new Set<string>();
+ const result: SessionQueueInspectionEntry[] = [];
+ const append = (item: AgentInputQueuedMessage, consuming: boolean): void => {
+ if (seen.has(item.clientId)) return;
+ seen.add(item.clientId);
+ result.push({
+ queuedMessageId: item.clientId,
+ position: result.length,
+ source: queueSource(item),
+ sourceLabel: queueSourceLabel(item),
+ enqueuedAtMs: acceptedAtMs(item),
+ content:
+ item.origin?.kind === 'orca' || item.origin?.kind === 'session'
+ ? (item.origin.displayText ?? item.text)
+ : item.text,
+ consuming,
+ });
+ };
+
+ if (activeItem) append(activeItem, true);
+ for (const item of directSteeringItems) append(item, true);
+ for (const item of pendingQueue) append(item, consumingIds.has(item.clientId));
+ return result;
+}
+
+function acceptedAtMs(item: AgentInputQueuedMessage): number | null {
+ if (typeof item.hostAcceptedAtMs === 'number' && Number.isFinite(item.hostAcceptedAtMs)) {
+ return item.hostAcceptedAtMs;
+ }
+ return parseCreatedAt(item.chatMessage.createdAt);
+}
+
+function queueSource(item: AgentInputQueuedMessage): SessionQueueInspectionEntry['source'] {
+ return item.origin?.kind ?? 'user';
+}
+
+function queueSourceLabel(item: AgentInputQueuedMessage): string | null {
+ if (item.origin?.kind === 'orca') return item.origin.senderLabel;
+ if (item.origin?.kind === 'scheduler') return item.origin.scheduleName;
+ if (item.origin?.kind === 'session') return item.origin.senderSessionId;
+ return null;
+}
+
+function parseCreatedAt(value: string | undefined): number | null {
+ if (!value) return null;
+ const parsed = new Date(value).getTime();
+ return Number.isFinite(parsed) ? parsed : null;
+}
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
index 0f26f3665d..5ea365f90a 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts
@@ -137,6 +137,13 @@ function createCollabService(overrides: Record<string, ReturnType<typeof vi.fn>>
getWorkspaceInfo: vi.fn(),
getWorkerStatus: vi.fn(),
readWorker: vi.fn(),
+ listSessionQueue: vi.fn(),
+ listSessionQueuedCounts: vi.fn(),
+ updateSessionQueuedMessage: vi.fn(),
+ cancelSessionQueuedMessage: vi.fn(),
+ steerSession: vi.fn(),
+ stopSessionTurn: vi.fn(),
+ getSessionRuntime: vi.fn(),
...overrides,
};
}
@@ -479,4 +486,84 @@ describe('collab send outcome semantics', () => {
expect(mockState.collabService.startTeam).not.toHaveBeenCalled();
expect(mockState.collabService.createWorker).not.toHaveBeenCalled();
});
+
+ it('exposes arbitrary session queue reads through cindy_helper without Lead ownership', async () => {
+ mockState.collabService = createCollabService({
+ listSessionQueue: vi.fn().mockResolvedValue({
+ ok: true,
+ messages: [{ queuedMessageId: 'q-1', position: 0 }],
+ }),
+ listSessionQueuedCounts: vi.fn().mockResolvedValue({
+ ok: true,
+ counts: { 'session-1': 1 },
+ }),
+ });
+
+ createDesktopMcpProviders({
+ getMakerMemoryManager: vi.fn(),
+ lspPool: {} as never,
+ pluginRegistry: { isEnabled: () => true } as never,
+ resolveIOSSimulatorAccess: () => ({ allowed: true }),
+ invokeRemote: vi.fn(),
+ });
+ const xdtHelper = mockState.capturedProvidersConfig?.xdtHelper as {
+ sessionQueue: {
+ listSessionQueue: (sessionId: string) => Promise<Record<string, unknown>>;
+ listSessionQueuedCounts: (sessionIds: string[]) => Promise<Record<string, unknown>>;
+ };
+ };
+
+ await expect(xdtHelper.sessionQueue.listSessionQueue('session-1')).resolves.toMatchObject({
+ ok: true,
+ messages: [{ queuedMessageId: 'q-1', position: 0 }],
+ });
+ await expect(
+ xdtHelper.sessionQueue.listSessionQueuedCounts(['session-1']),
+ ).resolves.toEqual({ ok: true, counts: { 'session-1': 1 } });
+ expect(mockState.collabService.listSessionQueue).toHaveBeenCalledWith('session-1');
+ expect(mockState.collabService.listSessionQueuedCounts).toHaveBeenCalledWith(['session-1']);
+ });
+
+ it('preserves retryable host-readiness errors at the cindy_helper control boundary', async () => {
+ mockState.collabService = createCollabService({
+ listSessionQueue: vi.fn().mockRejectedValue(new Error('DbClient not ready')),
+ listSessionQueuedCounts: vi.fn().mockRejectedValue(new Error('localDb not ready')),
+ stopSessionTurn: vi.fn().mockRejectedValue({
+ code: 'HOST_NOT_READY',
+ message: 'database owner unavailable',
+ }),
+ getSessionRuntime: vi.fn().mockRejectedValue(new Error('storage read failed')),
+ });
+
+ createDesktopMcpProviders({
+ getMakerMemoryManager: vi.fn(),
+ lspPool: {} as never,
+ pluginRegistry: { isEnabled: () => true } as never,
+ resolveIOSSimulatorAccess: () => ({ allowed: true }),
+ invokeRemote: vi.fn(),
+ });
+ const xdtHelper = mockState.capturedProvidersConfig?.xdtHelper as {
+ sessionQueue: {
+ listSessionQueue: (sessionId: string) => Promise<Record<string, unknown>>;
+ listSessionQueuedCounts: (sessionIds: string[]) => Promise<Record<string, unknown>>;
+ };
+ sessionControl: {
+ stopSessionTurn: (params: { targetSessionId: string }) => Promise<Record<string, unknown>>;
+ getSessionRuntime: (params: { targetSessionId: string }) => Promise<Record<string, unknown>>;
+ };
+ };
+
+ await expect(
+ xdtHelper.sessionQueue.listSessionQueue('session-1'),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'HOST_NOT_READY' });
+ await expect(
+ xdtHelper.sessionQueue.listSessionQueuedCounts(['session-1']),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'HOST_NOT_READY' });
+ await expect(
+ xdtHelper.sessionControl.stopSessionTurn({ targetSessionId: 'session-1' }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'HOST_NOT_READY' });
+ await expect(
+ xdtHelper.sessionControl.getSessionRuntime({ targetSessionId: 'session-1' }),
+ ).resolves.toMatchObject({ ok: false, errorCode: 'INTERNAL' });
+ });
});
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 12461d6ece..86dd7f0b98 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -35,7 +35,10 @@ import {
listSessionsForHistory,
getMessagesForHistory,
} from '../localDb/chatHistoryReader.js';
-import { tryGetDbClient } from '../localDb/client/current.js';
+import {
+ isDbClientNotReadyError,
+ tryGetDbClient,
+} from '../localDb/client/current.js';
import { searchChatHistoryHybrid } from '../localDb/chatHistorySearch.js';
import {
patchSessionMetaInDb,
@@ -94,7 +97,11 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
const s = tryGetOrcaCollabService();
if (!s) return { ok: false, errorCode: 'HOST_NOT_READY' as const, message: 'orca collab service not initialized' } as R;
try { return await fn(s, ...args); }
- catch (err) { return { ok: false, errorCode: 'INTERNAL' as const, message: err instanceof Error ? err.message : String(err) } as R; }
+ catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ const errorCode = isDbClientNotReadyError(err) ? 'HOST_NOT_READY' : 'INTERNAL';
+ return { ok: false, errorCode, message } as R;
+ }
};
}
@@ -301,6 +308,18 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
// (LLM 调工具时) registerMakerIpc 早已执行完毕, holder 已 ready。
xdtHelper: {
logger: createLogger('mcp/cindy_helper'),
+ sessionQueue: {
+ listSessionQueue: wrap((service, sessionId: string) => service.listSessionQueue(sessionId)),
+ listSessionQueuedCounts: wrap((service, sessionIds: string[]) =>
+ service.listSessionQueuedCounts(sessionIds)),
+ },
+ sessionControl: {
+ updateQueuedMessage: wrap((service, params) => service.updateSessionQueuedMessage(params)),
+ cancelQueuedMessage: wrap((service, params) => service.cancelSessionQueuedMessage(params)),
+ steerSession: wrap((service, params) => service.steerSession(params)),
+ stopSessionTurn: wrap((service, params) => service.stopSessionTurn(params)),
+ getSessionRuntime: wrap((service, params) => service.getSessionRuntime(params)),
+ },
setCurrentSessionTitle: async ({ sessionId, title }) => {
if (!tryGetDbClient()) {
return { ok: false, errorCode: 'HOST_NOT_READY', message: 'localDb not ready' };
@@ -400,11 +419,11 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
history: {
listWorkdirs: async (args) => {
try { const page = await listWorkdirsForHistory(args); return { ok: true, page }; }
- catch (err) { const msg = err instanceof Error ? err.message : String(err); const errorCode = /localDb not ready/i.test(msg) ? 'HOST_NOT_READY' : 'INTERNAL'; return { ok: false, errorCode, message: msg }; }
+ catch (err) { const msg = err instanceof Error ? err.message : String(err); const errorCode = isDbClientNotReadyError(err) ? 'HOST_NOT_READY' : 'INTERNAL'; return { ok: false, errorCode, message: msg }; }
},
listSessions: async (args) => {
try { const page = await listSessionsForHistory(args); return { ok: true, page }; }
- catch (err) { const msg = err instanceof Error ? err.message : String(err); const errorCode = /localDb not ready/i.test(msg) ? 'HOST_NOT_READY' : 'INTERNAL'; return { ok: false, errorCode, message: msg }; }
+ catch (err) { const msg = err instanceof Error ? err.message : String(err); const errorCode = isDbClientNotReadyError(err) ? 'HOST_NOT_READY' : 'INTERNAL'; return { ok: false, errorCode, message: msg }; }
},
getMessages: async (args) => {
return readChatHistoryMessages(args, {
@@ -414,7 +433,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
},
searchChatHistory: async (args) => {
try { const result = await searchChatHistoryHybrid(args); return { ok: true, result }; }
- catch (err) { const msg = err instanceof Error ? err.message : String(err); const errorCode = /localDb not ready/i.test(msg) ? 'HOST_NOT_READY' : 'INTERNAL'; return { ok: false, errorCode, message: msg }; }
+ catch (err) { const msg = err instanceof Error ? err.message : String(err); const errorCode = isDbClientNotReadyError(err) ? 'HOST_NOT_READY' : 'INTERNAL'; return { ok: false, errorCode, message: msg }; }
},
},
// submit_github_issue: 官方反馈提交(确认卡片 → serverApiFetch)。
diff --git a/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.ts b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.ts
index c50f9bb02a..b74500f17c 100644
--- a/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.ts
+++ b/apps/desktop/src/main/worklouder-codex/WorkLouderCodexLightingController.ts
@@ -1,4 +1,3 @@
-import type { AgentIslandSessionActivity } from '../../shared/agentIsland.js';
import {
WORKLOUDER_CODEX_AGENT_SLOT_COUNT,
WORKLOUDER_CODEX_EMPTY_DEVICE_STATE,
@@ -30,6 +29,7 @@ import {
type WorkLouderCodexHidEvent,
type WorkLouderCodexJoystickEvent,
type WorkLouderCodexLightingFrame,
+ type WorkLouderCodexSessionActivity,
} from './protocol.js';
import type { WorkLouderCodexTaskCatalog } from './taskSlots.js';
import {
@@ -77,7 +77,7 @@ type TaskCatalogLoader = () => Promise<WorkLouderCodexTaskCatalog | readonly str
export class WorkLouderCodexLightingController {
private lastFrameKey = '';
private slotSessionIds: string[] = [];
- private latestActivity: readonly AgentIslandSessionActivity[] = [];
+ private latestActivity: readonly WorkLouderCodexSessionActivity[] = [];
private taskCatalog: WorkLouderCodexTaskCatalog = { sidebar: [], lastSent: [], options: [] };
private agentSlots: WorkLouderCodexAgentSlotState[] = emptyAgentSlots();
private slotRefreshVersion = 0;
@@ -137,7 +137,7 @@ export class WorkLouderCodexLightingController {
}
}
- updateSessionActivity(activity: readonly AgentIslandSessionActivity[]): void {
+ updateSessionActivity(activity: readonly WorkLouderCodexSessionActivity[]): void {
this.latestActivity = activity;
if (this.settings.agentSource === 'priority') this.publishAgentSlots();
this.updateLightingFrame(true);
@@ -842,7 +842,7 @@ function actionTitle(action: WorkLouderCodexAction | null): string | null {
}
}
-function activityPriority(activity: AgentIslandSessionActivity): number {
+function activityPriority(activity: WorkLouderCodexSessionActivity): number {
if (activity.phase === 'needs-interaction') return 5;
if (activity.attention) return 4;
if (activity.phase === 'error') return 3;
diff --git a/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.ts b/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.ts
index 466d10e49d..13627f89b4 100644
--- a/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.ts
+++ b/apps/desktop/src/main/worklouder-codex/__tests__/protocol.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, it } from 'vitest';
-import type { AgentIslandSessionActivity } from '../../../shared/agentIsland.js';
import {
applyWorkLouderCodexLightingBrightness,
createWorkLouderCodexOffFrame,
@@ -10,14 +9,15 @@ import {
isWorkLouderCodexLightingFrameOff,
parseWorkLouderCodexAgentKeyPress,
projectWorkLouderCodexSlotActivity,
+ type WorkLouderCodexSessionActivity,
WorkLouderLightingEffect,
} from '../protocol.js';
function activity(
sessionId: string,
- phase: AgentIslandSessionActivity['phase'],
+ phase: WorkLouderCodexSessionActivity['phase'],
attention = false,
-): AgentIslandSessionActivity {
+): WorkLouderCodexSessionActivity {
return { sessionId, phase, compactDetail: '', attention };
}
diff --git a/apps/desktop/src/main/worklouder-codex/protocol.ts b/apps/desktop/src/main/worklouder-codex/protocol.ts
index 26af56bb73..0c82593283 100644
--- a/apps/desktop/src/main/worklouder-codex/protocol.ts
+++ b/apps/desktop/src/main/worklouder-codex/protocol.ts
@@ -17,6 +17,12 @@ export const enum WorkLouderLightingEffect {
ShallowBreath = 6,
}
+/** Hardware lighting consumes only the stable activity facets it renders. */
+export type WorkLouderCodexSessionActivity = Pick<
+ AgentIslandSessionActivity,
+ 'sessionId' | 'phase' | 'attention' | 'compactDetail'
+>;
+
export interface WorkLouderLightingSide {
effect: WorkLouderLightingEffect;
brightness: number;
@@ -97,7 +103,7 @@ const OFF_SIDE: WorkLouderLightingSide = {
color: 0,
};
-const PHASE_PRIORITY: Readonly<Record<AgentIslandSessionActivity['phase'], number>> = {
+const PHASE_PRIORITY: Readonly<Record<WorkLouderCodexSessionActivity['phase'], number>> = {
'needs-interaction': 4,
error: 3,
running: 2,
@@ -109,11 +115,11 @@ const PHASE_PRIORITY: Readonly<Record<AgentIslandSessionActivity['phase'], numbe
* zones plus its six per-thread indicators.
*/
export function createWorkLouderCodexLightingFrame(
- activity: readonly AgentIslandSessionActivity[],
+ activity: readonly WorkLouderCodexSessionActivity[],
slotSessionIds?: readonly string[],
): WorkLouderCodexLightingFrame {
const slots = projectWorkLouderCodexSlotActivity(activity, slotSessionIds);
- const aggregate = slots.reduce<AgentIslandSessionActivity['phase'] | null>((current, item) => {
+ const aggregate = slots.reduce<WorkLouderCodexSessionActivity['phase'] | null>((current, item) => {
if (!item) return current;
return current === null || PHASE_PRIORITY[item.phase] > PHASE_PRIORITY[current]
? item.phase
@@ -131,16 +137,16 @@ export function createWorkLouderCodexLightingFrame(
/** The ordered task assignment shared by the six LEDs and their physical keys. */
export function selectWorkLouderCodexSlotActivity(
- activity: readonly AgentIslandSessionActivity[],
-): AgentIslandSessionActivity[] {
+ activity: readonly WorkLouderCodexSessionActivity[],
+): WorkLouderCodexSessionActivity[] {
return activity.filter(isLightingVisibleActivity).slice(0, WORKLOUDER_CODEX_AGENT_SLOT_COUNT);
}
/** Aligns activity LEDs with an explicit six-task key assignment when one is available. */
export function projectWorkLouderCodexSlotActivity(
- activity: readonly AgentIslandSessionActivity[],
+ activity: readonly WorkLouderCodexSessionActivity[],
slotSessionIds?: readonly string[],
-): Array<AgentIslandSessionActivity | undefined> {
+): Array<WorkLouderCodexSessionActivity | undefined> {
if (slotSessionIds === undefined) return selectWorkLouderCodexSlotActivity(activity);
const visibleBySessionId = new Map(
activity.filter(isLightingVisibleActivity).map((item) => [item.sessionId, item] as const),
@@ -331,7 +337,7 @@ function isWorkLouderCodexDeviceState(value: unknown): value is WorkLouderCodexD
);
}
-function isLightingVisibleActivity(activity: AgentIslandSessionActivity): boolean {
+function isLightingVisibleActivity(activity: WorkLouderCodexSessionActivity): boolean {
return (
activity.phase === 'running' ||
activity.phase === 'needs-interaction' ||
@@ -339,7 +345,7 @@ function isLightingVisibleActivity(activity: AgentIslandSessionActivity): boolea
);
}
-function ambientForPhase(phase: AgentIslandSessionActivity['phase']): WorkLouderLightingSide {
+function ambientForPhase(phase: WorkLouderCodexSessionActivity['phase']): WorkLouderLightingSide {
switch (phase) {
case 'running':
return side(WorkLouderLightingEffect.Snake, 0.7, 0.4, COLORS.running);
@@ -352,7 +358,7 @@ function ambientForPhase(phase: AgentIslandSessionActivity['phase']): WorkLouder
}
}
-function keysForPhase(phase: AgentIslandSessionActivity['phase']): WorkLouderLightingSide {
+function keysForPhase(phase: WorkLouderCodexSessionActivity['phase']): WorkLouderLightingSide {
const effect =
phase === 'error' ? WorkLouderLightingEffect.Breath : WorkLouderLightingEffect.Solid;
const brightness = phase === 'needs-interaction' || phase === 'error' ? 0.28 : 0.16;
@@ -361,7 +367,7 @@ function keysForPhase(phase: AgentIslandSessionActivity['phase']): WorkLouderLig
function threadForActivity(
id: number,
- activity: AgentIslandSessionActivity | undefined,
+ activity: WorkLouderCodexSessionActivity | undefined,
): WorkLouderThreadLighting {
if (!activity) {
return {
diff --git a/apps/desktop/src/renderer/__tests__/sidebarAttentionBadge.test.ts b/apps/desktop/src/renderer/__tests__/sidebarAttentionBadge.test.ts
index 81d9b32f96..b3c4c7b72e 100644
--- a/apps/desktop/src/renderer/__tests__/sidebarAttentionBadge.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sidebarAttentionBadge.test.ts
@@ -15,7 +15,10 @@ import { cleanup, render } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { Session } from '@/lib/ccAgent.types';
-import { resolveSidebarRightStatus } from '../features/cc-agent/sidebar/sidebarRightStatus';
+import {
+ projectSidebarSessionActivity,
+ resolveSidebarRightStatus,
+} from '../features/cc-agent/sidebar/sidebarRightStatus';
import { SessionStatusIcon } from '../features/cc-agent/sidebar/SessionStatusIcon';
const sidebarState = vi.hoisted(() => ({
@@ -67,56 +70,127 @@ function attentionDot(container: HTMLElement): Element | undefined {
describe('sidebar right status priority', () => {
it('keeps error/awaiting above running and running above unread-done', () => {
+ const resolve = (input: Parameters<typeof projectSidebarSessionActivity>[0]) =>
+ resolveSidebarRightStatus(projectSidebarSessionActivity(input));
// error(chat 侧错误终止)压过 running 与其它一切
- expect(resolveSidebarRightStatus({
+ expect(resolve({
+ sessionId: 'session-1',
attentionKind: 'error',
isUrgentFromContext: false,
isRunning: true,
hasAttentionNotification: true,
})).toBe('error');
+ const runningWithStaleError = projectSidebarSessionActivity({
+ sessionId: 'session-1',
+ attentionKind: 'error',
+ isUrgentFromContext: false,
+ isRunning: true,
+ hasAttentionNotification: true,
+ });
+ expect(runningWithStaleError).toMatchObject({
+ phase: 'error',
+ attention: true,
+ currentTurnActive: true,
+ });
+ expect(resolveSidebarRightStatus(runningWithStaleError)).toBe('error');
+ // device-link 镜像可以同时保留 stale error 与新一轮运行 facet;本地
+ // isRunning 对远程会话恒 false,仍须让左侧 vendor mark 保持呼吸。
+ const remoteRunningWithStaleError = projectSidebarSessionActivity({
+ sessionId: 'remote-session',
+ liveActivity: {
+ phase: 'error',
+ currentTurnActive: true,
+ source: 'live',
+ },
+ attentionKind: undefined,
+ isUrgentFromContext: true,
+ isRunning: false,
+ hasAttentionNotification: false,
+ });
+ expect(remoteRunningWithStaleError).toMatchObject({
+ phase: 'error',
+ attention: true,
+ currentTurnActive: true,
+ });
+ expect(resolveSidebarRightStatus(remoteRunningWithStaleError)).toBe('error');
// 定时任务失败未读(attentionKind 缺失,由 urgency context 注入)同样是 error 档
- expect(resolveSidebarRightStatus({
+ expect(resolve({
+ sessionId: 'session-1',
attentionKind: undefined,
isUrgentFromContext: true,
isRunning: true,
hasAttentionNotification: true,
})).toBe('error');
+ expect(projectSidebarSessionActivity({
+ sessionId: 'session-1',
+ liveActivity: { phase: 'running' },
+ attentionKind: undefined,
+ isUrgentFromContext: true,
+ isRunning: false,
+ hasAttentionNotification: false,
+ })).toMatchObject({
+ phase: 'error',
+ attention: true,
+ currentTurnActive: true,
+ });
+ // automation failure urgency is durable outside the notification store:
+ // after restart, unread expiry or acknowledgement it must still stay red.
+ expect(resolve({
+ sessionId: 'session-1',
+ attentionKind: undefined,
+ isUrgentFromContext: true,
+ isRunning: false,
+ hasAttentionNotification: false,
+ })).toBe('error');
+ expect(resolve({
+ sessionId: 'session-1',
+ attentionKind: 'done',
+ isUrgentFromContext: true,
+ isRunning: false,
+ hasAttentionNotification: false,
+ })).toBe('error');
// awaiting(ask-user / 权限 / 计划审阅)压过 running,但低于 error
- expect(resolveSidebarRightStatus({
+ expect(resolve({
+ sessionId: 'session-1',
attentionKind: 'awaiting',
isUrgentFromContext: false,
isRunning: true,
hasAttentionNotification: true,
})).toBe('awaiting');
// running 压过完成未读
- expect(resolveSidebarRightStatus({
+ expect(resolve({
+ sessionId: 'session-1',
attentionKind: 'done',
isUrgentFromContext: false,
isRunning: true,
hasAttentionNotification: true,
})).toBe('running');
// 完成未读(含 attentionKind 缺失的定时任务未读)→ done
- expect(resolveSidebarRightStatus({
+ expect(resolve({
+ sessionId: 'session-1',
attentionKind: 'done',
isUrgentFromContext: false,
isRunning: false,
hasAttentionNotification: true,
})).toBe('done');
- expect(resolveSidebarRightStatus({
+ expect(resolve({
+ sessionId: 'session-1',
attentionKind: undefined,
isUrgentFromContext: false,
isRunning: false,
hasAttentionNotification: true,
})).toBe('done');
// 没有任何 attention → time
- expect(resolveSidebarRightStatus({
+ expect(resolve({
+ sessionId: 'session-1',
attentionKind: undefined,
isUrgentFromContext: false,
isRunning: false,
hasAttentionNotification: false,
})).toBe('time');
// attention 已被查看清零(hasAttentionNotification=false)时,残留 kind 不生效
- expect(resolveSidebarRightStatus({
+ expect(resolve({
+ sessionId: 'session-1',
attentionKind: 'error',
isUrgentFromContext: false,
isRunning: false,
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
index bfda29f930..92bd328169 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
@@ -31,7 +31,11 @@ import type { SessionClickHandler } from './SessionItem';
import { MENU_CONTENT_CLASS, MENU_ITEM_CLASS, MENU_SEPARATOR_CLASS } from './menuStyles';
import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyContext';
import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
-import { resolveSidebarRightStatus } from './sidebarRightStatus';
+import { useAgentIslandActivity } from '@/state/agentIslandActivity';
+import {
+ projectSidebarSessionActivity,
+ resolveSidebarRightStatus,
+} from './sidebarRightStatus';
import { AutomationTimerIcon } from './AutomationTimerIcon';
import { SessionCard } from './SessionCard';
import type { FolderPickerOption } from '@/components/new-chat/FolderPickerPopover';
@@ -157,6 +161,7 @@ export function AutomationSessionGroupItem({
// (性能不变量,别退回整组 / 整张表订阅)。
const latestUrgentFromSchedule = useSessionAttentionUrgency(latestSessionId ?? '');
const latestChatKind = useSessionAttentionKind(latestSessionId ?? '');
+ const latestLiveActivity = useAgentIslandActivity(latestSessionId ?? '');
const scheduleId = group.scheduleId;
// 「已停止」= paused(用户主动暂停)+ expired(计划到期不再触发);两者对用户体验
// 而言都是「不会再自动跑」,视觉上都在 Timer chip 上叠 Pause 徽标,并在 tooltip
@@ -181,12 +186,17 @@ export function AutomationSessionGroupItem({
// done 绿 / time 文字):四个 input 全部取「最新一条」运行,送进同一 resolveSidebarRightStatus,
// 于是组头右侧状态与最新 session 子行像素级一致(色号 / 图标尺寸 / 判定完全同源)。
const latestHasNotification = latestSessionId != null && notifications.has(latestSessionId);
- const groupRightStatusKind = resolveSidebarRightStatus({
+ const groupActivity = projectSidebarSessionActivity({
+ sessionId: latestSessionId ?? '',
+ title: latestSession?.title,
+ recordStatus: latestSession?.status,
+ liveActivity: latestLiveActivity,
attentionKind: latestChatKind,
isUrgentFromContext: latestUrgentFromSchedule,
isRunning,
hasAttentionNotification: latestHasNotification,
});
+ const groupRightStatusKind = resolveSidebarRightStatus(groupActivity);
const showRightStatus = groupRightStatusKind !== 'time';
const actionButtonToneClassName = hasActiveHidden
? 'text-sidebar-item-active-foreground hover:text-sidebar-item-active-foreground hover:bg-[color-mix(in_srgb,var(--sidebar-item-active-foreground)_14%,transparent)]'
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
index ee1745818d..47ae668f04 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -87,7 +87,10 @@ import {
scheduleFocusPath,
} from '@/features/scheduler/lib/scheduleSessionBinding';
import { loadScheduleSidebarIndexRuns } from '@/features/scheduler/lib/scheduleSidebarIndexRuns';
-import { resolveSidebarRightStatus } from './sidebarRightStatus';
+import {
+ projectSidebarSessionActivity,
+ resolveSidebarRightStatus,
+} from './sidebarRightStatus';
import { Tip } from '@/components/ui/tooltip';
import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';
import { shouldPrefetchSessionOnPointerDown } from './sessionSwitchPrefetch';
@@ -166,28 +169,18 @@ export function SessionCard({
const attentionKind = useSessionAttentionKind(session.id);
const isUrgentFromContext = useSessionAttentionUrgency(session.id);
const remoteActivity = useRemoteSessionActivity(session.id);
- const remoteRightStatus =
- remoteActivity == null
- ? null
- : remoteActivity.phase === 'error'
- ? ('error' as const)
- : remoteActivity.phase === 'needs-interaction'
- ? ('awaiting' as const)
- : remoteActivity.phase === 'running'
- ? ('running' as const)
- : ('done' as const);
- // 左侧 vendor mark 呼吸原先只看本地 running 集;远程会话的运行态只进了右侧
- // 状态槽。只并入 phase=running,与 SessionItem / 折叠 rail 同一口径;
- // needs-interaction 继续由右侧 awaiting 表达。
- const leftIconRunning = isRunning || remoteActivity?.phase === 'running';
- const rightStatusKind =
- remoteRightStatus ??
- resolveSidebarRightStatus({
- attentionKind,
- isUrgentFromContext,
- isRunning,
- hasAttentionNotification,
- });
+ const sessionActivity = projectSidebarSessionActivity({
+ sessionId: session.id,
+ title: session.title,
+ recordStatus: session.status,
+ liveActivity: remoteActivity ?? islandActivity,
+ attentionKind,
+ isUrgentFromContext,
+ isRunning,
+ hasAttentionNotification,
+ });
+ const leftIconRunning = sessionActivity.currentTurnActive === true;
+ const rightStatusKind = resolveSidebarRightStatus(sessionActivity);
const isPinned = session.pinnedAt != null;
const isEmpty = isEmptyDraftSession(session);
const activityIso = session.updatedAt;
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
index b5098c015f..53eabe9d77 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -93,7 +93,11 @@ import { prefetchDirtyWorktreeForRemoval } from '@/lib/worktreeRemovalWarning';
import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyContext';
import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
-import { resolveSidebarRightStatus } from './sidebarRightStatus';
+import { useAgentIslandActivity } from '@/state/agentIslandActivity';
+import {
+ projectSidebarSessionActivity,
+ resolveSidebarRightStatus,
+} from './sidebarRightStatus';
import { AutomationTimerIcon } from './AutomationTimerIcon';
import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';
import {
@@ -392,32 +396,23 @@ export const SessionItem = memo(function SessionItem({
// 通过 SessionAttentionUrgencyContext 由上游注入,避免误把失败的 automation 涂成 Completed。
const attentionKind = useSessionAttentionKind(session.id);
const isUrgentFromContext = useSessionAttentionUrgency(session.id);
+ const islandActivity = useAgentIslandActivity(session.id);
// device-link 远程会话行:本地 attention/running 链路对被控端后台会话是盲区,状态改由
// 被控端灵动岛 relay 的活动镜像驱动(remoteSessionActivityStore,按行精准订阅;本地
// 会话恒 undefined 零开销)。镜像只保留活跃态与未读终态,映射与本地五档同一张色表。
const remoteActivity = useRemoteSessionActivity(session.id);
- const remoteRightStatus =
- remoteActivity == null
- ? null
- : remoteActivity.phase === 'error'
- ? ('error' as const)
- : remoteActivity.phase === 'needs-interaction'
- ? ('awaiting' as const)
- : remoteActivity.phase === 'running'
- ? ('running' as const)
- : ('done' as const);
- // 左侧 vendor mark 呼吸原先只看本地 running 集;远程会话的运行态只进了右侧
- // 状态槽,图标颜色不会刷新。只并入 phase=running,与折叠 rail 的 remoteLampOf
- // 以及本地 pending-prompt 口径一致:needs-interaction 继续由右侧 awaiting 表达。
- const leftIconRunning = isRunning || remoteActivity?.phase === 'running';
- const rightStatusKind =
- remoteRightStatus ??
- resolveSidebarRightStatus({
- attentionKind,
- isUrgentFromContext,
- isRunning,
- hasAttentionNotification,
- });
+ const sessionActivity = projectSidebarSessionActivity({
+ sessionId: session.id,
+ title: session.title,
+ recordStatus: session.status,
+ liveActivity: remoteActivity ?? islandActivity,
+ attentionKind,
+ isUrgentFromContext,
+ isRunning,
+ hasAttentionNotification,
+ });
+ const leftIconRunning = sessionActivity.currentTurnActive === true;
+ const rightStatusKind = resolveSidebarRightStatus(sessionActivity);
const showRightStatus = rightStatusKind !== 'time';
const remoteIconKind = session.deviceLinkDeviceId
? 'device-link'
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
index eabddebadb..f524ab4b45 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
@@ -123,17 +123,19 @@ describe('SessionCard review regressions', () => {
expect(sessionCardSource).not.toContain('titlePrefixWidth');
});
- it('merges remote activity into the left vendor-mark running state', () => {
- // 远程会话的运行态原先只进右侧状态槽,左侧图标仍只看本地 running 集。
- // 只并入 phase=running,与折叠 rail / remoteLampOf 同一口径;
- // needs-interaction 继续由右侧 awaiting 表达。
+ it('projects local and remote activity through the shared session status model', () => {
+ // 左侧运行标记和右侧状态槽必须消费同一投影,避免各自组合本地/远程状态源。
+ expect(sessionItemSource).toContain('projectSidebarSessionActivity({');
expect(sessionItemSource).toContain(
- "const leftIconRunning = isRunning || remoteActivity?.phase === 'running'",
+ 'const leftIconRunning = sessionActivity.currentTurnActive === true',
);
+ expect(sessionItemSource).toContain('resolveSidebarRightStatus(sessionActivity)');
expect(sessionItemSource).toContain('isRunning={leftIconRunning}');
+ expect(sessionCardSource).toContain('projectSidebarSessionActivity({');
expect(sessionCardSource).toContain(
- "const leftIconRunning = isRunning || remoteActivity?.phase === 'running'",
+ 'const leftIconRunning = sessionActivity.currentTurnActive === true',
);
+ expect(sessionCardSource).toContain('resolveSidebarRightStatus(sessionActivity)');
expect(sessionCardSource).toContain('isRunning={leftIconRunning}');
expect(sessionCardSource).not.toContain('isRemoteSessionActivityActive');
expect(sessionItemSource).not.toContain('isRemoteSessionActivityActive');
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts
index 6fba411d5a..27aa6a585e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sidebarRightStatus.ts
@@ -1,8 +1,28 @@
+import {
+ projectSessionActivity,
+ type SessionActivitySnapshot,
+} from '@cindy/maker-shared/session-activity';
+
import type { AttentionKind } from '@/lib/sessionAttentionStore';
export type SidebarRightStatusKind = 'error' | 'awaiting' | 'running' | 'done' | 'time';
export interface SidebarRightStatusInput {
+ sessionId: string;
+ title?: string | null;
+ recordStatus?: SessionActivitySnapshot['recordStatus'];
+ liveActivity?: {
+ phase: SessionActivitySnapshot['phase'];
+ recordStatus?: SessionActivitySnapshot['recordStatus'];
+ compactDetail?: string;
+ currentActionSummary?: string | null;
+ interactionKind?: string;
+ attention?: boolean;
+ currentTurnActive?: boolean;
+ startedAtMs?: number | null;
+ lastActivityAtMs?: number | null;
+ source?: SessionActivitySnapshot['source'];
+ } | null;
/**
* store 记录的 attention kind(按 sessionId 精准订阅取得);
* 定时任务未读(attentionKind 缺失)语义等同 'done'。
@@ -14,20 +34,52 @@ export interface SidebarRightStatusInput {
hasAttentionNotification: boolean;
}
+/** Collapse local/remote live state and legacy attention fallbacks into one model. */
+export function projectSidebarSessionActivity({
+ sessionId,
+ title,
+ recordStatus,
+ liveActivity,
+ attentionKind,
+ isUrgentFromContext,
+ isRunning,
+ hasAttentionNotification,
+}: SidebarRightStatusInput): SessionActivitySnapshot {
+ const errorAttention =
+ isUrgentFromContext || (hasAttentionNotification && attentionKind === 'error');
+ const awaitingAttention = hasAttentionNotification && attentionKind === 'awaiting';
+ const doneAttention = hasAttentionNotification && !errorAttention && !awaitingAttention;
+ return projectSessionActivity({
+ sessionId,
+ recordStatus: liveActivity?.recordStatus ?? recordStatus,
+ title,
+ source: liveActivity?.source ?? 'fallback',
+ livePhase: liveActivity?.phase ?? null,
+ running: isRunning || liveActivity?.currentTurnActive === true,
+ waitingForUser: awaitingAttention,
+ terminal: errorAttention ? 'error' : doneAttention ? 'completed' : null,
+ startedAtMs: liveActivity?.startedAtMs,
+ lastActivityAtMs: liveActivity?.lastActivityAtMs,
+ currentActionSummary: liveActivity?.currentActionSummary ?? null,
+ interactionKind: liveActivity?.interactionKind,
+ // Automation failure urgency intentionally lives outside the regular
+ // attention-notification store. Preserve it in the canonical projection so
+ // restart/expiry/acknowledgement cannot erase the existing red error state.
+ attention: liveActivity?.attention === true || hasAttentionNotification || isUrgentFromContext,
+ });
+}
+
/**
* 右侧状态槽优先级:error > awaiting > running > done(完成未读)> time。
* error / awaiting 拆成两档两色(红 / TapTap 蓝),与灵动岛 phase 色表一致;
* 两者都压过 running spinner —— "需要你处理"永远最高。
*/
-export function resolveSidebarRightStatus({
- attentionKind,
- isUrgentFromContext,
- isRunning,
- hasAttentionNotification,
-}: SidebarRightStatusInput): SidebarRightStatusKind {
- if (isUrgentFromContext || (hasAttentionNotification && attentionKind === 'error')) return 'error';
- if (hasAttentionNotification && attentionKind === 'awaiting') return 'awaiting';
- if (isRunning) return 'running';
- if (hasAttentionNotification) return 'done';
+export function resolveSidebarRightStatus(
+ activity: Pick<SessionActivitySnapshot, 'phase' | 'attention'>,
+): SidebarRightStatusKind {
+ if (activity.phase === 'error' && activity.attention) return 'error';
+ if (activity.phase === 'needs-interaction') return 'awaiting';
+ if (activity.phase === 'running') return 'running';
+ if (activity.phase === 'completed' && activity.attention) return 'done';
return 'time';
}
diff --git a/apps/desktop/src/renderer/state/agentIslandActivity.ts b/apps/desktop/src/renderer/state/agentIslandActivity.ts
index ecd27bc05c..5a97eb46c0 100644
--- a/apps/desktop/src/renderer/state/agentIslandActivity.ts
+++ b/apps/desktop/src/renderer/state/agentIslandActivity.ts
@@ -26,9 +26,19 @@ function emit(): void {
function sameActivity(a: AgentIslandSessionActivity, b: AgentIslandSessionActivity): boolean {
return (
a.phase === b.phase &&
+ a.recordStatus === b.recordStatus &&
a.compactDetail === b.compactDetail &&
+ a.currentActionSummary === b.currentActionSummary &&
a.interactionKind === b.interactionKind &&
- a.attention === b.attention
+ a.attention === b.attention &&
+ a.startedAtMs === b.startedAtMs &&
+ a.lastActivityAtMs === b.lastActivityAtMs &&
+ a.workflow?.key === b.workflow?.key &&
+ a.workflow?.label === b.workflow?.label &&
+ a.workflow?.waitingOn === b.workflow?.waitingOn &&
+ a.turnGeneration === b.turnGeneration &&
+ a.gracefulStopState === b.gracefulStopState &&
+ a.source === b.source
);
}
diff --git a/apps/desktop/src/shared/agentInputQueue.ts b/apps/desktop/src/shared/agentInputQueue.ts
index 263ff89e96..b10ebbd6f2 100644
--- a/apps/desktop/src/shared/agentInputQueue.ts
+++ b/apps/desktop/src/shared/agentInputQueue.ts
@@ -237,6 +237,13 @@ export interface AgentInputQueuedMessage {
scheduleName: string;
/** 老队列快照可能没有;新 scheduler run 始终写入。 */
runId?: string;
+ }
+ | {
+ /** cindy_helper 的 send_to_session 入队来源;只用于本人排队消息控制授权。 */
+ kind: 'session';
+ senderSessionId: string;
+ /** 原始可编辑正文;单独保留以兼容未来可能加入的派发包装。 */
+ displayText: string;
};
/**
* 本条由**手机控制端**入队 / 插入。
diff --git a/apps/desktop/src/shared/agentIsland.ts b/apps/desktop/src/shared/agentIsland.ts
index b07f9638d4..62e40259d2 100644
--- a/apps/desktop/src/shared/agentIsland.ts
+++ b/apps/desktop/src/shared/agentIsland.ts
@@ -1,4 +1,5 @@
import { BRAND_NAME } from '@cindy/maker-shared/branding';
+import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
export type AgentIslandSessionPhase = 'running' | 'needs-interaction' | 'completed' | 'error';
@@ -48,12 +49,12 @@ export interface AgentIslandPermissionActionSnapshot {
* 让卡片在任务执行中显示与灵动岛同源的逐步活动 + 等待交互态。只取卡片要的字段
* (不含 activityLines 多行,控体积)。
*/
-export interface AgentIslandSessionActivity {
- sessionId: string;
+export interface AgentIslandSessionActivity
+ extends Omit<SessionActivitySnapshot, 'phase' | 'interactionKind'> {
phase: AgentIslandSessionPhase;
- compactDetail: string;
interactionKind?: AgentIslandInteractionKind;
- attention: boolean;
+ /** Compatibility/display alias; canonical probe field is currentActionSummary. */
+ compactDetail: string;
}
export type AgentIslandDisplayMode = 'compact' | 'expanded';
diff --git a/packages/lizi-mcps/src/__tests__/getChatHistoryToolContract.test.ts b/packages/lizi-mcps/src/__tests__/getChatHistoryToolContract.test.ts
index 09a2b494b1..e71c9fd6b8 100644
--- a/packages/lizi-mcps/src/__tests__/getChatHistoryToolContract.test.ts
+++ b/packages/lizi-mcps/src/__tests__/getChatHistoryToolContract.test.ts
@@ -22,8 +22,8 @@ describe('get_chat_history published contract', () => {
const capability = CAPABILITIES.find((entry) => entry.key === 'chat-history-query');
expect(capability).toBeDefined();
- expect(capability!.detail).toContain('开放了四个只读查询入口');
- expect(capability!.detail).not.toContain('开放了三个只读查询入口');
+ expect(capability!.detail).toContain('开放了五个只读查询入口');
+ expect(capability!.detail).not.toContain('开放了四个只读查询入口');
expect(capability!.detail).toContain('get_chat_history({session_ids: [...]})');
expect(capability!.detail).not.toContain('get_chat_history({sessionIds: [...]})');
});
diff --git a/packages/lizi-mcps/src/__tests__/listSessionQueueTool.test.ts b/packages/lizi-mcps/src/__tests__/listSessionQueueTool.test.ts
new file mode 100644
index 0000000000..76047ce3a2
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/listSessionQueueTool.test.ts
@@ -0,0 +1,152 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { XdtHelperToolRegistry } from "../lizi_xdtHelperToolRegistry.js";
+import {
+ registerListSessionQueueTool,
+ type SessionQueueDeps,
+} from "../xdt-helper/list_session_queue.js";
+
+function parse(result: {
+ content: Array<{ type: string; text?: string }>;
+}): Record<string, unknown> {
+ const first = result.content[0];
+ if (!first || first.type !== "text" || !first.text)
+ throw new Error("missing text payload");
+ return JSON.parse(first.text) as Record<string, unknown>;
+}
+
+describe("list_session_queue", () => {
+ it("returns ordered queue metadata with bounded content summaries", async () => {
+ const longContent = ` first\nmessage ${"界".repeat(510)}`;
+ const deps: SessionQueueDeps = {
+ listSessionQueue: vi.fn(async () => ({
+ ok: true as const,
+ messages: [
+ {
+ queuedMessageId: "q-1",
+ position: 0,
+ source: "orca" as const,
+ sourceLabel: "Lead",
+ enqueuedAtMs: Date.parse("2026-08-16T01:02:03.000Z"),
+ content: longContent,
+ consuming: true,
+ },
+ {
+ queuedMessageId: "q-2",
+ position: 1,
+ source: "user" as const,
+ sourceLabel: null,
+ enqueuedAtMs: null,
+ content: "follow up",
+ consuming: false,
+ },
+ {
+ queuedMessageId: "q-3",
+ position: 2,
+ source: "session" as const,
+ sourceLabel: "sender-session",
+ enqueuedAtMs: Date.parse("2026-08-16T01:02:04.000Z"),
+ content: "cross-session follow up",
+ consuming: false,
+ },
+ ],
+ })),
+ listSessionQueuedCounts: vi.fn(),
+ };
+ const registry = new XdtHelperToolRegistry();
+ registerListSessionQueueTool(registry, deps);
+
+ const payload = parse(
+ await registry.call("list_session_queue", { session_id: "session-1" }),
+ );
+
+ expect(payload).toMatchObject({
+ ok: true,
+ session_id: "session-1",
+ queued_count: 3,
+ queue: [
+ {
+ queued_message_id: "q-1",
+ position: 0,
+ source: "orca",
+ source_label: "Lead",
+ enqueued_at: "2026-08-16T01:02:03.000Z",
+ truncated: true,
+ consuming: true,
+ },
+ {
+ queued_message_id: "q-2",
+ position: 1,
+ source: "user",
+ enqueued_at: null,
+ content_summary: "follow up",
+ truncated: false,
+ consuming: false,
+ },
+ {
+ queued_message_id: "q-3",
+ position: 2,
+ source: "session",
+ source_label: "sender-session",
+ enqueued_at: "2026-08-16T01:02:04.000Z",
+ content_summary: "cross-session follow up",
+ truncated: false,
+ consuming: false,
+ },
+ ],
+ });
+ const queue = payload.queue as Array<Record<string, unknown>>;
+ expect(Array.from(String(queue[0]?.content_summary)).length).toBe(501);
+ expect(queue[1]).not.toHaveProperty("source_label");
+ expect(deps.listSessionQueue).toHaveBeenCalledWith("session-1");
+ });
+
+ it("maps missing sessions and host failures to stable errors", async () => {
+ const listSessionQueue = vi
+ .fn<SessionQueueDeps["listSessionQueue"]>()
+ .mockResolvedValueOnce({
+ ok: false as const,
+ errorCode: "NOT_FOUND" as const,
+ message: "missing",
+ })
+ .mockResolvedValueOnce({
+ ok: false as const,
+ errorCode: "HOST_NOT_READY" as const,
+ message: "booting",
+ })
+ .mockResolvedValueOnce({
+ ok: false as const,
+ errorCode: "INTERNAL" as const,
+ message: "restore failed",
+ });
+ const registry = new XdtHelperToolRegistry();
+ registerListSessionQueueTool(registry, {
+ listSessionQueue,
+ listSessionQueuedCounts: vi.fn(),
+ });
+
+ expect(
+ parse(await registry.call("list_session_queue", { session_id: "gone" })),
+ ).toMatchObject({
+ ok: false,
+ errorCode: "NOT_FOUND",
+ });
+ expect(
+ parse(
+ await registry.call("list_session_queue", { session_id: "booting" }),
+ ),
+ ).toMatchObject({
+ ok: false,
+ errorCode: "HOST_NOT_READY",
+ });
+ expect(
+ parse(
+ await registry.call("list_session_queue", { session_id: "broken" }),
+ ),
+ ).toMatchObject({
+ ok: false,
+ errorCode: "INTERNAL",
+ data: { hint: "restore failed" },
+ });
+ });
+});
diff --git a/packages/lizi-mcps/src/__tests__/listSessionsTool.test.ts b/packages/lizi-mcps/src/__tests__/listSessionsTool.test.ts
new file mode 100644
index 0000000000..96a106464a
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/listSessionsTool.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { XdtHelperToolRegistry } from "../lizi_xdtHelperToolRegistry.js";
+import type { XdtHelperHistoryDeps } from "../xdt-helper/_history_types.js";
+import { registerListSessionsTool } from "../xdt-helper/list_sessions.js";
+import type { SessionQueueDeps } from "../xdt-helper/list_session_queue.js";
+
+function parse(result: {
+ content: Array<{ type: string; text?: string }>;
+}): Record<string, unknown> {
+ const first = result.content[0];
+ if (!first || first.type !== "text" || !first.text)
+ throw new Error("missing text payload");
+ return JSON.parse(first.text) as Record<string, unknown>;
+}
+
+function historyWithSessions(): XdtHelperHistoryDeps {
+ return {
+ listWorkdirs: vi.fn(),
+ listSessions: vi.fn(async () => ({
+ ok: true as const,
+ page: {
+ items: [
+ {
+ id: "session-1",
+ title: "Busy",
+ workingDir: "/repo",
+ agentKind: "codex",
+ workspaceKind: "project",
+ model: "gpt-5.6",
+ status: "active",
+ source: "desktop",
+ orcaRole: null,
+ parentSessionId: null,
+ createdAt: 1,
+ updatedAt: 2,
+ userSendAt: null,
+ messageCount: 3,
+ },
+ {
+ id: "session-2",
+ title: "Idle",
+ workingDir: "/repo",
+ agentKind: "cc",
+ workspaceKind: "project",
+ model: "claude",
+ status: "active",
+ source: "desktop",
+ orcaRole: null,
+ parentSessionId: null,
+ createdAt: 3,
+ updatedAt: 4,
+ userSendAt: null,
+ messageCount: 1,
+ },
+ ],
+ nextCursor: null,
+ hasMore: false,
+ },
+ })),
+ getMessages: vi.fn(),
+ searchChatHistory: vi.fn(),
+ };
+}
+
+describe("list_sessions queuedCount", () => {
+ it("adds live queuedCount values for the returned page", async () => {
+ const sessionQueue: SessionQueueDeps = {
+ listSessionQueue: vi.fn(),
+ listSessionQueuedCounts: vi.fn(async () => ({
+ ok: true as const,
+ counts: { "session-1": 2 },
+ })),
+ };
+ const registry = new XdtHelperToolRegistry();
+ registerListSessionsTool(registry, {
+ history: historyWithSessions(),
+ sessionQueue,
+ });
+
+ const payload = parse(await registry.call("list_sessions", {}));
+
+ expect(payload).toMatchObject({
+ ok: true,
+ sessions: [
+ { id: "session-1", messageCount: 3, queuedCount: 2 },
+ { id: "session-2", messageCount: 1, queuedCount: 0 },
+ ],
+ });
+ expect(sessionQueue.listSessionQueuedCounts).toHaveBeenCalledWith([
+ "session-1",
+ "session-2",
+ ]);
+ });
+
+ it("fails instead of reporting stale zeroes when queue restoration fails", async () => {
+ const registry = new XdtHelperToolRegistry();
+ registerListSessionsTool(registry, {
+ history: historyWithSessions(),
+ sessionQueue: {
+ listSessionQueue: vi.fn(),
+ listSessionQueuedCounts: vi.fn(async () => ({
+ ok: false as const,
+ errorCode: "INTERNAL" as const,
+ message: "snapshot unavailable",
+ })),
+ },
+ });
+
+ expect(parse(await registry.call("list_sessions", {}))).toMatchObject({
+ ok: false,
+ errorCode: "INTERNAL",
+ data: { hint: "snapshot unavailable" },
+ });
+ });
+});
diff --git a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
index cbaa7cc1c0..4724f36e3d 100644
--- a/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/lizi_xdtHelperMcpServer.test.ts
@@ -99,4 +99,134 @@ describe("cindy_helper MCP server", () => {
await server.close();
}
});
+
+ it("discovers and calls the arbitrary session queue tool through the entry tools", async () => {
+ const listSessionQueue = vi.fn(async () => ({
+ ok: true as const,
+ messages: [],
+ }));
+ const server = createXdtHelperMcpServer(
+ {
+ sessionQueue: {
+ listSessionQueue,
+ listSessionQueuedCounts: vi.fn(async () => ({ ok: true as const, counts: {} })),
+ },
+ },
+ {
+ agentKind: "codex",
+ workingDir: "/repo",
+ sessionId: "dispatcher-session",
+ },
+ );
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ const client = new Client({
+ name: "cindy-helper-queue-test",
+ version: "0.0.0",
+ });
+
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
+ try {
+ const discovered = parsePayload(
+ await client.callTool({
+ name: "list_tools",
+ arguments: { category: "history" },
+ }),
+ );
+ expect((discovered.tools as Array<{ name: string }>).map((tool) => tool.name)).toContain(
+ "list_session_queue",
+ );
+
+ const result = await client.callTool({
+ name: "call_tool",
+ arguments: {
+ name: "list_session_queue",
+ args: { session_id: "session-1" },
+ },
+ });
+
+ expect(parsePayload(result)).toMatchObject({
+ ok: true,
+ session_id: "session-1",
+ queued_count: 0,
+ queue: [],
+ });
+ expect(listSessionQueue).toHaveBeenCalledWith("session-1");
+ } finally {
+ await client.close();
+ await server.close();
+ }
+ });
+
+ it("discovers the complete session control surface through the control category", async () => {
+ const server = createXdtHelperMcpServer(
+ {
+ sessionControl: {
+ updateQueuedMessage: vi.fn(async ({ queuedMessageId }) => ({
+ ok: true as const,
+ queuedMessageId,
+ })),
+ cancelQueuedMessage: vi.fn(async ({ queuedMessageId }) => ({
+ ok: true as const,
+ queuedMessageId,
+ })),
+ steerSession: vi.fn(async () => ({
+ ok: true as const,
+ queuedMessageId: "steer-1",
+ })),
+ stopSessionTurn: vi.fn(async () => ({
+ ok: true as const,
+ status: "requested" as const,
+ turnGeneration: 4,
+ })),
+ getSessionRuntime: vi.fn(async () => ({
+ ok: true as const,
+ runtime: {
+ sessionId: "target",
+ phase: "idle" as const,
+ recordStatus: "active" as const,
+ attention: false,
+ workflow: null,
+ source: "persisted" as const,
+ turnGeneration: null,
+ startedAtMs: null,
+ lastActivityAtMs: null,
+ currentActionSummary: null,
+ gracefulStopState: "none" as const,
+ },
+ })),
+ },
+ },
+ {
+ agentKind: "codex",
+ workingDir: "/repo",
+ sessionId: "dispatcher-session",
+ },
+ );
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ const client = new Client({
+ name: "cindy-helper-control-test",
+ version: "0.0.0",
+ });
+
+ await Promise.all([server.connect(serverTransport), client.connect(clientTransport)]);
+ try {
+ const discovered = parsePayload(
+ await client.callTool({
+ name: "list_tools",
+ arguments: { category: "control" },
+ }),
+ );
+ const names = (discovered.tools as Array<{ name: string }>).map((tool) => tool.name);
+ expect(names).toEqual(expect.arrayContaining([
+ "update_session_queued_message",
+ "cancel_session_queued_message",
+ "steer_session",
+ "stop_session_turn",
+ "get_session_runtime",
+ ]));
+ } finally {
+ await client.close();
+ await server.close();
+ }
+ });
});
diff --git a/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts b/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts
index 9573043d01..29d98a2c6d 100644
--- a/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts
+++ b/packages/lizi-mcps/src/__tests__/sendToSessionTool.test.ts
@@ -277,6 +277,31 @@ describe('send_to_session tool', () => {
expect(parse(res)).toMatchObject({ ok: true, wake_kind: 'resumed', target_title: null });
});
+ it('jump 排队时返回可供后续修改或撤回的 queued_message_id', async () => {
+ const { registry } = setup({
+ result: {
+ ok: true,
+ targetSessionId: UUID,
+ agentKind: 'codex',
+ wakeKind: 'queued',
+ queuedMessageId: 'queued-by-session-1',
+ targetTitle: 'Busy target',
+ targetLastUserSendAt: '2026-08-16T01:00:00.000Z',
+ },
+ });
+
+ const res = await registry.call('send_to_session', {
+ target_session_id: UUID,
+ message: '稍后处理这条',
+ });
+
+ expect(parse(res)).toMatchObject({
+ ok: true,
+ wake_kind: 'queued',
+ queued_message_id: 'queued-by-session-1',
+ });
+ });
+
it('无 dispatcher sessionId → host 仍被调(dispatcherSessionId=undefined), host 返 LEAD_NOT_SUPPORTED 透传', async () => {
const { registry, sendToSession } = setup({
sessionId: undefined,
diff --git a/packages/lizi-mcps/src/__tests__/sessionControlTools.test.ts b/packages/lizi-mcps/src/__tests__/sessionControlTools.test.ts
new file mode 100644
index 0000000000..e61d37c715
--- /dev/null
+++ b/packages/lizi-mcps/src/__tests__/sessionControlTools.test.ts
@@ -0,0 +1,182 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { XdtHelperToolRegistry, type XdtHelperToolResult } from '../lizi_xdtHelperToolRegistry.js';
+import {
+ registerCancelSessionQueuedMessageTool,
+ registerGetSessionRuntimeTool,
+ registerSteerSessionTool,
+ registerStopSessionTurnTool,
+ registerUpdateSessionQueuedMessageTool,
+ type SessionControlDeps,
+} from '../xdt-helper/session_control.js';
+
+function parse(result: XdtHelperToolResult): Record<string, unknown> {
+ const first = result.content[0];
+ if (!first || first.type !== 'text') throw new Error('missing text payload');
+ return JSON.parse(first.text) as Record<string, unknown>;
+}
+
+function setup(opts?: { sessionId?: string | undefined }) {
+ const sessionId = opts && 'sessionId' in opts ? opts.sessionId : 'caller-session';
+ const deps: SessionControlDeps = {
+ getSessionContext: () => ({
+ sessionId,
+ agentKind: 'codex',
+ workingDir: '/repo',
+ }),
+ updateQueuedMessage: vi.fn(async ({ queuedMessageId }) => ({
+ ok: true as const,
+ queuedMessageId,
+ })),
+ cancelQueuedMessage: vi.fn(async ({ queuedMessageId }) => ({
+ ok: true as const,
+ queuedMessageId,
+ })),
+ steerSession: vi.fn(async () => ({ ok: true as const, queuedMessageId: 'steer-1' })),
+ stopSessionTurn: vi.fn(async () => ({
+ ok: true as const,
+ status: 'waiting-for-safe-point' as const,
+ turnGeneration: 7,
+ })),
+ getSessionRuntime: vi.fn(async () => ({
+ ok: true as const,
+ runtime: {
+ sessionId: 'target-session',
+ phase: 'running' as const,
+ recordStatus: 'active' as const,
+ attention: false,
+ workflow: null,
+ source: 'live' as const,
+ turnGeneration: 7,
+ startedAtMs: Date.parse('2026-08-16T01:00:00.000Z'),
+ lastActivityAtMs: Date.parse('2026-08-16T01:00:05.000Z'),
+ currentActionSummary: '正在运行工具 Bash',
+ gracefulStopState: 'waiting-for-safe-point' as const,
+ },
+ })),
+ };
+ const registry = new XdtHelperToolRegistry();
+ registerUpdateSessionQueuedMessageTool(registry, deps);
+ registerCancelSessionQueuedMessageTool(registry, deps);
+ registerSteerSessionTool(registry, deps);
+ registerStopSessionTurnTool(registry, deps);
+ registerGetSessionRuntimeTool(registry, deps);
+ return { deps, registry };
+}
+
+describe('cindy_helper session control tools', () => {
+ it('updates and cancels only through the caller-bound ownership context', async () => {
+ const { deps, registry } = setup();
+
+ expect(parse(await registry.call('update_session_queued_message', {
+ session_id: 'target-session',
+ queued_message_id: 'queued-1',
+ message: 'revised',
+ }))).toMatchObject({
+ ok: true,
+ session_id: 'target-session',
+ queued_message_id: 'queued-1',
+ updated: true,
+ });
+ expect(deps.updateQueuedMessage).toHaveBeenCalledWith({
+ callerSessionId: 'caller-session',
+ targetSessionId: 'target-session',
+ queuedMessageId: 'queued-1',
+ message: 'revised',
+ });
+
+ expect(parse(await registry.call('cancel_session_queued_message', {
+ session_id: 'target-session',
+ queued_message_id: 'queued-2',
+ }))).toMatchObject({
+ ok: true,
+ queued_message_id: 'queued-2',
+ cancelled: true,
+ });
+ });
+
+ it('fails closed without a caller session for ownership-sensitive actions', async () => {
+ const { deps, registry } = setup({ sessionId: undefined });
+
+ for (const [name, args] of [
+ ['update_session_queued_message', {
+ session_id: 'target', queued_message_id: 'q', message: 'next',
+ }],
+ ['cancel_session_queued_message', { session_id: 'target', queued_message_id: 'q' }],
+ ['steer_session', { session_id: 'target', message: 'urgent context' }],
+ ] as const) {
+ expect(parse(await registry.call(name, args))).toMatchObject({
+ ok: false,
+ errorCode: 'NO_SESSION_CONTEXT',
+ });
+ }
+ expect(deps.updateQueuedMessage).not.toHaveBeenCalled();
+ expect(deps.cancelQueuedMessage).not.toHaveBeenCalled();
+ expect(deps.steerSession).not.toHaveBeenCalled();
+ });
+
+ it('steers, requests graceful stop and projects bounded runtime metadata', async () => {
+ const { deps, registry } = setup();
+
+ expect(parse(await registry.call('steer_session', {
+ session_id: 'target-session',
+ message: 'check this first',
+ }))).toMatchObject({
+ ok: true,
+ queued_message_id: 'steer-1',
+ steered: true,
+ });
+ expect(deps.steerSession).toHaveBeenCalledWith({
+ callerSessionId: 'caller-session',
+ targetSessionId: 'target-session',
+ message: 'check this first',
+ });
+
+ expect(parse(await registry.call('stop_session_turn', {
+ session_id: 'target-session',
+ }))).toMatchObject({
+ ok: true,
+ status: 'waiting-for-safe-point',
+ turn_generation: 7,
+ });
+
+ expect(parse(await registry.call('get_session_runtime', {
+ session_id: 'target-session',
+ }))).toEqual({
+ ok: true,
+ session_id: 'target-session',
+ phase: 'running',
+ active: true,
+ record_status: 'active',
+ source: 'live',
+ attention: false,
+ workflow: null,
+ turn_generation: 7,
+ started_at: '2026-08-16T01:00:00.000Z',
+ last_activity_at: '2026-08-16T01:00:05.000Z',
+ current_action_summary: '正在运行工具 Bash',
+ graceful_stop_state: 'waiting-for-safe-point',
+ });
+ });
+
+ it('preserves structured host failures', async () => {
+ const { deps, registry } = setup();
+ vi.mocked(deps.updateQueuedMessage).mockResolvedValueOnce({
+ ok: false,
+ errorCode: 'NOT_AUTHORIZED',
+ message: 'not yours',
+ });
+ vi.mocked(deps.stopSessionTurn).mockResolvedValueOnce({
+ ok: false,
+ errorCode: 'UNSUPPORTED_CAPABILITY',
+ message: 'soft stop unsupported',
+ });
+
+ expect(parse(await registry.call('update_session_queued_message', {
+ session_id: 'target', queued_message_id: 'q', message: 'next',
+ }))).toMatchObject({ ok: false, errorCode: 'NOT_AUTHORIZED' });
+ expect(parse(await registry.call('stop_session_turn', {
+ session_id: 'target',
+ }))).toMatchObject({ ok: false, errorCode: 'UNSUPPORTED_CAPABILITY' });
+ });
+});
diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
index b2325a2cb4..9ad704cefe 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts
@@ -7,8 +7,9 @@
* - server name = `cindy_helper`,essential(常开,不可被用户关闭)
* - 所有工具走 `list_tools` / `call_tool` 两个入口,渐进式发现,分五类:
* - 'cindy' : 只读自省 (get_capabilities / get_current_session_id)
- * - 'history' : 只读查询本地数据库聊天历史 (list_workdirs / list_sessions /
- * get_chat_history / search_chat_history)
+ * - 'history' : 只读查询本地数据库聊天历史与输入队列 (list_workdirs /
+ * list_sessions / list_session_queue / get_chat_history /
+ * search_chat_history)
* - 'control' : 会话状态控制 (set_current_session_title / rename_sessions /
* archive_sessions / unarchive_sessions)
* - 'feedback': 官方反馈提交 (submit_github_issue)
@@ -40,6 +41,12 @@ import {
registerSendToSessionTool,
registerListWorkdirsTool,
registerListSessionsTool,
+ registerListSessionQueueTool,
+ registerUpdateSessionQueuedMessageTool,
+ registerCancelSessionQueuedMessageTool,
+ registerSteerSessionTool,
+ registerStopSessionTurnTool,
+ registerGetSessionRuntimeTool,
registerGetChatHistoryTool,
registerSearchChatHistoryTool,
registerSubmitGithubIssueTool,
@@ -50,6 +57,8 @@ import type { RenameSessionsDeps } from './xdt-helper/rename_sessions.js';
import type { ArchiveSessionsDeps } from './xdt-helper/archive_sessions.js';
import type { SendToSessionCallback } from './xdt-helper/send_to_session.js';
import type { XdtHelperHistoryDeps } from './xdt-helper/_history_types.js';
+import type { SessionQueueDeps } from './xdt-helper/list_session_queue.js';
+import type { SessionControlDeps } from './xdt-helper/session_control.js';
import type { LiziMcpLogger } from './types.js';
import { resolveLiziMcpSessionContext } from './session-context.js';
import { logToolResultErrorCode } from './tool-error-telemetry.js';
@@ -68,9 +77,9 @@ export type {
const D_LIST_TOOLS =
'探索 cindy_helper 可用工具(渐进式发现入口)。不传 category → 返回所有类目+每个类目工具数量。' +
`传 category=cindy → ${BRAND_NAME} 自省类只读工具(get_capabilities / get_current_session_id);` +
- '传 category=control → 对话控制工具(set_current_session_title / rename_sessions);' +
+ '传 category=control → 会话控制工具(标题/归档、本人排队消息编辑撤回、same-turn 插话、优雅停止、运行探针);' +
'传 category=history → 只读查询本地数据库聊天历史' +
- '(list_workdirs / list_sessions / get_chat_history 按元数据捞, search_chat_history 按内容语义找),' +
+ '(list_workdirs / list_sessions / list_session_queue / get_chat_history 按元数据捞, search_chat_history 按内容语义找),' +
'用于让用户基于自己的对话历史组织 memory / 知识库;' +
`传 category=feedback → 用户要给 ${BRAND_NAME} 官方提 bug / 反馈 / 功能建议时用` +
'(submit_github_issue,先与用户对话澄清缺失细节;Bug 可在用户同意后附脱敏诊断摘要;提交前会弹系统确认卡片,创建后可继续协助源码修复);' +
@@ -82,14 +91,16 @@ const D_LIST_TOOLS =
const D_CALL_TOOL =
'调用 cindy_helper 中的某个具体工具(如 get_capabilities / get_current_session_id / ' +
- 'set_current_session_title / rename_sessions / send_to_session / list_workdirs / list_sessions / get_chat_history / search_chat_history / submit_github_issue)。' +
+ 'set_current_session_title / rename_sessions / send_to_session / list_session_queue / ' +
+ 'update_session_queued_message / cancel_session_queued_message / steer_session / ' +
+ 'stop_session_turn / get_session_runtime / get_chat_history / submit_github_issue)。' +
'先用 list_tools 拿工具名 + 简介。' +
'错误码:`UNKNOWN_TOOL` = 工具名不存在;`INVALID_ARGS` = 参数 schema 校验失败(返回 schema 自纠);' +
'tool 自身的业务错(如 NO_SESSION_CONTEXT / INVALID_FILTER / HOST_NOT_READY / INTERNAL)' +
'在返回 payload 的 errorCode 字段, 附 data.hint 引导自纠。' +
'history 类工具返回 hasMore=true 时用响应里的 nextCursor 再次调用本工具拿下一页, 不会丢信息。';
-// list_tools 入口类目: cindy(自省) / control(会话标题控制) / history(聊天历史) / feedback(官方反馈提交) / handoff(session 间 handoff)。
+// list_tools 入口类目: cindy(自省) / control(会话控制面) / history(聊天历史) / feedback(官方反馈提交) / handoff(session 间 handoff)。
// 协同 team 工具已拆到独立 cindy_orca server(插件开关 gate)。
const CATEGORY_ENUM = ['cindy', 'control', 'history', 'feedback', 'handoff'] as const;
@@ -220,6 +231,13 @@ export interface XdtHelperMcpDeps {
* search_chat_history) 会被注册; 不注入则这四个工具不出现在 list_tools 里。
*/
history?: XdtHelperHistoryDeps;
+ /**
+ * 本机 session 输入队列的只读查询回调。host 注入后注册 list_session_queue,
+ * 并让 list_sessions 为每条 session 附带 queuedCount。
+ */
+ sessionQueue?: SessionQueueDeps;
+ /** 本机 session 的统一控制面;host 注入后注册队列编辑/撤回、插话、停止与运行探针。 */
+ sessionControl?: Omit<SessionControlDeps, 'getSessionContext'>;
/**
* Session handoff 回调。host 注入后, send_to_session 工具注册到 handoff 类目(走
* call_tool);不注入则工具不出现。此工具是 skill(如 maker-github-issue)做跨会话
@@ -301,10 +319,27 @@ export function createXdtHelperMcpServer(
// History 类工具: 仅 host 注入了 history 回调时注册。
if (deps.history) {
registerListWorkdirsTool(registry, { history: deps.history });
- registerListSessionsTool(registry, { history: deps.history });
+ registerListSessionsTool(registry, {
+ history: deps.history,
+ ...(deps.sessionQueue ? { sessionQueue: deps.sessionQueue } : {}),
+ });
registerGetChatHistoryTool(registry, { history: deps.history });
registerSearchChatHistoryTool(registry, { history: deps.history });
}
+ if (deps.sessionQueue) {
+ registerListSessionQueueTool(registry, deps.sessionQueue);
+ }
+ if (deps.sessionControl) {
+ const controlDeps: SessionControlDeps = {
+ getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),
+ ...deps.sessionControl,
+ };
+ registerUpdateSessionQueuedMessageTool(registry, controlDeps);
+ registerCancelSessionQueuedMessageTool(registry, controlDeps);
+ registerSteerSessionTool(registry, controlDeps);
+ registerStopSessionTurnTool(registry, controlDeps);
+ registerGetSessionRuntimeTool(registry, controlDeps);
+ }
// Feedback 类工具: 仅 host 注入了 githubIssue 回调时注册。
if (deps.githubIssue) {
diff --git a/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts b/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts
index 6d9006a233..0262b0aa0a 100644
--- a/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts
+++ b/packages/lizi-mcps/src/lizi_xdtHelperToolRegistry.ts
@@ -25,8 +25,8 @@ import { z } from 'zod';
* history 单独成类是因为它和 cindy 自省虽都只读, 但语义不同 (自省 = "我是谁",
* 查询 = "我和你聊过啥"), 拆开后 list_tools 入口更清晰。
*
- * 第三类 'control' 是改变 Cindy 状态的副作用工具(当前:set_current_session_title /
- * rename_sessions 改会话标题)。
+ * 第三类 'control' 是会话控制面:标题 / 归档,以及跨 session 的本人队列消息控制、
+ * same-turn 插话、优雅停止与只读运行探针。
*
* 第四类 'feedback' 是向 Cindy 官方提交反馈的工具 (submit_github_issue),
* 有副作用但提交前由 host 弹系统确认卡片把关。
diff --git a/packages/lizi-mcps/src/xdt-helper/capabilities.ts b/packages/lizi-mcps/src/xdt-helper/capabilities.ts
index fef1a6cbb4..ec2b832d7c 100644
--- a/packages/lizi-mcps/src/xdt-helper/capabilities.ts
+++ b/packages/lizi-mcps/src/xdt-helper/capabilities.ts
@@ -85,6 +85,19 @@ export const CAPABILITIES: readonly CapabilityEntry[] = [
'【边界】它不是普通聊天入口,而是 session 间 handoff 的控制层能力;不会自动关闭当前 dispatcher session,也不会替 skill 管理绑定键的存储语义。',
].join(' '),
},
+ {
+ key: 'session-control',
+ title: '会话控制面(队列 / 插话 / 停止 / 运行探针)',
+ oneLiner:
+ 'agent 可观察任意本机会话队列与运行状态,并控制自己投递的队列消息、same-turn 插话或请求优雅停止。',
+ detail: [
+ '【入口】cindy_helper 的 history 类 list_sessions / list_session_queue 提供 queuedCount、队列位置、来源、入队时间、正文摘要与 consuming 状态;control 类提供 update_session_queued_message、cancel_session_queued_message、steer_session、stop_session_turn、get_session_runtime。',
+ '【队列所有权】只能修改或撤回当前调用 session 自己通过 send_to_session 投递、且尚未进入 consuming 的消息;Orca、scheduler、用户或其它 session 的消息都会 fail-closed 拒绝。Orca worker 队列控制与这里复用同一底层生命周期实现。',
+ '【插话】steer_session 只对正在运行且支持 same-turn steer 的 session 生效,在 provider 的下一个输入间隙注入当前 turn;若 turn 已结束会明确失败,不会退化成下一 turn。',
+ '【停止】stop_session_turn 是请求式优雅停止:当前并行工具全部收尾后才发送 provider 软中断;不关闭 transport、不重建 session、不硬杀进程,超时未确认会返回 unconfirmed。',
+ '【探针】get_session_runtime 返回统一 phase、记录状态、标题工作流语义、turn generation、开始时间、最后活动时间、当前动作摘要和停止状态;动作摘要有界且不包含提示词正文、工具参数或凭证。',
+ ].join(' '),
+ },
{
key: 'session-management',
title: '会话管理(含 Fork / Rewind / 批量归档)',
@@ -148,8 +161,8 @@ export const CAPABILITIES: readonly CapabilityEntry[] = [
title: '聊天历史查询(给 LLM 自助拉本地对话数据)',
oneLiner: 'agent 通过 MCP 工具拉本地 SQLite 里所有 session / message 原始数据,适合做用户级 memory / 知识库整理。',
detail: [
- `【是什么】${BRAND_NAME} 所有用户和 agent 的对话全部存在本地 SQLite(按 userId 物理隔离), 但用户原本看不到这些数据, 也无法让 agent 帮忙整理。cindy_helper 的 history 类工具开放了四个只读查询入口, 让 agent 能拿到原始 raw data 协助用户组织自己的 memory / 知识库系统。`,
- '【四个工具】(1)list_workdirs: 列出所有出现过的工作目录 + session 数 / 首末活动时间; (2)list_sessions: 按 workdir / 时间段 / agent_kind 过滤 session 元数据(不返消息内容); (3)get_chat_history: 按 session_ids / workdir / 时间段 / role "按元数据精确捞"原始消息(content / agentMeta JSON 解析后透传); (4)search_chat_history: 跨 session "按内容语义找"——自然语言 query, FTS5 全文(全量、永远可用)+ 向量语义(开启"聊天记录语义索引"后生效)RRF 融合, 返回命中 + 上下文窗口。',
+ `【是什么】${BRAND_NAME} 所有用户和 agent 的对话全部存在本地 SQLite(按 userId 物理隔离), 但用户原本看不到这些数据, 也无法让 agent 帮忙整理。cindy_helper 的 history 类工具开放了五个只读查询入口, 让 agent 能拿到原始 raw data 与当前输入队列协助用户组织自己的 memory / 知识库系统。`,
+ '【五个工具】(1)list_workdirs: 列出所有出现过的工作目录 + session 数 / 首末活动时间; (2)list_sessions: 按 workdir / 时间段 / agent_kind 过滤 session 元数据,并附当前 queuedCount; (3)list_session_queue: 按 session_id 查看尚未消费消息的位置、来源、入队时间、正文摘要与投递状态; (4)get_chat_history: 按 session_ids / workdir / 时间段 / role "按元数据精确捞"原始消息(content / agentMeta JSON 解析后透传); (5)search_chat_history: 跨 session "按内容语义找"——自然语言 query, FTS5 全文(全量、永远可用)+ 向量语义(开启"聊天记录语义索引"后生效)RRF 融合, 返回命中 + 上下文窗口。',
'【典型用法】"帮我总结这周和 agent 的讨论, 写成 memory 条目" → list_sessions({from: 周一 ISO}) 拿 sessionId 列表 → get_chat_history({session_ids: [...]}) 拿对话 → LLM 提炼成 memory。"我之前聊过 X / 上次怎么解决那个 bug"(只记得内容、不知道在哪) → search_chat_history({query}) 直接语义召回。"我在 xxx 项目里都聊过啥" → list_sessions({workdir}) → get_chat_history。',
'【向量是增益不是依赖】search_chat_history 在用户没开 embedding / sqlite-vec 不可用时静默退化为纯 FTS, 搜索照常工作; 响应里 vector_used 标明向量是否生效。',
'【分页】所有工具游标分页, 单次硬上限防炸 context, 但 hasMore + nextCursor 串联多次调用可拿全量, 不会丢信息。',
diff --git a/packages/lizi-mcps/src/xdt-helper/index.ts b/packages/lizi-mcps/src/xdt-helper/index.ts
index 633bad3080..b36e08fc8b 100644
--- a/packages/lizi-mcps/src/xdt-helper/index.ts
+++ b/packages/lizi-mcps/src/xdt-helper/index.ts
@@ -101,6 +101,23 @@ export {
registerListSessionsTool,
type ListSessionsToolDeps,
} from './list_sessions.js';
+export {
+ registerListSessionQueueTool,
+ type SessionQueueDeps,
+ type SessionQueuedMessageEntry,
+} from './list_session_queue.js';
+export {
+ registerUpdateSessionQueuedMessageTool,
+ registerCancelSessionQueuedMessageTool,
+ registerSteerSessionTool,
+ registerStopSessionTurnTool,
+ registerGetSessionRuntimeTool,
+ type SessionControlDeps,
+ type SessionQueueControlErrorCode,
+ type SessionRuntimeSnapshot,
+ type SessionSteerErrorCode,
+ type SessionStopErrorCode,
+} from './session_control.js';
export {
registerGetChatHistoryTool,
type GetChatHistoryToolDeps,
diff --git a/packages/lizi-mcps/src/xdt-helper/list_session_queue.ts b/packages/lizi-mcps/src/xdt-helper/list_session_queue.ts
new file mode 100644
index 0000000000..9ed87e4225
--- /dev/null
+++ b/packages/lizi-mcps/src/xdt-helper/list_session_queue.ts
@@ -0,0 +1,112 @@
+/**
+ * xdt-helper/list_session_queue.ts —— 查询任意本机 session 的只读输入队列。
+ *
+ * 与 cindy_orca/list_worker_queue 的边界不同:本工具不要求 Lead 身份,也不暴露
+ * 修改、撤回或重排能力;它只把 host 注入的队列快照压成有界摘要,供 agent 确认
+ * 一条消息是否已经排队、位于什么位置、是否正在投递。
+ */
+
+import { z } from "zod";
+
+import type { XdtHelperToolRegistry } from "../lizi_xdtHelperToolRegistry.js";
+import type { ControlResult } from "../types.js";
+import { errorPayload, okPayload } from "./_payload.js";
+
+const MAX_CONTENT_SUMMARY_CHARS = 500;
+
+export interface SessionQueuedMessageEntry {
+ queuedMessageId: string;
+ position: number;
+ source: "user" | "orca" | "scheduler" | "session";
+ sourceLabel: string | null;
+ enqueuedAtMs: number | null;
+ content: string;
+ consuming: boolean;
+}
+
+export interface SessionQueueDeps {
+ listSessionQueue: (
+ sessionId: string,
+ ) => Promise<
+ ControlResult<{ messages: SessionQueuedMessageEntry[] }, "NOT_FOUND">
+ >;
+ listSessionQueuedCounts: (
+ sessionIds: string[],
+ ) => Promise<ControlResult<{ counts: Record<string, number> }>>;
+}
+
+const DESCRIPTION =
+ "只读列出本机任意 session 当前尚未消费的输入队列。每条返回队列位置、来源、入队时间、" +
+ "正文摘要与 consuming 状态;consuming=true 表示该条正在投递。此工具不提供修改、撤回或重排。" +
+ "session_id 建议来自 list_sessions。失败码: NOT_FOUND / HOST_NOT_READY / INTERNAL。";
+
+export function registerListSessionQueueTool(
+ registry: XdtHelperToolRegistry,
+ deps: SessionQueueDeps,
+): void {
+ registry.register({
+ name: "list_session_queue",
+ category: "history",
+ description: DESCRIPTION,
+ inputShape: {
+ session_id: z
+ .string()
+ .min(1)
+ .describe("目标 session id,建议来自 list_sessions。"),
+ },
+ handler: async ({ session_id }) => {
+ const result = await deps.listSessionQueue(session_id);
+ if (!result.ok) {
+ if (result.errorCode === "NOT_FOUND") {
+ return errorPayload(
+ "NOT_FOUND",
+ `找不到 session ${session_id},请先用 list_sessions 核对 id。`,
+ );
+ }
+ if (result.errorCode === "HOST_NOT_READY") {
+ return errorPayload(
+ "HOST_NOT_READY",
+ "本机 session 队列服务尚未就绪,请稍后重试。",
+ );
+ }
+ return errorPayload("INTERNAL", result.message);
+ }
+ return okPayload({
+ session_id,
+ queued_count: result.messages.length,
+ queue: result.messages.map((entry) => {
+ const summary = summarizeContent(entry.content);
+ const out: Record<string, unknown> = {
+ queued_message_id: entry.queuedMessageId,
+ position: entry.position,
+ source: entry.source,
+ enqueued_at:
+ entry.enqueuedAtMs === null
+ ? null
+ : new Date(entry.enqueuedAtMs).toISOString(),
+ content_summary: summary.text,
+ truncated: summary.truncated,
+ consuming: entry.consuming,
+ };
+ if (entry.sourceLabel !== null) out.source_label = entry.sourceLabel;
+ return out;
+ }),
+ });
+ },
+ });
+}
+
+function summarizeContent(content: string): {
+ text: string;
+ truncated: boolean;
+} {
+ const normalized = content.replace(/\s+/gu, " ").trim();
+ const chars = Array.from(normalized);
+ if (chars.length <= MAX_CONTENT_SUMMARY_CHARS) {
+ return { text: normalized, truncated: false };
+ }
+ return {
+ text: `${chars.slice(0, MAX_CONTENT_SUMMARY_CHARS).join("")}…`,
+ truncated: true,
+ };
+}
diff --git a/packages/lizi-mcps/src/xdt-helper/list_sessions.ts b/packages/lizi-mcps/src/xdt-helper/list_sessions.ts
index 1a12624fba..c06fb809c9 100644
--- a/packages/lizi-mcps/src/xdt-helper/list_sessions.ts
+++ b/packages/lizi-mcps/src/xdt-helper/list_sessions.ts
@@ -15,6 +15,7 @@ import { z } from 'zod';
import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
import type { XdtHelperHistoryDeps } from './_history_types.js';
+import type { SessionQueueDeps } from './list_session_queue.js';
import { okPayload, errorPayload } from './_payload.js';
import { encodeCursor, decodeCursor } from './_history_cursor.js';
@@ -33,6 +34,7 @@ const DESCRIPTION = [
' - include_deleted: 默认 false (排除 status=deleted)',
'',
'【输出】messageCount 已过滤被 rewind 软删的消息, 是用户可见的真实条数。',
+ 'queuedCount 是当前尚未消费的输入队列条数,可用 list_session_queue 查看明细。',
'时间戳均为 ISO 8601 字符串(对应 DB 里的 unix ms 转换)。',
'orcaRole / parentSessionId / userSendAt 仅在非 null 时出现(默认场景几乎全为 null, 已 omit)。',
'',
@@ -41,6 +43,7 @@ const DESCRIPTION = [
export interface ListSessionsToolDeps {
history: XdtHelperHistoryDeps;
+ sessionQueue?: SessionQueueDeps;
}
export function registerListSessionsTool(
@@ -110,6 +113,22 @@ export function registerListSessionsTool(
return errorPayload('INTERNAL', result.message);
}
const { page } = result;
+ let queuedCounts: Record<string, number> | null = null;
+ if (deps.sessionQueue && page.items.length > 0) {
+ const countsResult = await deps.sessionQueue.listSessionQueuedCounts(
+ page.items.map((session) => session.id),
+ );
+ if (!countsResult.ok) {
+ if (countsResult.errorCode === 'HOST_NOT_READY') {
+ return errorPayload(
+ 'HOST_NOT_READY',
+ `${BRAND_NAME} 本机 session 队列服务尚未就绪,请稍后重试。`,
+ );
+ }
+ return errorPayload('INTERNAL', countsResult.message);
+ }
+ queuedCounts = countsResult.counts;
+ }
// Token 优化: orcaRole / parentSessionId / userSendAt 这几个字段在绝大多数
// session 上都是 null, 逐行带 null 会浪费 token。改成 omit-when-null。
return okPayload({
@@ -127,6 +146,7 @@ export function registerListSessionsTool(
updatedAt: new Date(s.updatedAt).toISOString(),
messageCount: s.messageCount,
};
+ if (queuedCounts !== null) out.queuedCount = queuedCounts[s.id] ?? 0;
if (s.orcaRole !== null) out.orcaRole = s.orcaRole;
if (s.parentSessionId !== null) out.parentSessionId = s.parentSessionId;
if (s.userSendAt !== null) out.userSendAt = new Date(s.userSendAt).toISOString();
diff --git a/packages/lizi-mcps/src/xdt-helper/send_to_session.ts b/packages/lizi-mcps/src/xdt-helper/send_to_session.ts
index 2099ebe234..a9e3e514f0 100644
--- a/packages/lizi-mcps/src/xdt-helper/send_to_session.ts
+++ b/packages/lizi-mcps/src/xdt-helper/send_to_session.ts
@@ -43,6 +43,8 @@ export type SendToSessionCallback = (params: {
wakeKind: "resumed" | "already-active" | "created" | "queued";
targetTitle: string | null;
targetLastUserSendAt: string | null;
+ /** jump 进入队列时的可寻址句柄,可用于本人编辑/撤回。 */
+ queuedMessageId?: string;
/** create + useWorktree 成功时为新 session 的 worktree 绝对路径;其余情况 host 可省略。 */
worktreePath?: string | null;
model?: string;
@@ -218,6 +220,7 @@ export function registerSendToSessionTool(
wake_kind: result.wakeKind,
target_title: result.targetTitle,
target_last_user_send_at: result.targetLastUserSendAt,
+ ...(result.queuedMessageId ? { queued_message_id: result.queuedMessageId } : {}),
worktree_path: result.worktreePath ?? null,
...(result.model !== undefined ? { model: result.model } : {}),
...(result.effort !== undefined ? { effort: result.effort } : {}),
diff --git a/packages/lizi-mcps/src/xdt-helper/session_control.ts b/packages/lizi-mcps/src/xdt-helper/session_control.ts
new file mode 100644
index 0000000000..a89975ba92
--- /dev/null
+++ b/packages/lizi-mcps/src/xdt-helper/session_control.ts
@@ -0,0 +1,240 @@
+import { BRAND_NAME } from '@cindy/maker-shared/branding';
+import type { SessionActivitySnapshot } from '@cindy/maker-shared/session-activity';
+import { z } from 'zod';
+
+import type { XdtHelperToolRegistry } from '../lizi_xdtHelperToolRegistry.js';
+import type { ControlResult, LiziMcpSessionContext } from '../types.js';
+import { errorPayload, okPayload } from './_payload.js';
+
+export type SessionQueueControlErrorCode =
+ | 'NOT_FOUND'
+ | 'QUEUED_MESSAGE_NOT_FOUND'
+ | 'MESSAGE_CONSUMING'
+ | 'NOT_AUTHORIZED'
+ | 'INVALID_ARGS';
+
+export type SessionSteerErrorCode =
+ | 'NOT_FOUND'
+ | 'NO_ACTIVE_TURN'
+ | 'UNSUPPORTED_CAPABILITY'
+ | 'INPUT_LOCKED'
+ | 'DELIVERY_FAILED';
+
+export type SessionStopErrorCode = 'NOT_FOUND' | 'UNSUPPORTED_CAPABILITY';
+
+export type SessionRuntimeSnapshot = SessionActivitySnapshot;
+
+export interface SessionControlDeps {
+ getSessionContext: () => LiziMcpSessionContext;
+ updateQueuedMessage(params: {
+ callerSessionId: string;
+ targetSessionId: string;
+ queuedMessageId: string;
+ message: string;
+ }): Promise<ControlResult<{ queuedMessageId: string }, SessionQueueControlErrorCode>>;
+ cancelQueuedMessage(params: {
+ callerSessionId: string;
+ targetSessionId: string;
+ queuedMessageId: string;
+ }): Promise<ControlResult<{ queuedMessageId: string }, SessionQueueControlErrorCode>>;
+ steerSession(params: {
+ callerSessionId: string;
+ targetSessionId: string;
+ message: string;
+ }): Promise<ControlResult<{ queuedMessageId: string }, SessionSteerErrorCode>>;
+ stopSessionTurn(params: {
+ targetSessionId: string;
+ }): Promise<
+ ControlResult<
+ {
+ status: 'no-active-turn' | 'waiting-for-safe-point' | 'requested' | 'unconfirmed';
+ turnGeneration?: number;
+ reason?: string;
+ },
+ SessionStopErrorCode
+ >
+ >;
+ getSessionRuntime(params: {
+ targetSessionId: string;
+ }): Promise<ControlResult<{ runtime: SessionRuntimeSnapshot }, 'NOT_FOUND'>>;
+}
+
+function requireCallerSession(deps: SessionControlDeps): string | null {
+ return deps.getSessionContext().sessionId ?? null;
+}
+
+function mapControlFailure(result: { ok: false; errorCode: string; message: string }) {
+ if (result.errorCode === 'HOST_NOT_READY') {
+ return errorPayload('HOST_NOT_READY', `${BRAND_NAME} 主进程会话服务尚未就绪,请稍后重试。`);
+ }
+ return errorPayload(result.errorCode, result.message);
+}
+
+export function registerUpdateSessionQueuedMessageTool(
+ registry: XdtHelperToolRegistry,
+ deps: SessionControlDeps,
+): void {
+ registry.register({
+ name: 'update_session_queued_message',
+ category: 'control',
+ description:
+ '修改你通过 send_to_session 投递、且目标 session 尚未消费的一条排队消息。' +
+ '只能修改当前调用 session 自己投递的消息;正在投递或其它来源的消息会被拒绝。',
+ inputShape: {
+ session_id: z.string().min(1).describe('目标 session id。'),
+ queued_message_id: z.string().min(1).describe('来自 send_to_session 或 list_session_queue 的消息 id。'),
+ message: z.string().min(1).describe('替换后的完整消息正文。'),
+ },
+ handler: async ({ session_id, queued_message_id, message }) => {
+ const callerSessionId = requireCallerSession(deps);
+ if (!callerSessionId) {
+ return errorPayload('NO_SESSION_CONTEXT', '当前 MCP 调用没有绑定 session,无法校验消息所有权。');
+ }
+ const result = await deps.updateQueuedMessage({
+ callerSessionId,
+ targetSessionId: session_id,
+ queuedMessageId: queued_message_id,
+ message,
+ });
+ if (!result.ok) return mapControlFailure(result);
+ return okPayload({
+ session_id,
+ queued_message_id: result.queuedMessageId,
+ updated: true,
+ });
+ },
+ });
+}
+
+export function registerCancelSessionQueuedMessageTool(
+ registry: XdtHelperToolRegistry,
+ deps: SessionControlDeps,
+): void {
+ registry.register({
+ name: 'cancel_session_queued_message',
+ category: 'control',
+ description:
+ '撤回你通过 send_to_session 投递、且目标 session 尚未消费的一条排队消息。' +
+ '只能撤回当前调用 session 自己投递的消息;正在投递或其它来源的消息会被拒绝。',
+ inputShape: {
+ session_id: z.string().min(1).describe('目标 session id。'),
+ queued_message_id: z.string().min(1).describe('来自 send_to_session 或 list_session_queue 的消息 id。'),
+ },
+ handler: async ({ session_id, queued_message_id }) => {
+ const callerSessionId = requireCallerSession(deps);
+ if (!callerSessionId) {
+ return errorPayload('NO_SESSION_CONTEXT', '当前 MCP 调用没有绑定 session,无法校验消息所有权。');
+ }
+ const result = await deps.cancelQueuedMessage({
+ callerSessionId,
+ targetSessionId: session_id,
+ queuedMessageId: queued_message_id,
+ });
+ if (!result.ok) return mapControlFailure(result);
+ return okPayload({
+ session_id,
+ queued_message_id: result.queuedMessageId,
+ cancelled: true,
+ });
+ },
+ });
+}
+
+export function registerSteerSessionTool(
+ registry: XdtHelperToolRegistry,
+ deps: SessionControlDeps,
+): void {
+ registry.register({
+ name: 'steer_session',
+ category: 'control',
+ description:
+ '向正在运行的本机 session 高优先级插话;消息复用该 session 的原生 same-turn steer,' +
+ '在 provider 的下一个输入安全间隙可见,不等待当前 turn 结束。目标不在运行或不支持时明确失败。',
+ inputShape: {
+ session_id: z.string().min(1).describe('目标 session id。'),
+ message: z.string().min(1).describe('要注入当前 turn 的完整消息正文。'),
+ },
+ handler: async ({ session_id, message }) => {
+ const callerSessionId = requireCallerSession(deps);
+ if (!callerSessionId) {
+ return errorPayload('NO_SESSION_CONTEXT', '当前 MCP 调用没有绑定 session,无法记录插话来源。');
+ }
+ const result = await deps.steerSession({
+ callerSessionId,
+ targetSessionId: session_id,
+ message,
+ });
+ if (!result.ok) return mapControlFailure(result);
+ return okPayload({
+ session_id,
+ queued_message_id: result.queuedMessageId,
+ steered: true,
+ });
+ },
+ });
+}
+
+export function registerStopSessionTurnTool(
+ registry: XdtHelperToolRegistry,
+ deps: SessionControlDeps,
+): void {
+ registry.register({
+ name: 'stop_session_turn',
+ category: 'control',
+ description:
+ '请求另一个本机 session 的当前 turn 优雅停止。若正在执行工具,会等全部当前工具结果返回后再发送 provider 软中断;' +
+ '不会关闭 transport、重建 session 或硬杀进程。',
+ inputShape: {
+ session_id: z.string().min(1).describe('目标 session id。'),
+ },
+ handler: async ({ session_id }) => {
+ const result = await deps.stopSessionTurn({ targetSessionId: session_id });
+ if (!result.ok) return mapControlFailure(result);
+ return okPayload({
+ session_id,
+ status: result.status,
+ ...(result.turnGeneration !== undefined
+ ? { turn_generation: result.turnGeneration }
+ : {}),
+ ...(result.reason ? { reason: result.reason } : {}),
+ });
+ },
+ });
+}
+
+export function registerGetSessionRuntimeTool(
+ registry: XdtHelperToolRegistry,
+ deps: SessionControlDeps,
+): void {
+ registry.register({
+ name: 'get_session_runtime',
+ category: 'control',
+ description:
+ '只读查询本机 session 的统一状态:记录生命周期、运行/等待/正常结束/出错结束、标题工作流语义、' +
+ '开始时间、最后活动时间、动作摘要和优雅停止状态;' +
+ '不返回提示词正文、工具参数或凭证。',
+ inputShape: {
+ session_id: z.string().min(1).describe('目标 session id。'),
+ },
+ handler: async ({ session_id }) => {
+ const result = await deps.getSessionRuntime({ targetSessionId: session_id });
+ if (!result.ok) return mapControlFailure(result);
+ const runtime = result.runtime;
+ return okPayload({
+ session_id,
+ phase: runtime.phase,
+ active: runtime.phase === 'running' || runtime.phase === 'needs-interaction',
+ record_status: runtime.recordStatus ?? null,
+ source: runtime.source,
+ attention: runtime.attention,
+ workflow: runtime.workflow,
+ turn_generation: runtime.turnGeneration,
+ started_at: runtime.startedAtMs === null ? null : new Date(runtime.startedAtMs).toISOString(),
+ last_activity_at:
+ runtime.lastActivityAtMs === null ? null : new Date(runtime.lastActivityAtMs).toISOString(),
+ current_action_summary: runtime.currentActionSummary,
+ graceful_stop_state: runtime.gracefulStopState,
+ });
+ },
+ });
+}
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 43d30965d7..cf992db82c 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -1519,6 +1519,15 @@ export interface AgentSessionHandle {
/** 中断当前 turn */
abort(): Promise<void>;
+ /**
+ * 请求当前 turn 在 provider 的安全边界停止。
+ *
+ * 与 abort() 的产品语义不同:这里只发送 provider 原生的软中断请求,不得关闭
+ * Query、transport 或子进程,也不得升级为 kill/rebuild。Session 层负责等到当前
+ * 工具结果边界再调用,并对悬挂/失败做有界的 unconfirmed 降级。
+ */
+ requestGracefulStop?(opts?: { signal?: AbortSignal }): Promise<void>;
+
/** Provider turn identity when the adapter exposes one (currently Codex). */
getCurrentTurnId?(): string | null;
diff --git a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
index 8adf87d11d..e0436ddb83 100644
--- a/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
+++ b/packages/maker-core/src/agents/claude-code/__tests__/abort-stops-background-tasks.test.ts
@@ -475,6 +475,283 @@ afterEach(async () => {
});
describe('ClaudeCodeAgent abort stops background wake tasks', () => {
+ it('graceful stop cancels a Session send while Claude is still converting attachments', async () => {
+ const { handle, stream, fakeQuery } = await startSessionWithStream();
+ const session = wrapInSession(handle);
+ let resolveResize!: (value: string) => void;
+ imageResizerMock.process.mockImplementationOnce(
+ () => new Promise<string>((resolve) => { resolveResize = resolve; }),
+ );
+
+ const imagePath = path.join(os.tmpdir(), 'graceful-stop-pre-acceptance.png');
+ const send = session.send({
+ type: 'user',
+ content: [{ type: 'image', path: imagePath }],
+ });
+ await waitFor(() => imageResizerMock.process.mock.calls.length > 0, 'attachment conversion started');
+
+ const firstStop = session.requestGracefulStop();
+ const secondStop = session.requestGracefulStop();
+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();
+ resolveResize(imagePath);
+
+ await expect(send).resolves.toEqual({ accepted: false, reason: 'cancelled-before-dispatch' });
+ await expect(Promise.all([firstStop, secondStop])).resolves.toEqual([
+ { status: 'requested', turnGeneration: 1 },
+ { status: 'requested', turnGeneration: 1 },
+ ]);
+ expect(fakeQuery.interrupt).not.toHaveBeenCalled();
+
+ stream.end();
+ await session.close().catch(() => undefined);
+ });
+
+ it('graceful stop sends only the SDK interrupt without closing or stopping background tasks', async () => {
+ const { handle, stream, events, fakeQuery } = await startSessionWithStream();
+ await handle.send({ type: 'user', content: 'long turn' });
+
+ await expect(handle.requestGracefulStop?.()).resolves.toBeUndefined();
+ expect(fakeQuery.interrupt).toHaveBeenCalledOnce();
+ expect(fakeQuery.close).not.toHaveBeenCalled();
+ expect(fakeQuery.stopTask).not.toHaveBeenCalled();
+
+ stream.emit(turnResult('stopped'));
+ await waitFor(
+ () => events.some((event) => event.type === 'done'),
+ 'graceful stop terminal',
+ );
+ await handle.close();
+ });
+
+ it('graceful stop cancels an awaiting wake continuation and rebuilds before the next send', async () => {
+ const { handle, stream, streams, events, fakeQuery, fakeQueries } =
+ await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');
+ stream.emit(turnResult('waiting'));
+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');
+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
+ expect(continuationId).toBeTypeOf('number');
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');
+
+ await expect(handle.requestGracefulStop?.()).resolves.toBeUndefined();
+
+ expect(fakeQuery.stopTask).toHaveBeenCalledWith('task-agent');
+ expect(fakeQuery.interrupt).toHaveBeenCalledOnce();
+ expect(fakeQuery.close).not.toHaveBeenCalled();
+ await waitFor(
+ () =>
+ events.some(
+ (event) =>
+ event.type === 'done' &&
+ (event.data as { reason?: unknown } | null | undefined)?.reason ===
+ 'turn_continuation_cancelled',
+ ),
+ 'graceful continuation cancellation observed',
+ );
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ const eventCountAfterStop = events.length;
+ streams[0]?.emit(assistantText('late automatic continuation'));
+ streams[0]?.emit(turnResult('late automatic result'));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(events).toHaveLength(eventCountAfterStop);
+
+ await handle.send({ type: 'user', content: 'fresh turn after graceful stop' });
+ expect(fakeQueries).toHaveLength(2);
+ expect(fakeQuery.close).toHaveBeenCalledTimes(1);
+ stream.emit(turnResult('fresh turn complete'));
+ await waitFor(() => events.filter(isProductTerminal).length === 2, 'fresh terminal observed');
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+
+ it('graceful stop cancels an awaiting claim after its wake task already completed', async () => {
+ const { handle, stream, events, fakeQuery } = await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');
+ stream.emit(turnResult('waiting'));
+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');
+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
+ expect(continuationId).toBeTypeOf('number');
+ stream.emit(taskNotification('task-agent', 'completed'));
+ await waitFor(() => taskEvents(events).length >= 2, 'task completion observed');
+
+ await expect(handle.requestGracefulStop?.()).resolves.toBeUndefined();
+
+ expect(fakeQuery.stopTask).not.toHaveBeenCalled();
+ expect(fakeQuery.interrupt).toHaveBeenCalledOnce();
+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'cancellation terminal observed');
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+
+ it('graceful stop lets an already active continuation finish through its interrupted result', async () => {
+ const { handle, stream, events, fakeQuery } = await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');
+ stream.emit(turnResult('waiting'));
+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');
+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
+ expect(continuationId).toBeTypeOf('number');
+ stream.emit(taskNotification('task-agent', 'completed'));
+ await waitFor(() => taskEvents(events).length >= 2, 'task completion observed');
+ stream.emit(assistantText('automatic continuation started'));
+ await waitFor(() => handle.beginTurnContinuationWait?.(continuationId) === 'active', 'claim activated');
+
+ await expect(handle.requestGracefulStop?.()).resolves.toBeUndefined();
+
+ expect(fakeQuery.stopTask).not.toHaveBeenCalled();
+ expect(fakeQuery.interrupt).toHaveBeenCalledOnce();
+ expect(events.filter(isProductTerminal)).toHaveLength(0);
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('active');
+
+ stream.emit(interruptedTurnResult());
+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'interrupted continuation terminal');
+ await waitFor(() => handle.isTurnRunning?.() === false, 'active continuation settled');
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+
+ it('provider stopped notification may cancel the awaiting claim before graceful-stop ACK', async () => {
+ const { handle, stream, events, fakeQuery } = await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');
+ stream.emit(turnResult('waiting'));
+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');
+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
+ expect(continuationId).toBeTypeOf('number');
+
+ const stopTask = createDeferred<void>();
+ const interrupt = createDeferred<void>();
+ fakeQuery.stopTask!.mockImplementationOnce(() => stopTask.promise);
+ fakeQuery.interrupt.mockImplementationOnce(() => interrupt.promise);
+ const stop = handle.requestGracefulStop?.();
+ await waitFor(() => fakeQuery.interrupt.mock.calls.length === 1, 'interrupt dispatched');
+
+ stream.emit(taskNotification('task-agent', 'stopped'));
+ await waitFor(() => events.filter(isProductTerminal).length === 1, 'provider stop terminal observed');
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBeNull();
+
+ stopTask.resolve(undefined);
+ interrupt.resolve(undefined);
+ await expect(stop).resolves.toBeUndefined();
+ expect(events.filter(isProductTerminal)).toHaveLength(1);
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+
+ it.each([
+ ['stopTask rejection', false],
+ ['legacy query without stopTask', true],
+ ] as const)(
+ 'graceful stop stays unconfirmed without hard-closing on %s',
+ async (_label, omitStopTask) => {
+ const { handle, stream, events, fakeQuery } = await startSessionWithStream({ omitStopTask });
+
+ await handle.send({ type: 'user', content: 'spawn background work' });
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await waitFor(() => taskEvents(events).length >= 1, 'wake task observed');
+ stream.emit(turnResult('waiting'));
+ await waitFor(() => events.some((event) => event.type === 'done'), 'parent done observed');
+ const continuationId = events.find((event) => event.type === 'done')?.turnContinuationId;
+ expect(continuationId).toBeTypeOf('number');
+ if (!omitStopTask) {
+ fakeQuery.stopTask!.mockRejectedValueOnce(new Error('stop rejected'));
+ }
+
+ await expect(handle.requestGracefulStop?.()).rejects.toThrow(
+ 'could not confirm all background task stops',
+ );
+
+ expect(fakeQuery.interrupt).toHaveBeenCalledOnce();
+ expect(fakeQuery.close).not.toHaveBeenCalled();
+ expect(handle.beginTurnContinuationWait?.(continuationId)).toBe('awaiting');
+ expect(handle.isTurnRunning?.()).toBe(true);
+ expect(events.filter(isProductTerminal)).toHaveLength(0);
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ },
+ );
+
+ it('graceful stop stays unconfirmed when a new wake task appears before interrupt ACK', async () => {
+ const { handle, stream, events, fakeQuery } = await startSessionWithStream();
+
+ await handle.send({ type: 'user', content: 'ordinary foreground turn' });
+ const interrupt = createDeferred<void>();
+ fakeQuery.interrupt.mockImplementationOnce(() => interrupt.promise);
+ const stop = handle.requestGracefulStop?.();
+ await waitFor(() => fakeQuery.interrupt.mock.calls.length === 1, 'interrupt dispatched');
+
+ stream.emit(taskStarted('task-late', 'local_agent'));
+ await waitFor(() => taskEvents(events).length >= 1, 'late wake task observed');
+ interrupt.resolve(undefined);
+
+ await expect(stop).rejects.toThrow('could not confirm all background task stops');
+ expect(fakeQuery.stopTask).not.toHaveBeenCalled();
+ expect(fakeQuery.close).not.toHaveBeenCalled();
+ expect(handle.listBackgroundTasks?.().map((task) => task.taskId)).toEqual(['task-late']);
+ expect(handle.isTurnRunning?.()).toBe(true);
+
+ stream.end();
+ await handle.close().catch(() => undefined);
+ });
+
+ it('concurrent Session graceful-stop requests share one continuation cancellation', async () => {
+ const { handle, stream, fakeQuery } = await startSessionWithStream(undefined, {
+ autoCollect: false,
+ });
+ const session = wrapInSession(handle);
+ const seen: AgentEvent[] = [];
+ session.onEvent((event) => seen.push(event));
+
+ await session.send('spawn background work');
+ stream.emit(taskStarted('task-agent', 'local_agent'));
+ await waitFor(() => taskEvents(seen).length >= 1, 'Session observed wake task');
+ stream.emit(turnResult('waiting'));
+ await waitFor(
+ () => seen.some((event) => event.type === 'done' && event.turnContinuationId !== undefined),
+ 'Session observed claimed parent done',
+ );
+
+ const interrupt = createDeferred<void>();
+ fakeQuery.interrupt.mockImplementationOnce(() => interrupt.promise);
+ const first = session.requestGracefulStop();
+ const second = session.requestGracefulStop();
+ await waitFor(() => fakeQuery.interrupt.mock.calls.length === 1, 'single interrupt dispatched');
+ expect(fakeQuery.stopTask).toHaveBeenCalledTimes(1);
+ interrupt.resolve(undefined);
+
+ await expect(Promise.all([first, second])).resolves.toEqual([
+ { status: 'requested', turnGeneration: 1 },
+ { status: 'requested', turnGeneration: 1 },
+ ]);
+ await waitFor(() => session.isTurnRunning() === false, 'Session continuation settled');
+ expect(fakeQuery.interrupt).toHaveBeenCalledTimes(1);
+ expect(fakeQuery.stopTask).toHaveBeenCalledTimes(1);
+
+ stream.end();
+ await session.close().catch(() => undefined);
+ });
+
it('只给会触发 SDK 自动续 turn 的 wake 任务对应 done 附 continuation claim', async () => {
const { handle, stream, events } = await startSessionWithStream();
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index cf5e85e9b3..fb1895655d 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -1795,6 +1795,7 @@ export class ClaudeCodeAgent extends BaseAgent {
const decision = await dispatchInteraction({
kind: 'ask_user_question',
requestId: options.toolUseID,
+ toolUseId: options.toolUseID,
questions,
});
if (decision.kind !== 'ask_user_question') {
@@ -1830,6 +1831,7 @@ export class ClaudeCodeAgent extends BaseAgent {
const decision = await dispatchInteraction({
kind: 'plan_review',
requestId: options.toolUseID,
+ toolUseId: options.toolUseID,
plan,
planFilePath,
});
@@ -1972,6 +1974,7 @@ export class ClaudeCodeAgent extends BaseAgent {
const permissionRequest = {
kind: 'permission' as const,
requestId: options.toolUseID,
+ toolUseId: options.toolUseID,
toolName,
input: input as Record<string, unknown>,
title: hostApprovalPresentation?.title ?? options.title,
@@ -2921,6 +2924,7 @@ export class ClaudeCodeAgent extends BaseAgent {
const decision = await dispatchWithTimeout({
kind: 'ask_user_question',
requestId: params.requestId,
+ toolUseId: params.requestId,
questions: (params.questions ?? askInput.questions ?? []) as AskUserQuestionItem[],
});
if (decision.kind !== 'ask_user_question') {
@@ -2945,6 +2949,7 @@ export class ClaudeCodeAgent extends BaseAgent {
const decision = await dispatchWithTimeout({
kind: 'plan_review',
requestId: params.requestId,
+ toolUseId: params.requestId,
plan,
planFilePath: params.planFilePath ?? planInput.planFilePath,
});
@@ -3070,6 +3075,7 @@ export class ClaudeCodeAgent extends BaseAgent {
const remotePermissionRequest = {
kind: 'permission' as const,
requestId: params.requestId,
+ toolUseId: params.requestId,
toolName: params.toolName ?? 'unknown',
input: params.input ?? {},
title: remoteHostApprovalPresentation?.title ?? params.title,
@@ -3881,14 +3887,16 @@ export class ClaudeCodeAgent extends BaseAgent {
// 逐个发起 stopTask,但不在这里等待 RPC:interrupt 必须先按控制通道顺序发出。
// 返回每个 RPC 的 promise,供 interrupt ACK 后只退休真正成功的任务;失败任务
// 仍留在本地账中,等待 provider 的真实 completed/stopped 事件继续记账。
+ const runningWakeTaskIds = (): string[] =>
+ [...runningBackgroundTasks.entries()]
+ .filter(([, info]) => info.wake)
+ .map(([taskId]) => taskId);
+
function stopRunningWakeBackgroundTasks(
reason: string,
): Array<{ taskId: string; promise: Promise<void> }> {
if (runningBackgroundTasks.size === 0) return [];
- const wakeIds: string[] = [];
- for (const [taskId, info] of runningBackgroundTasks) {
- if (info.wake) wakeIds.push(taskId);
- }
+ const wakeIds = runningWakeTaskIds();
if (wakeIds.length === 0) return [];
// 远端老 daemon / 老 SDK 没有 stopTask:退化为原行为(interrupt-only),
// proxy 活动检测 + 「全部停止」兜底仍在。
@@ -3934,6 +3942,45 @@ export class ClaudeCodeAgent extends BaseAgent {
return requests;
}
+ async function settleWakeStopRequests(
+ requests: Array<{ taskId: string; promise: Promise<void> }>,
+ ): Promise<{ fulfilledWakeIds: string[]; rejectedWakeIds: string[] }> {
+ const settled = await Promise.allSettled(requests.map(({ promise }) => promise));
+ const fulfilledWakeIds: string[] = [];
+ const rejectedWakeIds: string[] = [];
+ requests.forEach(({ taskId }, index) => {
+ if (settled[index]?.status === 'fulfilled') fulfilledWakeIds.push(taskId);
+ else rejectedWakeIds.push(taskId);
+ });
+ return { fulfilledWakeIds, rejectedWakeIds };
+ }
+
+ async function waitForGracefulStopStep<T>(
+ promise: Promise<T>,
+ signal?: AbortSignal,
+ ): Promise<T> {
+ if (!signal) return promise;
+ if (signal.aborted) throw new DOMException('aborted', 'AbortError');
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => {
+ cleanup();
+ reject(new DOMException('aborted', 'AbortError'));
+ };
+ const cleanup = () => signal.removeEventListener('abort', onAbort);
+ signal.addEventListener('abort', onAbort, { once: true });
+ void promise.then(
+ (value) => {
+ cleanup();
+ resolve(value);
+ },
+ (error) => {
+ cleanup();
+ reject(error);
+ },
+ );
+ });
+ }
+
// ── Middle-turn 事件过滤 (Codex review 3534925347 / 3535259132 / 3535293200) ──
// rewind rebuild 尾部注入的 /compact 是 SDK 独立 turn, 但从产品层看它是"用户 turn
// 的一部分" (预压缩) — 该 turn 的 done / status(isRunning=false) 不能让 register.ts
@@ -5427,6 +5474,58 @@ export class ClaudeCodeAgent extends BaseAgent {
armUpstreamResponseIdle();
},
+ async requestGracefulStop(stopOpts) {
+ if (canceledBridgeQueries.has(q)) {
+ throw new Error('Claude query is no longer active');
+ }
+ const awaitingContinuation = activeContinuationClaim();
+ if (!turnInFlight && awaitingContinuation?.state !== 'awaiting') {
+ throw new Error('No active Claude turn to stop');
+ }
+ const generation = turnState.generation;
+ turnState.interruptRequested = true;
+ turnState.interruptGeneration = generation;
+ dismissAllPending('graceful_stop', 'deny');
+ // A parent result can leave the foreground idle while wake tasks still
+ // own an awaiting continuation. Interrupting that idle Query alone does
+ // not revoke the task-triggered follow-up turn. Share the same stopTask
+ // accounting as hard Stop, but keep graceful-stop fail-safe semantics:
+ // only confirmed task stops may close the local continuation contract,
+ // and any unsupported/rejected control request remains unconfirmed
+ // without closing the provider process.
+ const wakeIds = runningWakeTaskIds();
+ const stopRequests = stopRunningWakeBackgroundTasks('graceful_stop');
+ try {
+ await waitForGracefulStopStep(Promise.resolve().then(() => q.interrupt()), stopOpts?.signal);
+ const { fulfilledWakeIds, rejectedWakeIds } = await waitForGracefulStopStep(
+ settleWakeStopRequests(stopRequests),
+ stopOpts?.signal,
+ );
+ if (turnState.generation !== generation) return;
+ const fulfilledWakeIdSet = new Set(fulfilledWakeIds);
+ const unconfirmedWakeIds = runningWakeTaskIds().filter(
+ (taskId) => !fulfilledWakeIdSet.has(taskId),
+ );
+ if (
+ stopRequests.length !== wakeIds.length ||
+ rejectedWakeIds.length > 0 ||
+ unconfirmedWakeIds.length > 0
+ ) {
+ throw new Error('Claude graceful stop could not confirm all background task stops');
+ }
+ const stoppedClaim = markWakeTasksStopped(fulfilledWakeIds, 'graceful_stop');
+ const cancelledContinuation =
+ stoppedClaim ?? cancelActiveContinuation('graceful_stop');
+ if (cancelledContinuation) {
+ retireContinuationTasks(cancelledContinuation);
+ emitCancelledContinuationBoundary(cancelledContinuation, 'graceful_stop');
+ }
+ } catch (error) {
+ if (turnState.generation === generation) turnState.interruptRequested = false;
+ throw error;
+ }
+ },
+
async abort() {
// 只 interrupt 当前 turn, 不能 abortController.abort() ——
// 那会杀掉整个 SDK Query, 让 streaming-input 流断开 (for await 抛
@@ -5528,10 +5627,7 @@ export class ClaudeCodeAgent extends BaseAgent {
// stopTask and interrupt share an ordered control channel: an
// interrupt ACK guarantees these earlier stop requests have settled,
// so allSettled intentionally has no extra timeout here.
- const settledStops = await Promise.allSettled(stopRequests.map(({ promise }) => promise));
- const fulfilledWakeIds = stopRequests
- .filter((_, index) => settledStops[index]?.status === 'fulfilled')
- .map(({ taskId }) => taskId);
+ const { fulfilledWakeIds } = await settleWakeStopRequests(stopRequests);
// interrupt ACK authorizes retiring only wake tasks whose stop RPC
// also succeeded. Rejected stops remain tracked for provider events,
// preserving their continuation contract instead of creating an
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 4c1a0f674e..4b7a2785c1 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -497,6 +497,30 @@ async function nextEvent(iterator: AsyncIterator<AgentEvent>): Promise<AgentEven
}
describe('CodexAgent permissions', () => {
+ it('graceful stop sends only turn/interrupt for the current turn', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-graceful-stop' } };
+ if (method === Method.TurnInterrupt) return {};
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-graceful-stop',
+ model: 'gpt-5.5',
+ workingDir: '/repo',
+ permissionMode: 'auto',
+ });
+ await handle.send({ type: 'user', content: 'long turn' });
+
+ await expect(handle.requestGracefulStop?.()).resolves.toBeUndefined();
+ expect(host.request).toHaveBeenCalledWith(Method.TurnInterrupt, {
+ threadId: 'start-thread-id',
+ turnId: 'turn-graceful-stop',
+ });
+ expect(host.unsubscribeThread).not.toHaveBeenCalled();
+ await handle.close();
+ });
+
it('advertises distinct Ask, Auto, and Full access modes', () => {
const agent = new CodexAgent(createDeps());
expect(agent.capabilities.permissionModes?.map((mode) => mode.id)).toEqual([
@@ -889,6 +913,7 @@ describe('CodexAgent permissions', () => {
threadId: 'start-thread-id',
turnId: 'turn-wechat-policy',
itemId: 'cmd-risky',
+ approvalId: 'approval-risky',
command: 'rm -rf build',
cwd: '/repo',
}),
@@ -896,6 +921,8 @@ describe('CodexAgent permissions', () => {
expect(resolver).toHaveBeenCalledOnce();
expect(resolver.mock.calls[0]?.[0]).toMatchObject({
kind: 'permission',
+ requestId: 'approval-risky',
+ toolUseId: 'cmd-risky',
toolName: 'exec',
input: { command: 'rm -rf build' },
suggestions: undefined,
@@ -1702,9 +1729,19 @@ describe('CodexAgent capability routing', () => {
});
const handlers = host.getThreadHandlers();
- if (!handlers?.mcpServerElicitation) {
+ if (!handlers?.mcpServerElicitation || !handlers.itemStarted) {
throw new Error('expected mcpServerElicitation handler');
}
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-wechat-mcp',
+ item: {
+ id: 'contacts-call-1',
+ type: 'mcpToolCall',
+ server: 'cindy_contacts',
+ tool: 'call_tool',
+ },
+ });
handlers.turnStarted?.({
threadId: 'start-thread-id',
turn: { id: 'early-capability-turn' },
@@ -1774,7 +1811,12 @@ describe('CodexAgent capability routing', () => {
content: '查一下我和康康的飞书消息',
});
const handlers = host.getThreadHandlers();
- if (!handlers?.mcpServerElicitation) {
+ if (
+ !handlers?.mcpServerElicitation
+ || !handlers.itemStarted
+ || !handlers.itemUpdated
+ || !handlers.itemCompleted
+ ) {
throw new Error('expected mcpServerElicitation handler');
}
handlers.itemStarted?.({
@@ -2132,6 +2174,105 @@ describe('CodexAgent capability routing', () => {
await handle.close();
});
+ it('tracks and tombstones descendant MCP items when compatibility events omit turnId', async () => {
+ const agent = new CodexAgent(
+ createDeps(
+ {},
+ {
+ capabilityRouting,
+ getMcpToolApprovalPolicy: () => 'auto-approve',
+ },
+ ),
+ );
+ const host = installFakeHost(
+ agent,
+ (method) => method === Method.TurnStart
+ ? { turn: { id: 'root-missing-turn-id' } }
+ : undefined,
+ { userAgent: 'mock-codex/0.145.0' },
+ );
+ const handle = await agent.startSession({
+ sessionId: 'session-descendant-missing-turn-id',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ await handle.send({
+ type: 'user',
+ content: '请用 $feishu-delegate:message-feishu-coworkers 查一下康康',
+ });
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemStarted || !handlers.descendantNotification || !handlers.mcpServerElicitation) {
+ throw new Error('expected descendant capability handlers');
+ }
+
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'root-missing-turn-id',
+ item: {
+ id: 'root-spawn-missing-turn-id',
+ type: 'subAgentActivity',
+ kind: 'started',
+ agentThreadId: 'child-missing-turn-id',
+ },
+ });
+ const childItem = {
+ id: 'child-routed-mcp-missing-turn-id',
+ type: 'mcpToolCall',
+ server: 'cindy-routed-feishu-delegate',
+ tool: 'feishu_read_messages',
+ pluginId: 'feishu-delegate@personal',
+ };
+ handlers.descendantNotification('child-missing-turn-id', 'item/started', {
+ threadId: 'child-missing-turn-id',
+ item: childItem,
+ });
+
+ const childRequest = {
+ threadId: 'child-missing-turn-id',
+ turnId: undefined as never,
+ serverName: 'cindy-routed-feishu-delegate',
+ mode: 'form' as const,
+ _meta: {
+ codex_approval_kind: 'mcp_tool_call',
+ tool_name: 'feishu_read_messages',
+ },
+ message: 'Allow tool call',
+ requestedSchema: {},
+ };
+ await expect(handlers.mcpServerElicitation(childRequest)).resolves.toEqual({
+ action: 'accept',
+ content: null,
+ _meta: null,
+ });
+
+ handlers.descendantNotification('child-missing-turn-id', 'item/completed', {
+ threadId: 'child-missing-turn-id',
+ item: childItem,
+ });
+ await expect(handlers.mcpServerElicitation(childRequest)).resolves.toEqual({
+ action: 'decline',
+ content: null,
+ _meta: null,
+ });
+
+ // A late duplicate start/update with the same compatibility shape must not
+ // resurrect provenance after the explicit completed-item tombstone.
+ for (const method of ['item/started', 'item/updated']) {
+ handlers.descendantNotification('child-missing-turn-id', method, {
+ threadId: 'child-missing-turn-id',
+ item: childItem,
+ });
+ }
+ await expect(handlers.mcpServerElicitation(childRequest)).resolves.toEqual({
+ action: 'decline',
+ content: null,
+ _meta: null,
+ });
+
+ await handle.close();
+ });
+
it('falls back to inherited thread selection when a child item predates turn binding', async () => {
const pendingTurnStart = deferred<{ turn: { id: string } }>();
const agent = new CodexAgent(
@@ -7832,6 +7973,58 @@ describe('CodexAgent MCP thread context hooks', () => {
}
});
+ it('gracefully stops the logical turn while an overload retry is pending', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ const host = installCapacityHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-overload-graceful-stop',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) events.push(event);
+ })();
+ await handle.send({ type: 'user', content: 'hello' });
+
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.error) throw new Error('expected error handler');
+ handlers.error({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ willRetry: false,
+ error: { message: CAPACITY_MESSAGE },
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(handle.getCurrentTurnId?.()).toBeNull();
+ expect(handle.isTurnRunning?.()).toBe(true);
+
+ await expect(handle.requestGracefulStop?.()).resolves.toBeUndefined();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(events).toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({
+ isTerminal: true,
+ reason: 'codex-turn-replay-retry-aborted',
+ }),
+ }));
+ expect(events).toContainEqual(expect.objectContaining({
+ type: 'status',
+ data: expect.objectContaining({ isRunning: false }),
+ }));
+ expect(handle.isTurnRunning?.()).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(40_000);
+ expect(turnStartCount(host)).toBe(1);
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('drops a pending retry when the original turn/start ultimately fails', async () => {
// 容量通知可能先于原始 turn/start 响应到达(协议允许的乱序),此时重投计时器
// 已排上。原始请求随后终失败会推 terminal error + Done,若不废掉重投,计时器
@@ -11271,6 +11464,16 @@ describe('CodexAgent MCP thread context hooks', () => {
if (!handlers?.mcpServerElicitation) {
throw new Error('expected mcpServerElicitation handler');
}
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-wechat-mcp',
+ item: {
+ id: 'contacts-call-1',
+ type: 'mcpToolCall',
+ server: 'cindy_contacts',
+ tool: 'call_tool',
+ },
+ });
const result = await handlers.mcpServerElicitation({
threadId: 'start-thread-id',
turnId: 'turn-wechat-mcp',
@@ -11292,9 +11495,76 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(resolver).toHaveBeenCalledOnce();
expect(resolver.mock.calls[0]?.[0]).toMatchObject({
kind: 'permission',
+ toolUseId: 'contacts-call-1',
toolName: 'mcp:cindy_contacts',
suggestions: undefined,
});
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-wechat-mcp',
+ item: {
+ id: 'contacts-call-2',
+ type: 'mcpToolCall',
+ server: 'cindy_contacts',
+ tool: 'call_tool',
+ },
+ });
+ await handlers.mcpServerElicitation({
+ threadId: 'start-thread-id',
+ turnId: 'turn-wechat-mcp',
+ serverName: 'cindy_contacts',
+ mode: 'form',
+ _meta: {
+ codex_approval_kind: 'mcp_tool_call',
+ tool_params: {
+ name: 'contacts_delete',
+ args: { id: 'contact-2' },
+ },
+ },
+ message: 'Allow another tool call',
+ requestedSchema: {},
+ });
+ expect(resolver.mock.calls[1]?.[0]).not.toHaveProperty('toolUseId');
+ for (const itemId of ['contacts-call-1', 'contacts-call-2']) {
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-wechat-mcp',
+ item: {
+ id: itemId,
+ type: 'mcpToolCall',
+ server: 'cindy_contacts',
+ tool: 'call_tool',
+ status: 'completed',
+ },
+ } as never);
+ }
+ handlers.itemUpdated({
+ threadId: 'start-thread-id',
+ turnId: 'turn-wechat-mcp',
+ item: {
+ id: 'contacts-call-2',
+ type: 'mcpToolCall',
+ server: 'cindy_contacts',
+ tool: 'call_tool',
+ status: 'inProgress',
+ },
+ } as never);
+ await handlers.mcpServerElicitation({
+ threadId: 'start-thread-id',
+ turnId: 'turn-wechat-mcp',
+ serverName: 'cindy_contacts',
+ mode: 'form',
+ _meta: {
+ codex_approval_kind: 'mcp_tool_call',
+ tool_params: {
+ name: 'contacts_delete',
+ args: { id: 'contact-3' },
+ },
+ },
+ message: 'Allow a late tool call',
+ requestedSchema: {},
+ });
+ expect(resolver.mock.calls[2]?.[0]).not.toHaveProperty('toolUseId');
await handle.close();
});
@@ -13170,7 +13440,19 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(resumeParams.dynamicTools).toBeUndefined();
const handlers = resumeHost.getThreadHandlers();
- if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall handler');
+ if (!handlers?.dynamicToolCall || !handlers.itemStarted) {
+ throw new Error('expected dynamicToolCall handler');
+ }
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-ios',
+ item: {
+ id: 'call-ios',
+ type: 'dynamicToolCall',
+ namespace: null,
+ tool: 'cindy_ios_simulator__call_tool',
+ },
+ });
const result = await handlers.dynamicToolCall(
{
threadId: 'resume-thread-id',
@@ -13286,6 +13568,7 @@ describe('CodexAgent MCP thread context hooks', () => {
handle.setInteractionResolver(async (request) => {
expect(request).toMatchObject({
kind: 'permission',
+ toolUseId: 'call-ios',
toolName: 'dynamic:cindy_ios_simulator:call_tool',
title: disclosure.title,
description: disclosure.description,
@@ -15066,9 +15349,19 @@ describe('CodexAgent MCP thread context hooks', () => {
workingDir: '/repo',
});
const handlers = host.getThreadHandlers();
- if (!handlers?.dynamicToolCall || !handlers.requestUserInput) {
+ if (!handlers?.dynamicToolCall || !handlers.requestUserInput || !handlers.itemStarted) {
throw new Error('expected user input handlers');
}
+ handlers.itemStarted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'dynamic-call-1',
+ type: 'dynamicToolCall',
+ namespace: null,
+ tool: 'cindy__ask_user_question',
+ },
+ });
let requestCount = 0;
const pendingDecision = deferred<InteractionDecision>();
handle.setInteractionResolver(async (req) => {
@@ -15076,6 +15369,7 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(req).toMatchObject({
kind: 'ask_user_question',
requestId: 'req-dynamic',
+ toolUseId: 'dynamic-call-1',
});
return pendingDecision.promise;
});
@@ -21142,6 +21436,158 @@ describe('CodexAgent upstream-response-idle watchdog', () => {
}
});
+ it('graceful stop interrupt 被拒绝后重新武装同一 turn 的 idle watchdog', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ let interruptAttempts = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-stop-rejected' } };
+ if (method === Method.TurnInterrupt) {
+ interruptAttempts += 1;
+ if (interruptAttempts === 1) return Promise.reject(new Error('interrupt rejected'));
+ return {};
+ }
+ return undefined;
+ });
+ const handle = await startIdleSession(agent, 'session-stop-rejected-watchdog');
+ const seen = collectEvents(handle);
+ await handle.send({ type: 'user', content: 'go' });
+ const handlers = host.getThreadHandlers();
+ if (!handlers) throw new Error('expected thread handlers');
+ handlers.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-stop-rejected' },
+ } as never);
+ await vi.advanceTimersByTimeAsync(IDLE_MS - 10_000);
+
+ await expect(handle.requestGracefulStop?.()).rejects.toThrow('interrupt rejected');
+ expect(handle.isTurnRunning?.()).toBe(true);
+
+ await vi.advanceTimersByTimeAsync(9_999);
+ expect(interruptAttempts).toBe(1);
+ expect(seen).not.toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'upstream_response_idle_timeout' }),
+ }));
+
+ await vi.advanceTimersByTimeAsync(2);
+ expect(interruptAttempts).toBeGreaterThanOrEqual(2);
+ expect(seen).toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'upstream_response_idle_timeout' }),
+ }));
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('graceful stop 确认超时后重新武装同一 turn 的 idle watchdog', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ let interruptAttempts = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-stop-timeout' } };
+ if (method === Method.TurnInterrupt) {
+ interruptAttempts += 1;
+ if (interruptAttempts === 1) return new Promise<never>(() => undefined);
+ return {};
+ }
+ return undefined;
+ });
+ const handle = await startIdleSession(agent, 'session-stop-timeout-watchdog');
+ const seen = collectEvents(handle);
+ await handle.send({ type: 'user', content: 'go' });
+ const handlers = host.getThreadHandlers();
+ if (!handlers) throw new Error('expected thread handlers');
+ handlers.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-stop-timeout' },
+ } as never);
+ await vi.advanceTimersByTimeAsync(IDLE_MS - 15_000);
+
+ const controller = new AbortController();
+ const stop = handle.requestGracefulStop?.({ signal: controller.signal });
+ controller.abort();
+ await expect(stop).rejects.toThrow('confirmation timed out');
+ expect(handle.isTurnRunning?.()).toBe(true);
+
+ await vi.advanceTimersByTimeAsync(14_999);
+ expect(interruptAttempts).toBe(1);
+ expect(seen).not.toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'upstream_response_idle_timeout' }),
+ }));
+
+ await vi.advanceTimersByTimeAsync(2);
+ expect(interruptAttempts).toBeGreaterThanOrEqual(2);
+ expect(seen).toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'upstream_response_idle_timeout' }),
+ }));
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('graceful stop 失败期间的新 provider 活动保留新 deadline,不恢复旧快照', async () => {
+ vi.useFakeTimers();
+ try {
+ const interrupt = deferred<void>();
+ const agent = new CodexAgent(createDeps());
+ let interruptAttempts = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-stop-new-activity' } };
+ if (method === Method.TurnInterrupt) {
+ interruptAttempts += 1;
+ if (interruptAttempts === 1) return interrupt.promise;
+ return {};
+ }
+ return undefined;
+ });
+ const handle = await startIdleSession(agent, 'session-stop-new-activity');
+ const seen = collectEvents(handle);
+ await handle.send({ type: 'user', content: 'go' });
+ const handlers = host.getThreadHandlers();
+ if (!handlers) throw new Error('expected thread handlers');
+ handlers.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-stop-new-activity' },
+ } as never);
+ await vi.advanceTimersByTimeAsync(IDLE_MS - 10_000);
+
+ const stop = handle.requestGracefulStop?.();
+ handlers.itemStarted?.({
+ threadId: 'start-thread-id',
+ turnId: 'turn-stop-new-activity',
+ item: { type: 'agentMessage', id: 'still-working', text: 'still working' },
+ } as never);
+ interrupt.reject(new Error('interrupt rejected'));
+ await expect(stop).rejects.toThrow('interrupt rejected');
+
+ // 旧快照只剩 10s;新 provider 活动应建立完整 60s deadline。
+ await vi.advanceTimersByTimeAsync(10_001);
+ expect(interruptAttempts).toBe(1);
+ expect(seen).not.toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'upstream_response_idle_timeout' }),
+ }));
+
+ await vi.advanceTimersByTimeAsync(IDLE_MS - 10_000);
+ expect(interruptAttempts).toBeGreaterThanOrEqual(2);
+ expect(seen).toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'upstream_response_idle_timeout' }),
+ }));
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('工具执行期间停表:长命令不会被误杀', async () => {
vi.useFakeTimers();
try {
@@ -21734,6 +22180,128 @@ describe('CodexAgent reconnect-stall watchdog', () => {
}
});
+ it('graceful stop interrupt 被拒绝后重新武装同一 turn 的 reconnect watchdog', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ let interruptAttempts = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-reconnect-stop-rejected' } };
+ if (method === Method.TurnInterrupt) {
+ interruptAttempts += 1;
+ if (interruptAttempts === 1) return Promise.reject(new Error('interrupt rejected'));
+ return {};
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-reconnect-stop-rejected',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const seen: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) seen.push(event);
+ })();
+ await handle.send({ type: 'user', content: 'go' });
+ const handlers = host.getThreadHandlers();
+ if (!handlers) throw new Error('expected thread handlers');
+ handlers.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-reconnect-stop-rejected' },
+ } as never);
+ handlers.error?.({
+ threadId: 'start-thread-id',
+ turnId: 'turn-reconnect-stop-rejected',
+ error: { message: 'Reconnecting... 1/5' },
+ willRetry: true,
+ } as never);
+ await vi.advanceTimersByTimeAsync(RECONNECT_STALL_MS - 20_000);
+
+ await expect(handle.requestGracefulStop?.()).rejects.toThrow('interrupt rejected');
+ await vi.advanceTimersByTimeAsync(19_999);
+
+ expect(interruptAttempts).toBe(1);
+ expect(seen).not.toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'codex_reconnect_stalled' }),
+ }));
+
+ await vi.advanceTimersByTimeAsync(2);
+
+ expect(interruptAttempts).toBeGreaterThanOrEqual(2);
+ expect(seen).toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'codex_reconnect_stalled' }),
+ }));
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('graceful stop 确认超时后恢复 reconnect watchdog 的剩余 deadline', async () => {
+ vi.useFakeTimers();
+ try {
+ const agent = new CodexAgent(createDeps());
+ let interruptAttempts = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-reconnect-stop-timeout' } };
+ if (method === Method.TurnInterrupt) {
+ interruptAttempts += 1;
+ if (interruptAttempts === 1) return new Promise<never>(() => undefined);
+ return {};
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-reconnect-stop-timeout',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const seen: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) seen.push(event);
+ })();
+ await handle.send({ type: 'user', content: 'go' });
+ const handlers = host.getThreadHandlers();
+ if (!handlers) throw new Error('expected thread handlers');
+ handlers.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-reconnect-stop-timeout' },
+ } as never);
+ handlers.error?.({
+ threadId: 'start-thread-id',
+ turnId: 'turn-reconnect-stop-timeout',
+ error: { message: 'Reconnecting... 1/5' },
+ willRetry: true,
+ } as never);
+ await vi.advanceTimersByTimeAsync(RECONNECT_STALL_MS - 25_000);
+
+ const controller = new AbortController();
+ const stop = handle.requestGracefulStop?.({ signal: controller.signal });
+ controller.abort();
+ await expect(stop).rejects.toThrow('confirmation timed out');
+ await vi.advanceTimersByTimeAsync(24_999);
+
+ expect(interruptAttempts).toBe(1);
+ expect(seen).not.toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'codex_reconnect_stalled' }),
+ }));
+
+ await vi.advanceTimersByTimeAsync(2);
+ expect(interruptAttempts).toBeGreaterThanOrEqual(2);
+ expect(seen).toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'codex_reconnect_stalled' }),
+ }));
+ await handle.close();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('子代理进展不算主 turn 恢复:reconnect deadline 照旧到点收口', async () => {
// eventQueue.push 的探针会刷新 upstreamIdleLastEventAt + armUpstreamIdle(),并把事件喂给
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 8c16d9ac0b..d995d8beaf 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -4408,7 +4408,11 @@ export class CodexAgent extends BaseAgent {
bindCapabilitySelectionToDescendantTurn(childThreadId, turnId);
} else if (isItemNotification && !descendantTurnIsTerminal) {
bindCapabilitySelectionToDescendantTurn(childThreadId, turnId);
- noteActiveToolContext(record?.item, turnId);
+ if (method === 'item/completed') {
+ completeActiveToolContext(record?.item, turnId);
+ } else {
+ noteActiveToolContext(record?.item, turnId);
+ }
}
// 嵌套子代理:孙线程的 spawn item 只出现在**子线程自己**的事件流里,主线程的
@@ -4527,6 +4531,7 @@ export class CodexAgent extends BaseAgent {
unregisterCodexMcpContext(threadId);
unregisterDescendantCodexMcpContexts();
activeToolContexts.clear();
+ completedActiveToolTurns.clear();
capabilitySelectionTextByTurnId.clear();
capabilitySelectionTextByThreadId.clear();
descendantParentThreadByThreadId.clear();
@@ -5385,6 +5390,7 @@ export class CodexAgent extends BaseAgent {
const userInputBroker = new CodexInteractionBroker<ToolRequestUserInputResponse>();
const dynamicToolBroker = new CodexInteractionBroker<DynamicToolCallResponse>();
const activeToolContexts = new Map<string, ActiveToolContext>();
+ const completedActiveToolTurns = new Map<string, string | null | undefined>();
// A single model turn can surface the same visible question through both
// the native requestUserInput request and the dynamic-tool compatibility
// path. Join an in-flight interaction, then replay its submitted answers
@@ -5948,6 +5954,21 @@ export class CodexAgent extends BaseAgent {
let upstreamIdleRemainingMs = 0;
/** 当前分片的起始壁钟时刻;片尾据此识别系统挂起。 */
let upstreamIdleSliceStartedAt = 0;
+ /** 主 turn 可见活动的单调代次;防止 stop 失败后的迟到恢复覆盖期间新装的 watchdog。 */
+ let watchdogActivityVersion = 0;
+ function captureWatchdogRemainingMs(
+ timer: ReturnType<typeof setTimeout> | null,
+ remainingMs: number,
+ sliceStartedAt: number,
+ ): number | null {
+ if (!timer && remainingMs <= 0) return null;
+ if (!timer || sliceStartedAt <= 0 || remainingMs <= 0) return Math.max(0, remainingMs);
+ const slice = Math.min(remainingMs, CODEX_UPSTREAM_IDLE_SLICE_MS);
+ const elapsed = Math.max(0, Date.now() - sliceStartedAt);
+ // 与分片回调保持相同的 suspend 语义:超长壁钟间隔不计入“清醒等待”额度。
+ if (elapsed > slice + CODEX_UPSTREAM_IDLE_SUSPEND_GAP_MS) return remainingMs;
+ return Math.max(0, remainingMs - elapsed);
+ }
function clearUpstreamIdle(): void {
if (upstreamIdleTimer) {
clearTimeout(upstreamIdleTimer);
@@ -5991,6 +6012,13 @@ export class CodexAgent extends BaseAgent {
upstreamIdleRemainingMs = upstreamIdleTimeoutMs;
armUpstreamIdleSlice();
}
+ function restoreUpstreamIdle(remainingMs: number): void {
+ if (upstreamIdleTimer || upstreamIdleRemainingMs > 0) return;
+ if (upstreamIdleTimeoutMs <= 0 || closed || !isTurnInFlight) return;
+ if (pendingToolItemIds.size > 0) return;
+ upstreamIdleRemainingMs = Math.max(1, Math.min(remainingMs, upstreamIdleTimeoutMs));
+ armUpstreamIdleSlice();
+ }
/**
* 分片计时,片尾核对真实耗时。不能用一个 30 分钟的长定时器直接判定 —— Electron 被
* 系统挂起(合盖睡眠)期间没有任何事件,定时器一旦在唤醒后到期就立刻开火,一次午休
@@ -6144,6 +6172,27 @@ export class CodexAgent extends BaseAgent {
reconnectStallRemainingMs = CODEX_RECONNECT_STALL_TIMEOUT_MS;
armReconnectStallSlice();
}
+ function restoreReconnectStall(
+ turnId: string,
+ turnGeneration: number,
+ remainingMs: number,
+ ): void {
+ if (reconnectStallTimer || reconnectStallRemainingMs > 0) return;
+ if (
+ closed ||
+ reconnectStallCleanupTurnId !== null ||
+ !isTurnInFlight ||
+ currentTurnId !== turnId ||
+ turnStartGeneration !== turnGeneration
+ ) return;
+ reconnectStallTurnId = turnId;
+ reconnectStallTurnGeneration = turnGeneration;
+ reconnectStallRemainingMs = Math.max(
+ 1,
+ Math.min(remainingMs, CODEX_RECONNECT_STALL_TIMEOUT_MS),
+ );
+ armReconnectStallSlice();
+ }
function isReconnectRecoveryEvent(event: AgentEvent): boolean {
if (event.type === 'text') {
@@ -6402,6 +6451,7 @@ export class CodexAgent extends BaseAgent {
// 子代理卡帧只是"子线程有进展",不代表主 turn 还活着 —— 不参与静默计时与
// reconnect 恢复判定,否则主 turn 哑火时会被子代理的心跳一直掩盖(review)。
if (!emittingDescendantUpdate && ev.turnScope !== 'background') {
+ watchdogActivityVersion += 1;
upstreamIdleLastEventType = ev.type;
upstreamIdleLastEventAt = Date.now();
armUpstreamIdle();
@@ -6466,6 +6516,7 @@ export class CodexAgent extends BaseAgent {
const decision = await awaitApprovalDecision(params.threadId, params.turnId, requestId, 'commandExecution', {
kind: 'permission',
requestId,
+ toolUseId: params.itemId,
toolName: 'exec',
input: commandExecutionDisplayInput(params.command ?? '', params.cwd ?? ''),
title: 'Allow Codex to run this command?',
@@ -6501,6 +6552,7 @@ export class CodexAgent extends BaseAgent {
const decision = await awaitApprovalDecision(params.threadId, params.turnId, requestId, 'fileChange', {
kind: 'permission',
requestId,
+ toolUseId: params.itemId,
toolName: 'file_change',
input: { grantRoot: params.grantRoot ?? null },
title: 'Allow Codex to change files?',
@@ -6587,12 +6639,15 @@ export class CodexAgent extends BaseAgent {
return stringFromMeta(recordFromUnknown(context.toolParams), 'name');
}
- function mcpToolPluginId(
+ function matchingActiveMcpTools(
params: McpServerElicitationRequestParams,
- ): string | null | undefined {
+ ): Array<{ itemId: string; context: ActiveToolContext }> {
const toolName = stringFromMeta(mcpElicitationMeta(params), 'tool_name');
- const matches: ActiveToolContext[] = [];
- for (const context of activeToolContexts.values()) {
+ const matches: Array<{
+ itemId: string;
+ context: ActiveToolContext;
+ }> = [];
+ for (const [itemId, context] of activeToolContexts) {
if (
context.type !== 'mcpToolCall' ||
context.turnId !== params.turnId ||
@@ -6601,17 +6656,32 @@ export class CodexAgent extends BaseAgent {
) {
continue;
}
- matches.push(context);
+ matches.push({ itemId, context });
}
+ return matches;
+ }
+
+ function mcpToolPluginId(
+ params: McpServerElicitationRequestParams,
+ ): string | null | undefined {
+ const toolName = stringFromMeta(mcpElicitationMeta(params), 'tool_name');
+ const matches = matchingActiveMcpTools(params);
if (matches.length === 0 || (!toolName && matches.length !== 1)) {
return undefined;
}
- const pluginId = matches[0]?.pluginId;
- return matches.every((context) => context.pluginId === pluginId)
+ const pluginId = matches[0]?.context.pluginId;
+ return matches.every(({ context }) => context.pluginId === pluginId)
? pluginId
: undefined;
}
+ function activeMcpToolUseId(
+ params: McpServerElicitationRequestParams,
+ ): string | undefined {
+ const matches = matchingActiveMcpTools(params);
+ return matches.length === 1 ? matches[0]?.itemId : undefined;
+ }
+
const classifyMcpToolApprovalPolicy = (
context: Parameters<NonNullable<AgentDeps['getMcpToolApprovalPolicy']>>[0],
) => {
@@ -6756,6 +6826,7 @@ export class CodexAgent extends BaseAgent {
const meta = mcpElicitationMeta(params);
const toolTitle = stringFromMeta(meta, 'tool_title');
const innerToolName = mcpInnerToolName(params);
+ const toolUseId = activeMcpToolUseId(params);
const requestId = `mcp-elicitation:${params.serverName}:${params.turnId ?? params.threadId}:${++mcpElicitationSeq}`;
const decision = await awaitApprovalDecision(
params.threadId,
@@ -6765,6 +6836,7 @@ export class CodexAgent extends BaseAgent {
{
kind: 'permission',
requestId,
+ ...(toolUseId ? { toolUseId } : {}),
toolName: `mcp:${params.serverName}`,
input: policyPermissionInput,
title:
@@ -6781,6 +6853,7 @@ export class CodexAgent extends BaseAgent {
{
forcePrompt:
turnPolicyForcePrompt || approvalPolicy === 'prompt-each-time',
+ ...(toolUseId ? { itemId: toolUseId } : {}),
},
);
@@ -6813,6 +6886,7 @@ export class CodexAgent extends BaseAgent {
const decision = await awaitApprovalDecision(params.threadId, params.turnId, requestId, 'commandExecution', {
kind: 'permission',
requestId,
+ ...(params.itemId ? { toolUseId: params.itemId } : {}),
toolName: 'permissions',
input: { permissions: params.permissions },
title: 'Allow Codex to use these permissions?',
@@ -6871,13 +6945,42 @@ export class CodexAgent extends BaseAgent {
function noteActiveToolContext(item: unknown, turnId?: string | null): void {
const active = activeToolContextFromItem(item, turnId);
if (!active) return;
+ if (
+ completedActiveToolTurns.has(active.id)
+ && completedActiveToolTurns.get(active.id) === turnId
+ ) return;
activeToolContexts.set(active.id, active.ctx);
}
+ function completeActiveToolContext(item: unknown, turnId?: string | null): void {
+ if (!item || typeof item !== 'object') return;
+ const itemId = typeof (item as Record<string, unknown>).id === 'string'
+ ? (item as Record<string, unknown>).id as string
+ : '';
+ if (!itemId) return;
+ activeToolContexts.delete(itemId);
+ completedActiveToolTurns.set(itemId, turnId);
+ }
+
+ function activeDynamicToolUseId(params: DynamicToolCallParams): string | undefined {
+ const matches = [...activeToolContexts.entries()].filter(([, context]) =>
+ context.type === 'dynamicToolCall'
+ && context.turnId === params.turnId
+ && context.namespace === params.namespace
+ && context.tool === params.tool,
+ );
+ const exact = matches.find(([itemId]) => itemId === params.callId);
+ if (exact) return exact[0];
+ return matches.length === 1 ? matches[0]?.[0] : undefined;
+ }
+
function clearActiveToolContextsForTurn(turnId: string): void {
for (const [itemId, ctx] of activeToolContexts) {
if (ctx.turnId === turnId) activeToolContexts.delete(itemId);
}
+ for (const [itemId, completedTurnId] of completedActiveToolTurns) {
+ if (completedTurnId === turnId) completedActiveToolTurns.delete(itemId);
+ }
// Lifecycle callers dismiss the broker entries first. Wake joined waiters
// before dropping the lookup maps so they can observe that their request
// is no longer pending instead of reopening the interaction.
@@ -6937,6 +7040,7 @@ export class CodexAgent extends BaseAgent {
questions: ToolRequestUserInputQuestion[],
turnId?: string | null,
isRequestPending: () => boolean = () => true,
+ toolUseId?: string,
): Promise<ToolRequestUserInputResponse> {
if (questions.some((q) => q.isSecret)) {
log.warn('requestUserInput secret question refused', {
@@ -6978,7 +7082,7 @@ export class CodexAgent extends BaseAgent {
turnId,
});
return isRequestPending()
- ? askUserViaInteraction(requestId, questions, turnId, isRequestPending)
+ ? askUserViaInteraction(requestId, questions, turnId, isRequestPending, toolUseId)
: emptyUserInputResponse(questions);
}
return responseFromUserInputAnswersByPosition(questions, joined.answersByPosition);
@@ -6988,6 +7092,7 @@ export class CodexAgent extends BaseAgent {
const decision = await dispatchInteraction({
kind: 'ask_user_question',
requestId,
+ ...(toolUseId ? { toolUseId } : {}),
questions: questionsToAskUserItems(questions),
});
if (decision.kind !== 'ask_user_question') {
@@ -7078,6 +7183,7 @@ export class CodexAgent extends BaseAgent {
const decision = await dispatchInteraction({
kind: 'permission',
requestId,
+ toolUseId: params.itemId,
toolName,
input: {
itemId: params.itemId,
@@ -7150,6 +7256,7 @@ export class CodexAgent extends BaseAgent {
questions,
params.turnId,
() => userInputBroker.has({ connectionId, requestId: meta.requestId }),
+ params.itemId,
);
settle(response);
},
@@ -7194,6 +7301,7 @@ export class CodexAgent extends BaseAgent {
success: false,
};
}
+ const toolUseId = activeDynamicToolUseId(params);
if (isAskUserDynamicTool(params)) {
const requestId = String(meta.requestId);
// 挂起期间服务端已取消本请求 (greptile R13 P1): 直接回失败响应, 不注册
@@ -7226,6 +7334,7 @@ export class CodexAgent extends BaseAgent {
questions,
params.turnId,
() => dynamicToolBroker.has({ connectionId, requestId: meta.requestId }),
+ toolUseId,
);
settle(dynamicToolResponseFromUserInput(response));
},
@@ -7260,6 +7369,7 @@ export class CodexAgent extends BaseAgent {
{
kind: 'permission',
requestId,
+ ...(toolUseId ? { toolUseId } : {}),
toolName: `dynamic:${serverName}:${toolName}`,
input: { serverName, toolName, toolParams: params.arguments },
title: hostApprovalPresentation?.title ?? `Allow Codex to use ${serverName}?`,
@@ -7267,7 +7377,10 @@ export class CodexAgent extends BaseAgent {
hostApprovalPresentation?.description ??
`Codex requested ${serverName}.${toolName}.`,
},
- { forcePrompt: approvalPolicy === 'prompt-each-time' },
+ {
+ forcePrompt: approvalPolicy === 'prompt-each-time',
+ ...(toolUseId ? { itemId: toolUseId } : {}),
+ },
);
if (decision !== 'accept' && decision !== 'acceptForSession') {
return {
@@ -8537,29 +8650,34 @@ export class CodexAgent extends BaseAgent {
* 闩, Codex coordinator 刻意等这个事件而不自解锁, hook runner 要等一小时硬超时
* (review #844 greptile P1)。
*/
- const settleCancelledOverloadRetry = (
+ const settleOverloadRetryLogicalTurn = (
state: NonNullable<typeof overloadRetry>,
- reason: string,
- ): void => {
- if (closed || overloadRetry !== state) return;
- discardOverloadRetry(`settle:${reason}`);
+ opts: {
+ reason: string;
+ message: string;
+ eventReason: string;
+ logMessage: string;
+ },
+ ): boolean => {
+ if (closed || overloadRetry !== state) return false;
+ discardOverloadRetry(`settle:${opts.reason}`);
// 重投的 turnStarted 已先于响应到达时, currentTurnId 指着一个真实在跑的
// server turn —— 必须一起收掉, 否则它会在调用方按"已取消"处理后继续执行工具。
- teardownActiveTurnForCancellation(reason);
+ teardownActiveTurnForCancellation(opts.reason);
markInFlightStartsTerminallySettled();
// 还有 turn/start 在飞时同理: 它的响应晚于本次收口回来, 不隔离就会被正常激活。
// 全部隔离而不只是最新那个: 取消的语义是"这一轮什么都别再跑"。
quarantineAllInFlightStarts();
- log.info('codex overload retry cancelled via send signal — settling logical turn', {
- reason,
+ log.info(opts.logMessage, {
+ reason: opts.reason,
threadId,
});
eventQueue.push({
type: 'error',
data: {
- message: 'Codex turn cancelled while waiting for an automatic retry',
+ message: opts.message,
isTerminal: true,
- reason: 'codex-turn-replay-retry-cancelled',
+ reason: opts.eventReason,
},
source: 'codex',
});
@@ -8568,8 +8686,31 @@ export class CodexAgent extends BaseAgent {
data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },
source: 'codex',
});
+ return true;
};
+ const settleCancelledOverloadRetry = (
+ state: NonNullable<typeof overloadRetry>,
+ reason: string,
+ ): void => {
+ settleOverloadRetryLogicalTurn(state, {
+ reason,
+ message: 'Codex turn cancelled while waiting for an automatic retry',
+ eventReason: 'codex-turn-replay-retry-cancelled',
+ logMessage: 'codex overload retry cancelled via send signal — settling logical turn',
+ });
+ };
+
+ const settleStoppedOverloadRetry = (
+ state: NonNullable<typeof overloadRetry>,
+ reason: string,
+ ): boolean => settleOverloadRetryLogicalTurn(state, {
+ reason,
+ message: 'Codex turn stopped while waiting for an automatic retry',
+ eventReason: 'codex-turn-replay-retry-aborted',
+ logMessage: 'codex overload retry stopped — settling logical turn',
+ });
+
/**
* 零产出 provider 终态错误的退避重投调度。
*
@@ -9014,6 +9155,7 @@ export class CodexAgent extends BaseAgent {
dismissAllPending('app_server_force_retired', 'deny');
dismissAllPendingUserInput('transport_error');
activeToolContexts.clear();
+ completedActiveToolTurns.clear();
capabilitySelectionTextByTurnId.clear();
capabilitySelectionTextByThreadId.clear();
descendantParentThreadByThreadId.clear();
@@ -9500,7 +9642,7 @@ export class CodexAgent extends BaseAgent {
clearApprovalPolicyDenialOnProgress(params.turnId, params.item.id);
producedOutputTurnIds.add(params.turnId);
}
- noteActiveToolContext(params.item, params.turnId);
+ completeActiveToolContext(params.item, params.turnId);
// This late item belongs to an already-terminal parent. The parent
// cleanup already cleared its pending tools; touching the shared
// lifecycle set here would re-arm the currently active turn's idle
@@ -9680,6 +9822,7 @@ export class CodexAgent extends BaseAgent {
subagentLiveCards.clear();
dismissAllPendingUserInput('transport_error');
activeToolContexts.clear();
+ completedActiveToolTurns.clear();
capabilitySelectionTextByTurnId.clear();
capabilitySelectionTextByThreadId.clear();
descendantParentThreadByThreadId.clear();
@@ -9968,6 +10111,7 @@ export class CodexAgent extends BaseAgent {
unregisterCodexMcpContext(threadId);
unregisterDescendantCodexMcpContexts();
activeToolContexts.clear();
+ completedActiveToolTurns.clear();
capabilitySelectionTextByTurnId.clear();
capabilitySelectionTextByThreadId.clear();
descendantParentThreadByThreadId.clear();
@@ -10894,12 +11038,117 @@ export class CodexAgent extends BaseAgent {
setAutoReviewIntent(message.content);
},
+ async requestGracefulStop(stopOpts) {
+ const retryState = overloadRetry;
+ if (
+ retryState &&
+ overloadRetryPending(retryState) &&
+ settleStoppedOverloadRetry(
+ retryState,
+ 'graceful stop while an automatic retry was pending',
+ )
+ ) {
+ return;
+ }
+ if (closed || !currentTurnId) throw new Error('No active Codex turn to stop');
+ if (skipIfStaleHost('turn/interrupt')) {
+ throw new Error('Codex host is stale');
+ }
+ const turnId = currentTurnId;
+ const upstreamIdleRemainingAtStop = captureWatchdogRemainingMs(
+ upstreamIdleTimer,
+ upstreamIdleRemainingMs,
+ upstreamIdleSliceStartedAt,
+ );
+ const reconnectRemainingAtStop = reconnectStallTurnId === turnId
+ ? captureWatchdogRemainingMs(
+ reconnectStallTimer,
+ reconnectStallRemainingMs,
+ reconnectStallSliceStartedAt,
+ )
+ : null;
+ const reconnectGenerationAtStop = reconnectStallTurnGeneration;
+ let watchdogActivityVersionAtStop = 0;
+ let watchdogsRestored = false;
+ const restoreWatchdogsIfStillRunning = (): void => {
+ if (
+ watchdogsRestored ||
+ closed ||
+ !isTurnInFlight ||
+ currentTurnId !== turnId ||
+ watchdogActivityVersion !== watchdogActivityVersionAtStop
+ ) {
+ return;
+ }
+ watchdogsRestored = true;
+ if (upstreamIdleRemainingAtStop === null) {
+ // turn/start 已受理但 started 通知尚未到达时可能尚未起表;保留原有失败兜底。
+ armUpstreamIdle();
+ } else {
+ restoreUpstreamIdle(upstreamIdleRemainingAtStop);
+ }
+ if (reconnectRemainingAtStop !== null) {
+ restoreReconnectStall(
+ turnId,
+ reconnectGenerationAtStop,
+ reconnectRemainingAtStop,
+ );
+ }
+ };
+ turnInterruptOrigins.set(turnId, { source: 'user-stop' });
+ dismissAllPending('turn_interrupted', 'deny');
+ dismissPendingUserInputForTurn(turnId, 'turn_interrupted');
+ // dismiss 会同步发布本地 interaction 投影;它不是 provider 进展,不能把刚捕获的
+ // 剩余 deadline 重置为满额。先让这些本地事件收口,再统一清表并锁存活动代次。
+ resetUpstreamIdleForTurnEnd();
+ watchdogActivityVersionAtStop = watchdogActivityVersion;
+ try {
+ const interruptRequest = host.request(Method.TurnInterrupt, { threadId, turnId });
+ await new Promise<void>((resolve, reject) => {
+ const onAbort = () => {
+ cleanup();
+ restoreWatchdogsIfStillRunning();
+ reject(new Error('Codex graceful stop confirmation timed out'));
+ };
+ const cleanup = () => stopOpts?.signal?.removeEventListener('abort', onAbort);
+ if (stopOpts?.signal?.aborted) {
+ onAbort();
+ return;
+ }
+ stopOpts?.signal?.addEventListener('abort', onAbort, { once: true });
+ interruptRequest.then(
+ () => {
+ cleanup();
+ resolve();
+ },
+ (error) => {
+ cleanup();
+ reject(error instanceof Error ? error : new Error(String(error)));
+ },
+ );
+ });
+ } catch (error) {
+ restoreWatchdogsIfStillRunning();
+ if (turnInterruptOrigins.get(turnId)?.source === 'user-stop') {
+ turnInterruptOrigins.delete(turnId);
+ }
+ throw error;
+ }
+ },
+
async abort() {
clearReconnectStall();
// 用户点 Stop = 明确不想继续这一轮,挂起的过载重投必须一起撤掉。
// 放在 currentTurnId 判空之前:重投等待期间 turn 已死、currentTurnId 为
// null,此时正是最需要响应 Stop 的时刻(否则计时器到点又发一个新 turn)。
- const hadPendingRetry = overloadRetryPending();
+ const retryState = overloadRetry;
+ if (
+ retryState &&
+ overloadRetryPending(retryState) &&
+ settleStoppedOverloadRetry(retryState, 'stopped while an automatic retry was pending')
+ ) {
+ return;
+ }
discardOverloadRetry('aborted');
if (closed) return;
if (currentTurnId) {
@@ -10908,41 +11157,6 @@ export class CodexAgent extends BaseAgent {
// notifications cannot re-arm it before turn/completed arrives.
turnInterruptOrigins.set(currentTurnId, { source: 'user-stop' });
}
- // 有挂起重投时的 Stop **必须**由这里显式收口逻辑 turn —— desktop 的
- // SessionTurnActivityTracker 只在收到终态事件后才释放派发闩,Codex
- // coordinator 也刻意等这个事件而不自己解锁,hook runner 同样等到一小时硬
- // 超时才罢休。不发的话会话永久忙、后续消息无法派发(review #844 codex P1)。
- //
- // 两种排序都要覆盖:
- // - 退避等待中: server 侧没有 turn 可 interrupt (currentTurnId 为 null);
- // - 重投的 turnStarted 已先于它的响应到达: currentTurnId 非空, 但**不能**
- // 像普通 Stop 那样把收口交给 turn/completed —— 随后到达的重投响应会走
- // cancelledMidFlight 把同一个 id 落墓碑, handleTurnCompleted 于是把唯一
- // 那条完成事件压掉, 派发闩永远不释放(review #844 codex P1)。这里自己
- // 落墓碑 + interrupt + 推终态, 保证恰好一次收口。
- if (hadPendingRetry) {
- teardownActiveTurnForCancellation('stopped while an automatic retry was pending');
- markInFlightStartsTerminallySettled();
- // turn/start 还在飞时按下 Stop: 这里马上会推终态事件, 而那个 RPC 的响应随后
- // 才回来。不武装隔离的话 handleTurnStartResp 会照常激活它 —— 用户看到
- // 「已停止」, 工具还在跑(review #844 codex P1)。
- quarantineAllInFlightStarts();
- eventQueue.push({
- type: 'error',
- data: {
- message: 'Codex turn stopped while waiting for an automatic retry',
- isTerminal: true,
- reason: 'codex-turn-replay-retry-aborted',
- },
- source: 'codex',
- });
- eventQueue.push({
- type: 'status',
- data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },
- source: 'codex',
- });
- return;
- }
if (!currentTurnId) return;
if (skipIfStaleHost('turn/interrupt')) return;
// 中断已在进行:收 idle 表,别让 watchdog 在收口窗口里再开一次火。
diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.ts
index f75c2ae83e..9aacc5b8d1 100644
--- a/packages/maker-core/src/agents/codex/translator.test.ts
+++ b/packages/maker-core/src/agents/codex/translator.test.ts
@@ -1852,6 +1852,7 @@ describe('translatePlanUpdatedNotification', () => {
expect(events[0].data).toMatchObject({
toolUseId: 'plan:turn-1',
toolName: 'update_plan',
+ runtimeActivity: 'snapshot',
input: {
explanation: 'Working through the implementation.',
plan: [
@@ -1864,6 +1865,7 @@ describe('translatePlanUpdatedNotification', () => {
expect(events[1].data).toMatchObject({
toolUseId: 'plan:turn-1',
toolName: 'update_plan',
+ runtimeActivity: 'snapshot',
input: {
plan: [
{ step: 'Read logs', status: 'completed' },
@@ -1908,6 +1910,7 @@ describe('extractRolloutUpdatePlanFunctionCallEvent', () => {
data: {
toolUseId: 'plan:turn-1',
toolName: 'update_plan',
+ runtimeActivity: 'snapshot',
input: {
plan: [
{ step: 'Read logs', status: 'completed' },
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index 3c8b046ffc..e831838f07 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -643,6 +643,7 @@ export function translatePlanUpdatedNotification(
data: {
toolUseId: `plan:${params.turnId}`,
toolName: 'update_plan',
+ runtimeActivity: 'snapshot',
input: {
...(params.explanation ? { explanation: params.explanation } : {}),
plan: params.plan,
@@ -716,6 +717,7 @@ export function extractRolloutUpdatePlanFunctionCallEvent(
data: {
toolUseId: turnId ? `plan:${turnId}` : `plan-call:${item.call_id ?? 'unknown'}`,
toolName: 'update_plan',
+ runtimeActivity: 'snapshot',
input,
},
source: 'codex',
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
index 3650417f71..04b1e37072 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-startsession-cleanup.test.ts
@@ -30,6 +30,7 @@ const knobs = vi.hoisted(() => ({
onEvent: null as null | ((event: unknown) => void),
spawnedEnvs: [] as Array<Record<string, string | undefined>>,
spawnedArgs: [] as string[][],
+ requests: [] as string[],
}));
vi.mock('../transport.js', () => ({
@@ -71,6 +72,7 @@ vi.mock('../rpc-client.js', () => ({
knobs.onEvent = o?.onEvent ?? null;
}
async request(cmd: { type: string }): Promise<{ success: boolean; data?: unknown; error?: string }> {
+ knobs.requests.push(cmd.type);
if (cmd.type === 'get_state') {
const gate = knobs.getStateGate;
if (gate) await gate;
@@ -126,6 +128,7 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
knobs.onEvent = null;
knobs.spawnedEnvs = [];
knobs.spawnedArgs = [];
+ knobs.requests = [];
disposed = 0;
proxyDisposed = 0;
preparedMcpContext = undefined;
@@ -367,6 +370,18 @@ describe('PiAgent.startSession failure cleanup (mocked pi process)', () => {
expect(proxyDisposed).toBe(1);
});
+ it('graceful stop uses only the Pi abort RPC and keeps the process alive', async () => {
+ const handle = await new PiAgent(buildDeps()).startSession(opts());
+ knobs.onEvent?.({ type: 'message_start' });
+ knobs.requests = [];
+
+ await expect(handle.requestGracefulStop?.()).resolves.toBeUndefined();
+ expect(knobs.requests).toEqual(['abort']);
+ expect(knobs.closeCount).toBe(0);
+
+ await handle.close();
+ });
+
it('keeps local runtime files until a close retry confirms process exit', async () => {
knobs.closeFailuresRemaining = 1;
const handle = await new PiAgent(buildDeps()).startSession(opts());
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index f020145ddb..55f0a7fd5a 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -3198,6 +3198,16 @@ export class PiAgent extends BaseAgent {
}
},
+ async requestGracefulStop(): Promise<void> {
+ if (proc.isClosed) throw new Error('No active Pi turn to stop');
+ dismissAllPendingPrompts('turn_aborted', 'deny');
+ const resp = await proc.request({ type: 'abort' });
+ if (!resp.success) {
+ throw new Error(`Pi graceful stop rejected: ${resp.error ?? 'unknown'}`);
+ }
+ clearActiveTurnPermissionPolicy('turn_aborted');
+ },
+
async abort(): Promise<void> {
if (proc.isClosed) return;
// 先把等待中的调用 fail-closed 唤醒;即使 abort RPC 失败,也不能让用户刚拒绝/
@@ -4003,6 +4013,7 @@ export class PiAgent extends BaseAgent {
const permissionRequest = {
kind: 'permission' as const,
requestId: id,
+ toolUseId: id,
toolName,
input,
...(hostApprovalPresentation?.title
diff --git a/packages/maker-core/src/maker.test.ts b/packages/maker-core/src/maker.test.ts
index b6392f0c8f..2b24cd949f 100644
--- a/packages/maker-core/src/maker.test.ts
+++ b/packages/maker-core/src/maker.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest';
import {
mkdirSync,
mkdtempSync,
+ promises as fsPromises,
realpathSync,
rmSync,
writeFileSync,
@@ -1461,6 +1462,23 @@ describe('Maker Pi runtime skill status', () => {
});
expect(initial.skills[0]).toMatchObject({ runtimeStatus: 'loaded' });
+ const realRealpath = fsPromises.realpath.bind(fsPromises);
+ let delayed = false;
+ vi.spyOn(fsPromises, 'realpath').mockImplementation(async (...args) => {
+ if (!delayed) {
+ delayed = true;
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ }
+ return realRealpath(...args);
+ });
+ const slowFilesystem = await maker.listAgentSkills('pi', {
+ workingDir: repoRoot,
+ sessionId: 'source-snapshot',
+ });
+ expect(delayed).toBe(true);
+ expect(slowFilesystem.skills[0]).toMatchObject({ runtimeStatus: 'loaded' });
+ vi.restoreAllMocks();
+
writeFileSync(path.join(sourcePath, 'assets', 'fixture.txt'), 'changed! asset\n');
const changedAsset = await maker.listAgentSkills('pi', {
workingDir: repoRoot,
@@ -1486,6 +1504,7 @@ describe('Maker Pi runtime skill status', () => {
expect(replacedDirectory.skills[0]).toMatchObject({ runtimeStatus: 'discovered' });
expect(replacedDirectory.errors?.[0]?.message).toContain('restart the session');
} finally {
+ vi.restoreAllMocks();
rmSync(root, { recursive: true, force: true });
}
});
diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.ts
index 9c6444dc2d..8bc615bcba 100644
--- a/packages/maker-core/src/maker.ts
+++ b/packages/maker-core/src/maker.ts
@@ -173,7 +173,12 @@ function canonicalPiRuntimePath(value: string): string {
}
}
-const PI_PROJECT_SKILL_PALETTE_FINGERPRINT_TIMEOUT_MS = 250;
+// Windows realpath/stat calls can legitimately take longer than 250 ms under
+// concurrent CI or endpoint scanning even for a tiny skill tree. Keep the
+// entry budget as the complexity bound, but give the fail-closed fingerprint
+// enough wall-clock time to preserve an unchanged launch snapshot's loaded
+// status across supported platforms.
+const PI_PROJECT_SKILL_PALETTE_FINGERPRINT_TIMEOUT_MS = 1_000;
const PI_PROJECT_SKILL_PALETTE_FINGERPRINT_ENTRY_BUDGET = 2_048;
async function fingerprintPiProjectSkillForPalette(
diff --git a/packages/maker-core/src/session-control.test.ts b/packages/maker-core/src/session-control.test.ts
new file mode 100644
index 0000000000..3a59322a97
--- /dev/null
+++ b/packages/maker-core/src/session-control.test.ts
@@ -0,0 +1,541 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { Session } from './session.js';
+import type { AgentSessionHandle } from './agents/base-agent.js';
+import type {
+ AgentEvent,
+ InteractionDecision,
+ InteractionRequest,
+ InteractionResolver,
+} from './types/events.js';
+
+function createLogger() {
+ const logger = {
+ trace() {},
+ debug() {},
+ info() {},
+ warn: vi.fn(),
+ error() {},
+ fatal() {},
+ child() {
+ return logger;
+ },
+ };
+ return logger;
+}
+
+function createHandle(opts?: {
+ gracefulStop?: (opts?: { signal?: AbortSignal }) => Promise<void>;
+ supported?: boolean;
+}) {
+ let running = false;
+ const pending: AgentEvent[] = [];
+ let notify: (() => void) | null = null;
+ let interactionResolver: InteractionResolver | null = null;
+ async function* events(): AsyncGenerator<AgentEvent> {
+ for (;;) {
+ if (pending.length === 0) {
+ await new Promise<void>((resolve) => {
+ notify = resolve;
+ });
+ }
+ const event = pending.shift();
+ if (event) yield event;
+ }
+ }
+ const requestGracefulStop = vi.fn(opts?.gracefulStop ?? (async () => undefined));
+ const abort = vi.fn(async () => {
+ running = false;
+ });
+ const handle = {
+ id: 'thread-control',
+ agentKind: 'claude-code',
+ model: 'claude-opus-5',
+ events,
+ async send() {
+ running = true;
+ },
+ async steer() {},
+ abort,
+ ...(opts?.supported === false ? {} : { requestGracefulStop }),
+ async close() {
+ running = false;
+ },
+ isTurnRunning: () => running,
+ getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),
+ setInteractionResolver(resolver: InteractionResolver) {
+ interactionResolver = resolver;
+ },
+ } as unknown as AgentSessionHandle;
+ return {
+ handle,
+ requestGracefulStop,
+ abort,
+ push(event: AgentEvent) {
+ if (event.type === 'done' || event.type === 'error') running = false;
+ pending.push(event);
+ notify?.();
+ notify = null;
+ },
+ requestInteraction(request: InteractionRequest): Promise<InteractionDecision> {
+ if (!interactionResolver) throw new Error('interaction resolver not installed');
+ return interactionResolver(request);
+ },
+ };
+}
+
+function createSession(stub: ReturnType<typeof createHandle>): Session {
+ return new Session({
+ id: 'session-control',
+ agentKind: 'claude-code',
+ workDir: '/repo',
+ handle: stub.handle,
+ capabilities: {} as never,
+ logger: createLogger() as never,
+ turnStallMs: 0,
+ });
+}
+
+function waitForSessionEvent(session: Session, type: AgentEvent['type']): Promise<void> {
+ return new Promise((resolve) => {
+ const unsubscribe = session.onEvent((event) => {
+ if (event.type !== type) return;
+ unsubscribe();
+ resolve();
+ });
+ });
+}
+
+describe('Session graceful-stop control state', () => {
+ it('cancels and joins a pre-acceptance send reservation before reporting stop requested', async () => {
+ const stub = createHandle();
+ let running = false;
+ let sendSignal: AbortSignal | undefined;
+ let releaseConversion!: () => void;
+ let markSendStarted!: () => void;
+ const sendStarted = new Promise<void>((resolve) => { markSendStarted = resolve; });
+ const conversion = new Promise<void>((resolve) => { releaseConversion = resolve; });
+ stub.handle.send = vi.fn(async (_message, opts) => {
+ running = true;
+ sendSignal = opts?.signal;
+ markSendStarted();
+ await conversion;
+ if (opts?.signal?.aborted) {
+ running = false;
+ throw new Error('provider input cancelled before acceptance');
+ }
+ });
+ stub.handle.isTurnRunning = () => running;
+ const session = createSession(stub);
+
+ const send = session.send('slow attachment');
+ await sendStarted;
+ const firstStop = session.requestGracefulStop();
+ const secondStop = session.requestGracefulStop();
+
+ expect(sendSignal?.aborted).toBe(true);
+ expect(stub.requestGracefulStop).not.toHaveBeenCalled();
+ releaseConversion();
+
+ await expect(send).resolves.toEqual({ accepted: false, reason: 'cancelled-before-dispatch' });
+ await expect(Promise.all([firstStop, secondStop])).resolves.toEqual([
+ { status: 'requested', turnGeneration: 1 },
+ { status: 'requested', turnGeneration: 1 },
+ ]);
+ expect(stub.requestGracefulStop).not.toHaveBeenCalled();
+ expect(session.getTurnControlSnapshot().active).toBe(false);
+ });
+
+ it('falls through to the provider soft interrupt when acceptance wins the reservation race', async () => {
+ const stub = createHandle();
+ let running = false;
+ let releaseAcceptance!: () => void;
+ let markSendStarted!: () => void;
+ const sendStarted = new Promise<void>((resolve) => { markSendStarted = resolve; });
+ const acceptance = new Promise<void>((resolve) => { releaseAcceptance = resolve; });
+ stub.handle.send = vi.fn(async () => {
+ running = true;
+ markSendStarted();
+ await acceptance;
+ });
+ stub.handle.isTurnRunning = () => running;
+ const session = createSession(stub);
+
+ const send = session.send('accept while stop races');
+ await sendStarted;
+ const stop = session.requestGracefulStop();
+ releaseAcceptance();
+
+ await expect(send).resolves.toEqual({ accepted: true });
+ await expect(stop).resolves.toEqual({ status: 'requested', turnGeneration: 1 });
+ expect(stub.requestGracefulStop).toHaveBeenCalledOnce();
+ expect(stub.abort).not.toHaveBeenCalled();
+ });
+
+ it('reports an unconfirmed stop when a cancelled reservation never settles', async () => {
+ vi.useFakeTimers();
+ try {
+ const stub = createHandle();
+ let running = false;
+ let releaseAcceptance!: () => void;
+ let markSendStarted!: () => void;
+ let sendSignal: AbortSignal | undefined;
+ const sendStarted = new Promise<void>((resolve) => { markSendStarted = resolve; });
+ const acceptance = new Promise<void>((resolve) => { releaseAcceptance = resolve; });
+ stub.handle.send = vi.fn(async (_message, opts) => {
+ running = true;
+ sendSignal = opts?.signal;
+ markSendStarted();
+ await acceptance;
+ if (opts?.signal?.aborted) {
+ running = false;
+ throw new Error('provider input cancelled before acceptance');
+ }
+ });
+ stub.handle.isTurnRunning = () => running;
+ const session = createSession(stub);
+
+ const send = session.send('hung acceptance');
+ await sendStarted;
+ const stop = session.requestGracefulStop();
+ await vi.advanceTimersByTimeAsync(5_000);
+
+ await expect(stop).resolves.toEqual({
+ status: 'unconfirmed',
+ turnGeneration: 1,
+ reason: 'provider-acceptance-timeout',
+ });
+ expect(sendSignal?.aborted).toBe(true);
+ expect(stub.requestGracefulStop).not.toHaveBeenCalled();
+
+ releaseAcceptance();
+ await expect(send).resolves.toEqual({ accepted: false, reason: 'cancelled-before-dispatch' });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('tracks only stop-control facts and clears them at terminal', async () => {
+ const stub = createHandle();
+ const session = createSession(stub);
+
+ expect(session.getTurnControlSnapshot()).toEqual({
+ active: false,
+ turnGeneration: null,
+ activeToolCount: 0,
+ pendingInteractionCount: 0,
+ gracefulStopState: 'none',
+ });
+
+ await session.send('start');
+ expect(session.getTurnControlSnapshot()).toEqual({
+ active: true,
+ turnGeneration: 1,
+ activeToolCount: 0,
+ pendingInteractionCount: 0,
+ gracefulStopState: 'none',
+ });
+
+ const toolObserved = waitForSessionEvent(session, 'tool_use');
+ stub.push({
+ type: 'tool_use',
+ data: {
+ toolUseId: 'tool-1',
+ toolName: `Bash\n${'x'.repeat(100)}`,
+ input: { command: 'secret-token-value' },
+ },
+ });
+ await toolObserved;
+ expect(session.getTurnControlSnapshot()).toMatchObject({ activeToolCount: 1 });
+ expect(JSON.stringify(session.getTurnControlSnapshot())).not.toContain('secret-token-value');
+
+ const doneObserved = waitForSessionEvent(session, 'done');
+ stub.push({ type: 'done', data: {} });
+ await doneObserved;
+ expect(session.getTurnControlSnapshot().active).toBe(false);
+ });
+
+ it('waits for every active tool result before issuing one soft stop request', async () => {
+ const stub = createHandle();
+ const session = createSession(stub);
+ await session.send('start');
+ stub.push({ type: 'tool_use', data: { toolUseId: 'tool-1', toolName: 'Read' } });
+ stub.push({ type: 'tool_use', data: { toolUseId: 'tool-2', toolName: 'Write' } });
+ await vi.waitFor(() => expect(session.getTurnControlSnapshot().activeToolCount).toBe(2));
+
+ await expect(session.requestGracefulStop()).resolves.toEqual({
+ status: 'waiting-for-safe-point',
+ turnGeneration: 1,
+ });
+ expect(stub.requestGracefulStop).not.toHaveBeenCalled();
+
+ stub.push({ type: 'tool_result_full', data: { toolUseId: 'tool-1', fullText: 'done' } });
+ await vi.waitFor(() => expect(session.getTurnControlSnapshot().activeToolCount).toBe(1));
+ expect(stub.requestGracefulStop).not.toHaveBeenCalled();
+
+ stub.push({ type: 'tool_result', data: { toolUseIds: ['tool-2'], summary: 'done' } });
+ await vi.waitFor(() => expect(stub.requestGracefulStop).toHaveBeenCalledTimes(1));
+ await vi.waitFor(() => {
+ expect(session.getTurnControlSnapshot().gracefulStopState).toBe('requested');
+ });
+ await expect(session.requestGracefulStop()).resolves.toEqual({
+ status: 'requested',
+ turnGeneration: 1,
+ });
+ expect(stub.abort).not.toHaveBeenCalled();
+ });
+
+ it('does not count display-only plan snapshots as active tools', async () => {
+ const snapshotStub = createHandle();
+ const snapshotSession = createSession(snapshotStub);
+ await snapshotSession.send('start');
+ const snapshotObserved = waitForSessionEvent(snapshotSession, 'tool_use');
+ snapshotStub.push({
+ type: 'tool_use',
+ data: {
+ toolUseId: 'plan:turn-1',
+ toolName: 'update_plan',
+ runtimeActivity: 'snapshot',
+ },
+ });
+ await snapshotObserved;
+ expect(snapshotSession.getTurnControlSnapshot().activeToolCount).toBe(0);
+
+ await expect(snapshotSession.requestGracefulStop()).resolves.toEqual({
+ status: 'requested',
+ turnGeneration: 1,
+ });
+ expect(snapshotStub.requestGracefulStop).toHaveBeenCalledOnce();
+
+ const toolStub = createHandle();
+ const toolSession = createSession(toolStub);
+ await toolSession.send('start');
+ toolStub.push({
+ type: 'tool_use',
+ data: { toolUseId: 'plan-call-1', toolName: 'update_plan' },
+ });
+ await vi.waitFor(() => expect(toolSession.getTurnControlSnapshot().activeToolCount).toBe(1));
+
+ await expect(toolSession.requestGracefulStop()).resolves.toEqual({
+ status: 'waiting-for-safe-point',
+ turnGeneration: 1,
+ });
+ expect(toolStub.requestGracefulStop).not.toHaveBeenCalled();
+
+ toolStub.push({
+ type: 'tool_result',
+ data: { toolUseIds: ['plan-call-1'], summary: 'done' },
+ });
+ await vi.waitFor(() => expect(toolStub.requestGracefulStop).toHaveBeenCalledOnce());
+ });
+
+ it('treats a pending interaction as a safe stop boundary and exposes it in runtime state', async () => {
+ const stub = createHandle();
+ const session = createSession(stub);
+ const settleInteractions: Array<(decision: InteractionDecision) => void> = [];
+ session.setInteractionListener(
+ () =>
+ new Promise<InteractionDecision>((resolve) => {
+ settleInteractions.push(resolve);
+ }),
+ );
+ await session.send('start');
+ stub.push({ type: 'tool_use', data: { toolUseId: 'tool-1', toolName: 'Bash' } });
+ await vi.waitFor(() => expect(session.getTurnControlSnapshot().activeToolCount).toBe(1));
+
+ const firstInteraction = stub.requestInteraction({
+ kind: 'permission',
+ requestId: 'approval-1',
+ toolUseId: 'tool-1',
+ toolName: 'Bash',
+ input: { command: 'echo safe' },
+ });
+ const secondInteraction = stub.requestInteraction({
+ kind: 'permission',
+ requestId: 'approval-2',
+ toolUseId: 'tool-1',
+ toolName: 'Bash',
+ input: { command: 'echo safe again' },
+ });
+ await vi.waitFor(() => {
+ expect(session.getTurnControlSnapshot().pendingInteractionCount).toBe(2);
+ expect(settleInteractions).toHaveLength(2);
+ });
+
+ settleInteractions[0]?.({
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'first approval settled',
+ });
+ await firstInteraction;
+
+ await expect(session.requestGracefulStop()).resolves.toEqual({
+ status: 'requested',
+ turnGeneration: 1,
+ });
+ expect(stub.requestGracefulStop).toHaveBeenCalledOnce();
+ expect(stub.abort).not.toHaveBeenCalled();
+
+ settleInteractions[1]?.({
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'graceful stop',
+ });
+ await secondInteraction;
+ });
+
+ it('waits for a parallel running tool even when another tool is awaiting permission', async () => {
+ const stub = createHandle();
+ const session = createSession(stub);
+ let settleInteraction!: (decision: InteractionDecision) => void;
+ session.setInteractionListener(
+ () =>
+ new Promise<InteractionDecision>((resolve) => {
+ settleInteraction = resolve;
+ }),
+ );
+ await session.send('start');
+ stub.push({ type: 'tool_use', data: { toolUseId: 'tool-waiting', toolName: 'Write' } });
+ stub.push({ type: 'tool_use', data: { toolUseId: 'tool-running', toolName: 'Bash' } });
+ await vi.waitFor(() => expect(session.getTurnControlSnapshot().activeToolCount).toBe(2));
+
+ const interaction = stub.requestInteraction({
+ kind: 'permission',
+ requestId: 'approval-waiting',
+ toolUseId: 'tool-waiting',
+ toolName: 'Write',
+ input: { file_path: '/repo/result.txt' },
+ });
+ await vi.waitFor(() => {
+ expect(session.getTurnControlSnapshot().pendingInteractionCount).toBe(1);
+ });
+
+ await expect(session.requestGracefulStop()).resolves.toEqual({
+ status: 'waiting-for-safe-point',
+ turnGeneration: 1,
+ });
+ expect(stub.requestGracefulStop).not.toHaveBeenCalled();
+
+ stub.push({
+ type: 'tool_result_full',
+ data: { toolUseId: 'tool-running', fullText: 'done' },
+ });
+ await vi.waitFor(() => expect(stub.requestGracefulStop).toHaveBeenCalledOnce());
+
+ settleInteraction({
+ kind: 'permission',
+ behavior: 'deny',
+ reason: 'graceful stop',
+ });
+ await interaction;
+ });
+
+ it('does not treat a missing or unrelated interaction tool id as a safe stop boundary', async () => {
+ const stub = createHandle();
+ const session = createSession(stub);
+ const pendingInteractions: Array<Promise<InteractionDecision>> = [];
+ session.setInteractionListener(
+ () => new Promise<InteractionDecision>(() => undefined),
+ );
+ await session.send('start');
+ stub.push({ type: 'tool_use', data: { toolUseId: 'tool-running', toolName: 'Bash' } });
+ await vi.waitFor(() => expect(session.getTurnControlSnapshot().activeToolCount).toBe(1));
+
+ pendingInteractions.push(stub.requestInteraction({
+ kind: 'permission',
+ requestId: 'tool-running',
+ toolName: 'Bash',
+ input: {},
+ }));
+ pendingInteractions.push(stub.requestInteraction({
+ kind: 'permission',
+ requestId: 'approval-other',
+ toolUseId: 'tool-other',
+ toolName: 'Write',
+ input: {},
+ }));
+ await vi.waitFor(() => {
+ expect(session.getTurnControlSnapshot().pendingInteractionCount).toBe(1);
+ });
+
+ await expect(session.requestGracefulStop()).resolves.toEqual({
+ status: 'waiting-for-safe-point',
+ turnGeneration: 1,
+ });
+ expect(stub.requestGracefulStop).not.toHaveBeenCalled();
+
+ // Keep the deliberately hanging interaction promises referenced until the assertion completes.
+ expect(pendingInteractions).toHaveLength(2);
+ });
+
+ it('reports unsupported, no-active-turn and provider failure without falling back to abort', async () => {
+ const unsupported = createSession(createHandle({ supported: false }));
+ await unsupported.send('start');
+ await expect(unsupported.requestGracefulStop()).resolves.toEqual({
+ status: 'unsupported',
+ reason: 'provider-not-supported',
+ });
+
+ const idleStub = createHandle();
+ const idle = createSession(idleStub);
+ await expect(idle.requestGracefulStop()).resolves.toEqual({ status: 'no-active-turn' });
+
+ const failedStub = createHandle({
+ gracefulStop: async () => {
+ throw new Error('soft interrupt unavailable');
+ },
+ });
+ const failed = createSession(failedStub);
+ await failed.send('start');
+ await expect(failed.requestGracefulStop()).resolves.toEqual({
+ status: 'unconfirmed',
+ turnGeneration: 1,
+ reason: 'provider-request-failed',
+ });
+ expect(failedStub.abort).not.toHaveBeenCalled();
+ });
+
+ it('bounds a hanging provider stop request and reports it as unconfirmed', async () => {
+ vi.useFakeTimers();
+ try {
+ let providerSignal: AbortSignal | undefined;
+ const stub = createHandle({
+ gracefulStop: (opts) => {
+ providerSignal = opts?.signal;
+ return new Promise<void>(() => undefined);
+ },
+ });
+ const session = createSession(stub);
+ await session.send('start');
+
+ const result = session.requestGracefulStop();
+ await vi.advanceTimersByTimeAsync(5_000);
+
+ await expect(result).resolves.toEqual({
+ status: 'unconfirmed',
+ turnGeneration: 1,
+ reason: 'provider-confirmation-timeout',
+ });
+ expect(stub.abort).not.toHaveBeenCalled();
+ expect(providerSignal?.aborted).toBe(true);
+ expect(session.getTurnControlSnapshot().gracefulStopState).toBe('unconfirmed');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('drops a stop waiting at a tool boundary when that generation terminates', async () => {
+ const stub = createHandle();
+ const session = createSession(stub);
+ await session.send('start');
+ stub.push({ type: 'tool_use', data: { toolUseId: 'tool-old', toolName: 'Bash' } });
+ await vi.waitFor(() => expect(session.getTurnControlSnapshot().activeToolCount).toBe(1));
+ await expect(session.requestGracefulStop()).resolves.toMatchObject({
+ status: 'waiting-for-safe-point',
+ });
+
+ stub.push({ type: 'done', data: {} });
+ await vi.waitFor(() => expect(session.getTurnControlSnapshot().active).toBe(false));
+ expect(stub.requestGracefulStop).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index 969137a0fb..0a7f24c300 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -16,6 +16,8 @@ import {
extractNonSecretErrorSignals,
redactSensitiveText,
} from '@cindy/maker-shared/error-redaction';
+import type { SessionGracefulStopState } from '@cindy/maker-shared/session-activity';
+export type { SessionGracefulStopState } from '@cindy/maker-shared/session-activity';
import type {
Effort,
PermissionMode,
@@ -113,6 +115,9 @@ export const STALL_ABORT_RECOVERY_GRACE_MS = 10_000;
*/
export const MANUAL_ABORT_RECOVERY_GRACE_MS = 15_000;
+/** Shared confirmation budget for provider interrupt ACK and send acceptance. */
+const GRACEFUL_STOP_CONFIRMATION_TIMEOUT_MS = 5_000;
+
/**
* turn 零事件看门狗的计时分片长度。额度按片累加,片尾核对真实经过时间,
* 借此把系统挂起(合盖睡眠)的那段排除掉 —— 见 armTurnStallSlice。
@@ -322,12 +327,58 @@ export type SessionSendResult =
reason: 'cancelled-before-dispatch' | 'provider-rejected-before-dispatch';
};
+export interface SessionTurnControlSnapshot {
+ active: boolean;
+ turnGeneration: number | null;
+ activeToolCount: number;
+ pendingInteractionCount: number;
+ gracefulStopState: SessionGracefulStopState;
+}
+
+export type SessionGracefulStopResult =
+ | { status: 'no-active-turn' }
+ | { status: 'unsupported'; reason: 'provider-not-supported' }
+ | { status: 'waiting-for-safe-point'; turnGeneration: number }
+ | { status: 'requested'; turnGeneration: number }
+ | { status: 'unconfirmed'; turnGeneration: number; reason: string };
+
+type TurnControlState = {
+ generation: number;
+ activeToolIds: Set<string>;
+ anonymousActiveTools: number;
+ pendingInteractionToolIds: Map<string, number>;
+ gracefulStopState: SessionGracefulStopState;
+ gracefulStopPromise: Promise<SessionGracefulStopResult> | null;
+};
+
type SendReservation = {
+ generation: number;
phase: 'accepting' | 'dispatching';
cancelled: boolean;
abortController: AbortController;
+ settled: Promise<SendReservationOutcome>;
+ settle(outcome: SendReservationOutcome): void;
+ gracefulStopPromise: Promise<SessionGracefulStopResult> | null;
};
+type SendReservationOutcome = 'accepted' | 'undispatched' | 'unconfirmed';
+
+function createSendReservation(generation: number): SendReservation {
+ let resolveSettled!: (outcome: SendReservationOutcome) => void;
+ const settled = new Promise<SendReservationOutcome>((resolve) => {
+ resolveSettled = resolve;
+ });
+ return {
+ generation,
+ phase: 'accepting',
+ cancelled: false,
+ abortController: new AbortController(),
+ settled,
+ settle: resolveSettled,
+ gracefulStopPromise: null,
+ };
+}
+
export class Session {
readonly id: string;
/** business id 可复用;instanceId 精确标识本次内存 Session incarnation。 */
@@ -405,6 +456,8 @@ export class Session {
/** 已为哪个 turn 代号排过 abort 复核;同一 turn 上重复 abort 不重复排。 */
private abortRecoveryScheduledFor: number | null = null;
private lastEventType: string | null = null;
+ /** 优雅停止所需的 turn 控制事实;不承担 UI/MCP 会话状态投影。 */
+ private turnControlState: TurnControlState | null = null;
constructor(opts: SessionOptions) {
this.id = opts.id;
@@ -429,6 +482,7 @@ export class Session {
// 等用户回应期间挂起 stall 看门狗:用户可能离开电脑很久,没有事件是正常的,
// 中断这种 turn 等于把"等你决定"误判成"卡死"(见 DEFAULT_TURN_STALL_MS)。
this.pendingInteractions += 1;
+ const interactionRuntime = this.observeInteractionStarted(req);
this.clearTurnStallWatchdog();
try {
if (!this.interactionListener) {
@@ -444,6 +498,7 @@ export class Session {
return await this.interactionListener(req);
} finally {
this.pendingInteractions = Math.max(0, this.pendingInteractions - 1);
+ this.observeInteractionSettled(interactionRuntime);
this.armTurnStallWatchdog();
}
});
@@ -510,23 +565,20 @@ export class Session {
if (this.sendReservation !== null) {
throw this.createSessionRunningError();
}
- const reservation: SendReservation = {
- phase: 'accepting',
- cancelled: false,
- abortController: new AbortController(),
- };
- this.sendReservation = reservation;
// 新一轮 turn 的代号(见 turnGeneration):看门狗的善后动作据此判断"还是不是那个
// 卡死的 turn",避免误杀宽限期内新起的健康 turn。
const previousTurnGeneration = this.turnGeneration;
this.turnGeneration += 1;
const reservedTurnGeneration = this.turnGeneration;
+ const reservation = createSendReservation(reservedTurnGeneration);
+ this.sendReservation = reservation;
const cleanupExternalAbort = this.attachExternalCancellation(reservation, handleOpts.signal);
// originInstalled:已越过 dispatch 边界、把本次 origin 装进 currentTurnOrigin。
// turnDispatched:handle.send 成功、本次 send 真正成为运行中的 turn。
let originInstalled = false;
let turnDispatched = false;
let dispatchConfirmedUndispatched = false;
+ let dispatchUnconfirmed = false;
let previousTurnOrigin: SendOrigin | null = null;
let previousTurnAttemptToken: number | null = null;
const turnLifecycleObserver = this.turnLifecycleObserver;
@@ -597,6 +649,7 @@ export class Session {
originInstalled = true;
this.startEventLoopIfNeeded();
try {
+ this.beginTurnControl(reservedTurnGeneration);
onDispatching?.();
await this.handle.send(msg, {
...handleOpts,
@@ -637,6 +690,7 @@ export class Session {
this.sendReservation = null;
}
if (e instanceof TurnDispatchUnconfirmedError) {
+ dispatchUnconfirmed = true;
// Reserve Session shutdown before closing the handle. This suppresses
// a synthetic terminal event from transport teardown and fences any
// late provider activity before the orchestrator reports blocked.
@@ -685,6 +739,10 @@ export class Session {
});
}
}
+ if (!turnDispatched) this.clearTurnControl(reservedTurnGeneration);
+ reservation.settle(
+ turnDispatched ? 'accepted' : dispatchUnconfirmed ? 'unconfirmed' : 'undispatched',
+ );
}
}
@@ -772,6 +830,130 @@ export class Session {
}
}
+ getTurnControlSnapshot(): SessionTurnControlSnapshot {
+ const control = this.turnControlState;
+ if (!control) {
+ return {
+ active: false,
+ turnGeneration: null,
+ activeToolCount: 0,
+ pendingInteractionCount: 0,
+ gracefulStopState: 'none',
+ };
+ }
+ return {
+ active: true,
+ turnGeneration: control.generation,
+ activeToolCount: control.activeToolIds.size + control.anonymousActiveTools,
+ pendingInteractionCount: [...control.pendingInteractionToolIds.values()]
+ .reduce((sum, count) => sum + count, 0),
+ gracefulStopState: control.gracefulStopState,
+ };
+ }
+
+ async requestGracefulStop(): Promise<SessionGracefulStopResult> {
+ const reservation = this.sendReservation;
+ if (reservation) return this.requestGracefulStopForReservation(reservation);
+ const control = this.turnControlState;
+ if (!control || control.generation !== this.turnGeneration || !this.isHandleTurnRunning()) {
+ return { status: 'no-active-turn' };
+ }
+ if (!this.handle.requestGracefulStop) {
+ return { status: 'unsupported', reason: 'provider-not-supported' };
+ }
+ if (control.gracefulStopPromise) return control.gracefulStopPromise;
+ if (control.gracefulStopState === 'requested') {
+ return { status: 'requested', turnGeneration: control.generation };
+ }
+ if (control.gracefulStopState === 'unconfirmed') {
+ return {
+ status: 'unconfirmed',
+ turnGeneration: control.generation,
+ reason: 'provider-did-not-confirm',
+ };
+ }
+ if (!this.isGracefulStopSafePoint(control)) {
+ control.gracefulStopState = 'waiting-for-safe-point';
+ return { status: 'waiting-for-safe-point', turnGeneration: control.generation };
+ }
+ return this.issueGracefulStop(control);
+ }
+
+ /** Fence a graceful stop against input that the provider has not accepted yet. */
+ private requestGracefulStopForReservation(
+ reservation: SendReservation,
+ ): Promise<SessionGracefulStopResult> {
+ if (reservation.gracefulStopPromise) return reservation.gracefulStopPromise;
+ this.cancelSendReservation(reservation);
+ const control = this.turnControlState;
+ if (control?.generation === reservation.generation) control.gracefulStopState = 'requesting';
+
+ const result = this.waitForSendReservationSettlement(reservation).then(async (outcome) => {
+ const currentControl = this.turnControlState;
+ if (outcome === 'undispatched') {
+ if (currentControl?.generation === reservation.generation) {
+ currentControl.gracefulStopState = 'requested';
+ }
+ return { status: 'requested', turnGeneration: reservation.generation } as const;
+ }
+ if (outcome === 'unconfirmed' || outcome === 'timeout') {
+ if (currentControl?.generation === reservation.generation) {
+ currentControl.gracefulStopState = 'unconfirmed';
+ }
+ return {
+ status: 'unconfirmed',
+ turnGeneration: reservation.generation,
+ reason: outcome === 'timeout'
+ ? 'provider-acceptance-timeout'
+ : 'provider-acceptance-unconfirmed',
+ } as const;
+ }
+
+ // The provider accepted while cancellation raced; only its own soft-interrupt ACK can
+ // confirm the stop from this point onward.
+ if (
+ !currentControl ||
+ currentControl.generation !== reservation.generation ||
+ !this.isHandleTurnRunning()
+ ) {
+ return { status: 'requested', turnGeneration: reservation.generation } as const;
+ }
+ if (!this.handle.requestGracefulStop) {
+ return { status: 'unsupported', reason: 'provider-not-supported' } as const;
+ }
+ if (!this.isGracefulStopSafePoint(currentControl)) {
+ currentControl.gracefulStopState = 'waiting-for-safe-point';
+ return {
+ status: 'waiting-for-safe-point',
+ turnGeneration: currentControl.generation,
+ } as const;
+ }
+ return this.issueGracefulStop(currentControl);
+ });
+ reservation.gracefulStopPromise = result;
+ return result;
+ }
+
+ private waitForSendReservationSettlement(
+ reservation: SendReservation,
+ ): Promise<SendReservationOutcome | 'timeout'> {
+ return new Promise((resolve) => {
+ let settled = false;
+ const timeout = setTimeout(() => {
+ if (settled) return;
+ settled = true;
+ resolve('timeout');
+ }, GRACEFUL_STOP_CONFIRMATION_TIMEOUT_MS);
+ (timeout as unknown as { unref?: () => void }).unref?.();
+ void reservation.settled.then((outcome) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timeout);
+ resolve(outcome);
+ });
+ });
+ }
+
/**
* 停止本会话内单个后台任务(run_in_background 的 Bash / 后台 subagent 等)。
* 与 abort() 不同:不中断当前 turn,只停指定 taskId;任务已到终态时幂等成功。
@@ -848,6 +1030,7 @@ export class Session {
this.sendReservation = null;
this.currentTurnOrigin = null;
this.currentTurnAttemptToken = null;
+ this.turnControlState = null;
this.eventListeners.clear();
this.interactionListener = null;
if (closeSucceeded) {
@@ -881,6 +1064,7 @@ export class Session {
this.sendReservation = null;
this.currentTurnOrigin = null;
this.currentTurnAttemptToken = null;
+ this.turnControlState = null;
this.clearTerminalErrorDrain();
this.eventListeners.clear();
this.interactionListener = null;
@@ -1367,6 +1551,154 @@ export class Session {
void this.runEventLoop();
}
+ private beginTurnControl(generation: number): void {
+ this.turnControlState = {
+ generation,
+ activeToolIds: new Set(),
+ anonymousActiveTools: 0,
+ pendingInteractionToolIds: new Map(),
+ gracefulStopState: 'none',
+ gracefulStopPromise: null,
+ };
+ }
+
+ private clearTurnControl(generation: number): void {
+ if (this.turnControlState?.generation === generation) this.turnControlState = null;
+ }
+
+ /**
+ * Provider 的权限/提问/计划确认会直接经过 InteractionResolver,不保证另发
+ * interaction_request event。这里从权威入口更新探针,并把“尚未执行、正在等用户”
+ * 视为优雅停止安全点,避免 stop 永久等不到该工具的 result。
+ */
+ private observeInteractionStarted(
+ request: InteractionRequest,
+ ): { control: TurnControlState; toolUseId: string | null } | null {
+ const control = this.turnControlState;
+ if (!control || control.generation !== this.turnGeneration) return null;
+ const toolUseId = request.toolUseId?.trim() || null;
+ if (toolUseId) {
+ control.pendingInteractionToolIds.set(
+ toolUseId,
+ (control.pendingInteractionToolIds.get(toolUseId) ?? 0) + 1,
+ );
+ }
+ if (
+ control.gracefulStopState === 'waiting-for-safe-point' &&
+ this.isGracefulStopSafePoint(control)
+ ) {
+ void this.issueGracefulStop(control);
+ }
+ return { control, toolUseId };
+ }
+
+ private observeInteractionSettled(
+ observation: { control: TurnControlState; toolUseId: string | null } | null,
+ ): void {
+ if (!observation || this.turnControlState !== observation.control) return;
+ const { control, toolUseId } = observation;
+ if (toolUseId) {
+ const remaining = (control.pendingInteractionToolIds.get(toolUseId) ?? 0) - 1;
+ if (remaining > 0) control.pendingInteractionToolIds.set(toolUseId, remaining);
+ else control.pendingInteractionToolIds.delete(toolUseId);
+ }
+ }
+
+ private isGracefulStopSafePoint(control: TurnControlState): boolean {
+ if (control.anonymousActiveTools > 0) return false;
+ return (
+ control.activeToolIds.size === 0 ||
+ [...control.activeToolIds].every((id) => control.pendingInteractionToolIds.has(id))
+ );
+ }
+
+ private issueGracefulStop(control: TurnControlState): Promise<SessionGracefulStopResult> {
+ if (control.gracefulStopPromise) return control.gracefulStopPromise;
+ control.gracefulStopState = 'requesting';
+ const abortController = new AbortController();
+ const request = Promise.resolve().then(() =>
+ this.handle.requestGracefulStop!({ signal: abortController.signal }),
+ );
+ const result = new Promise<SessionGracefulStopResult>((resolve) => {
+ let settled = false;
+ const timeout = setTimeout(() => {
+ settled = true;
+ abortController.abort();
+ if (this.turnControlState === control) control.gracefulStopState = 'unconfirmed';
+ resolve({
+ status: 'unconfirmed',
+ turnGeneration: control.generation,
+ reason: 'provider-confirmation-timeout',
+ });
+ }, GRACEFUL_STOP_CONFIRMATION_TIMEOUT_MS);
+ (timeout as unknown as { unref?: () => void }).unref?.();
+ void request.then(
+ () => {
+ clearTimeout(timeout);
+ if (settled) return;
+ settled = true;
+ if (this.turnControlState === control) control.gracefulStopState = 'requested';
+ resolve({ status: 'requested', turnGeneration: control.generation });
+ },
+ (error) => {
+ clearTimeout(timeout);
+ if (settled) return;
+ settled = true;
+ if (this.turnControlState === control) control.gracefulStopState = 'unconfirmed';
+ this.logger.warn('graceful stop request failed', {
+ turnGeneration: control.generation,
+ error: String(error),
+ });
+ resolve({
+ status: 'unconfirmed',
+ turnGeneration: control.generation,
+ reason: 'provider-request-failed',
+ });
+ },
+ );
+ });
+ control.gracefulStopPromise = result;
+ return result;
+ }
+
+ private observeTurnControl(event: AgentEvent, observedGeneration: number): void {
+ const control = this.turnControlState;
+ if (!control || control.generation !== observedGeneration || event.turnScope === 'background') return;
+ const data = event.data && typeof event.data === 'object'
+ ? event.data as Record<string, unknown>
+ : {};
+ if (event.type === 'tool_use') {
+ const toolUseId = typeof data.toolUseId === 'string' ? data.toolUseId : null;
+ // Some providers expose display-only tool-shaped snapshots (for example,
+ // Codex native plan updates). They have no matching tool_result and must
+ // not occupy the graceful-stop safe-point lifecycle.
+ if (data.runtimeActivity === 'snapshot') {
+ return;
+ }
+ if (toolUseId) control.activeToolIds.add(toolUseId);
+ else control.anonymousActiveTools += 1;
+ return;
+ }
+ if (event.type === 'tool_result_full' || event.type === 'tool_result') {
+ const ids = [
+ ...(typeof data.toolUseId === 'string' ? [data.toolUseId] : []),
+ ...(Array.isArray(data.toolUseIds)
+ ? data.toolUseIds.filter((id): id is string => typeof id === 'string')
+ : []),
+ ];
+ for (const id of ids) control.activeToolIds.delete(id);
+ if (ids.length === 0 && control.anonymousActiveTools > 0) {
+ control.anonymousActiveTools -= 1;
+ }
+ if (
+ this.isGracefulStopSafePoint(control) &&
+ control.gracefulStopState === 'waiting-for-safe-point'
+ ) {
+ void this.issueGracefulStop(control);
+ }
+ }
+ }
+
/**
* 事件 fan-out 的唯一出口(真实事件与看门狗合成的事件共用)。三件事都收在这里,
* 保证两条来路语义一致 —— origin 打标、订阅者分发、stall 看门狗记账。
@@ -1381,6 +1713,7 @@ export class Session {
if (!isBackgroundEvent) this.lastEventAt = Date.now();
this.lastEventType = event.type;
const isCurrentGeneration = observedGeneration === this.turnGeneration;
+ this.observeTurnControl(event, observedGeneration);
// fan-out 前打 turn origin(所有 listener 拿到同一份);事件对象由 translator
// 每次新建、看门狗每次合成,不会串台。=== undefined 守卫:不覆盖 agent 自带的。
if (!isBackgroundEvent && isCurrentGeneration && this.currentTurnOrigin && event.turnOrigin === undefined) {
@@ -1434,6 +1767,9 @@ export class Session {
this.clearTerminalErrorDrain();
}
const listenerEvent = redactEventForListeners(event);
+ if (isCurrentGeneration && isTerminal && !isBackgroundEvent) {
+ this.clearTurnControl(observedGeneration);
+ }
if (isTerminal && !isBackgroundEvent) {
try {
const pending = this.turnLifecycleObserver?.onTerminal({
@@ -1821,6 +2157,7 @@ export class Session {
this.sendReservation = null;
this.currentTurnOrigin = null;
this.currentTurnAttemptToken = null;
+ this.turnControlState = null;
this.setStatus('closed');
this.eventListeners.clear();
this.statusListeners.clear();
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index e4385d36a8..777ac2ae64 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -217,10 +217,15 @@ export interface AskUserQuestionItem {
multiSelect?: boolean;
}
+type InteractionRequestBase = {
+ requestId: string;
+ /** Provider tool/item id that owns this interaction; distinct from transport request ids. */
+ toolUseId?: string;
+};
+
export type InteractionRequest =
- | {
+ | (InteractionRequestBase & {
kind: 'permission';
- requestId: string;
toolName: string;
input: Record<string, unknown>;
title?: string;
@@ -228,18 +233,16 @@ export type InteractionRequest =
description?: string;
suggestions?: unknown[];
metadata?: Record<string, unknown>;
- }
- | {
+ })
+ | (InteractionRequestBase & {
kind: 'ask_user_question';
- requestId: string;
questions: AskUserQuestionItem[];
- }
- | {
+ })
+ | (InteractionRequestBase & {
kind: 'plan_review';
- requestId: string;
plan: string;
planFilePath?: string;
- };
+ });
export type InteractionDecision =
| {
diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.json
index d497346663..f293b43457 100644
--- a/packages/maker-shared/package.json
+++ b/packages/maker-shared/package.json
@@ -48,6 +48,7 @@
"./schedule-model": "./src/scheduleModel.ts",
"./schedule-types": "./src/scheduleTypes.ts",
"./session-action-strip": "./src/sessionActionStrip.ts",
+ "./session-activity": "./src/sessionActivity.ts",
"./session-controls": "./src/sessionControls.ts",
"./session-identity": "./src/sessionIdentity.ts",
"./session-list": "./src/sessionList.ts",
diff --git a/packages/maker-shared/src/__tests__/sessionActivity.test.ts b/packages/maker-shared/src/__tests__/sessionActivity.test.ts
new file mode 100644
index 0000000000..a47bbb69b8
--- /dev/null
+++ b/packages/maker-shared/src/__tests__/sessionActivity.test.ts
@@ -0,0 +1,81 @@
+import { describe, expect, it } from 'vitest';
+
+import { projectSessionActivity, sessionWorkflowFromTitle } from '../sessionActivity.js';
+
+describe('session activity projection', () => {
+ it('uses the lifecycle priority error > waiting > running > completed > idle', () => {
+ expect(projectSessionActivity({ sessionId: 's', running: true })).toMatchObject({
+ phase: 'running',
+ currentTurnActive: true,
+ });
+ expect(
+ projectSessionActivity({ sessionId: 's', running: true, waitingForUser: true }).phase,
+ ).toBe('needs-interaction');
+ expect(projectSessionActivity({
+ sessionId: 's',
+ running: true,
+ waitingForUser: true,
+ terminal: 'error',
+ })).toMatchObject({
+ phase: 'error',
+ currentTurnActive: true,
+ });
+ expect(projectSessionActivity({
+ sessionId: 's',
+ livePhase: 'running',
+ terminal: 'error',
+ })).toMatchObject({
+ phase: 'error',
+ currentTurnActive: true,
+ });
+ expect(projectSessionActivity({ sessionId: 's', terminal: 'error' }).phase).toBe('error');
+ expect(projectSessionActivity({ sessionId: 's', terminal: 'completed' }).phase).toBe(
+ 'completed',
+ );
+ expect(projectSessionActivity({ sessionId: 's' }).phase).toBe('idle');
+ expect(projectSessionActivity({ sessionId: 's' }).currentTurnActive).toBe(false);
+ });
+
+ it('lifts known and unknown title workflow states without rewriting the title', () => {
+ expect(sessionWorkflowFromTitle('🔴#2804 会话控制面 · 等拍板')).toEqual({
+ key: 'awaiting-user-decision',
+ label: '等拍板',
+ source: 'title',
+ waitingOn: 'user',
+ });
+ expect(sessionWorkflowFromTitle('🚧#2804 会话控制面 · 待bot')).toEqual({
+ key: 'awaiting-bot',
+ label: '待bot',
+ source: 'title',
+ waitingOn: 'automation',
+ });
+ expect(sessionWorkflowFromTitle('任务 · 等待外部系统')).toEqual({
+ key: 'title:等待外部系统',
+ label: '等待外部系统',
+ source: 'title',
+ });
+ });
+
+ it('preserves timing, action and graceful-stop control facets', () => {
+ expect(
+ projectSessionActivity({
+ sessionId: 's',
+ source: 'live',
+ livePhase: 'running',
+ startedAtMs: 10,
+ lastActivityAtMs: 20,
+ currentActionSummary: ' 正在测试 ',
+ turnGeneration: 3,
+ gracefulStopState: 'waiting-for-safe-point',
+ }),
+ ).toMatchObject({
+ phase: 'running',
+ startedAtMs: 10,
+ lastActivityAtMs: 20,
+ currentActionSummary: '正在测试',
+ turnGeneration: 3,
+ gracefulStopState: 'waiting-for-safe-point',
+ source: 'live',
+ });
+ });
+});
diff --git a/packages/maker-shared/src/index.ts b/packages/maker-shared/src/index.ts
index 3fd2a0f1fd..83f68e9bc2 100644
--- a/packages/maker-shared/src/index.ts
+++ b/packages/maker-shared/src/index.ts
@@ -34,6 +34,7 @@ export * from './scheduleForm.js';
export * from './scheduleModel.js';
export type * from './scheduleTypes.js';
export * from './sessionActionStrip.js';
+export * from './sessionActivity.js';
export * from './sessionControls.js';
export * from './sessionIdentity.js';
export * from './sessionList.js';
diff --git a/packages/maker-shared/src/sessionActivity.ts b/packages/maker-shared/src/sessionActivity.ts
new file mode 100644
index 0000000000..4d9d2e348e
--- /dev/null
+++ b/packages/maker-shared/src/sessionActivity.ts
@@ -0,0 +1,170 @@
+/**
+ * Canonical session control-plane status projection.
+ *
+ * The inputs remain owned by their existing lifecycle authorities (Agent Island,
+ * persisted session rows, queue/control state). This module only defines the one
+ * read model consumed by UI, MCP probes, and future subscribers.
+ */
+
+type OpenValue<Known extends string> = Known | (string & Record<never, never>);
+
+export type SessionActivityPhase = OpenValue<
+ 'idle' | 'running' | 'needs-interaction' | 'completed' | 'error'
+>;
+
+export type SessionRecordStatus = OpenValue<'active' | 'archived' | 'deleted'>;
+
+export type SessionGracefulStopState = OpenValue<
+ 'none' | 'waiting-for-safe-point' | 'requesting' | 'requested' | 'unconfirmed'
+>;
+
+export type SessionActivitySource = OpenValue<'live' | 'persisted' | 'fallback'>;
+
+export type SessionWorkflowWaitTarget = OpenValue<'user' | 'automation' | 'review' | 'merge'>;
+
+export interface SessionWorkflowState {
+ /** Stable machine key. Unknown title states retain an open `title:*` key. */
+ key: string;
+ /** Original user-visible suffix, without rewriting the session title. */
+ label: string;
+ source: 'title';
+ waitingOn?: SessionWorkflowWaitTarget;
+}
+
+export interface SessionActivitySnapshot {
+ sessionId: string;
+ phase: SessionActivityPhase;
+ /**
+ * Whether the current turn is still actively running. This stays orthogonal
+ * to `phase`: a durable/stale error may keep the right-side error status at
+ * higher priority while a newer turn continues running.
+ *
+ * Optional on the wire so older device-link snapshots remain readable.
+ */
+ currentTurnActive?: boolean;
+ recordStatus?: SessionRecordStatus;
+ startedAtMs: number | null;
+ lastActivityAtMs: number | null;
+ currentActionSummary: string | null;
+ interactionKind?: string;
+ attention: boolean;
+ workflow: SessionWorkflowState | null;
+ turnGeneration: number | null;
+ gracefulStopState: SessionGracefulStopState;
+ source: SessionActivitySource;
+}
+
+/**
+ * Observable edge emitted when a canonical session activity snapshot changes.
+ * A null side marks entry to or exit from the live projection.
+ */
+export interface SessionActivityTransition {
+ sessionId: string;
+ previous: SessionActivitySnapshot | null;
+ current: SessionActivitySnapshot | null;
+ changedAtMs: number;
+}
+
+export interface SessionActivityProjectionInput {
+ sessionId: string;
+ recordStatus?: SessionRecordStatus;
+ title?: string | null;
+ source?: SessionActivitySource;
+ livePhase?: SessionActivityPhase | null;
+ running?: boolean;
+ waitingForUser?: boolean;
+ terminal?: 'completed' | 'error' | null;
+ startedAtMs?: number | null;
+ lastActivityAtMs?: number | null;
+ currentActionSummary?: string | null;
+ interactionKind?: string;
+ attention?: boolean;
+ turnGeneration?: number | null;
+ gracefulStopState?: SessionGracefulStopState;
+}
+
+const WORKFLOW_RULES: readonly {
+ key: string;
+ waitingOn?: SessionWorkflowWaitTarget;
+ matches: (label: string) => boolean;
+}[] = [
+ { key: 'awaiting-user-decision', waitingOn: 'user', matches: (label) => /等拍板/u.test(label) },
+ { key: 'awaiting-acceptance', waitingOn: 'user', matches: (label) => /待验收/u.test(label) },
+ { key: 'awaiting-bot', waitingOn: 'automation', matches: (label) => /待\s*bot/iu.test(label) },
+ { key: 'awaiting-review', waitingOn: 'review', matches: (label) => /待人审|待审核/u.test(label) },
+ { key: 'awaiting-merge', waitingOn: 'merge', matches: (label) => /待合并/u.test(label) },
+ { key: 'draft', matches: (label) => /draft/iu.test(label) },
+ { key: 'in-progress', matches: (label) => /修\s*review|修复|处理中/u.test(label) },
+ { key: 'completed', matches: (label) => /已合并|已关闭|已完成/u.test(label) },
+];
+
+function workflowSuffix(title: string): string | null {
+ const parts = title.split('·');
+ const suffix = (parts.at(-1) ?? '').trim();
+ return parts.length > 1 && suffix ? suffix : null;
+}
+
+function openWorkflowKey(label: string): string {
+ const normalized = label
+ .normalize('NFKC')
+ .trim()
+ .toLowerCase()
+ .replace(/\s+/gu, '-');
+ return `title:${normalized || 'unknown'}`;
+}
+
+/** Lift the workflow suffix already carried by the title into a structured facet. */
+export function sessionWorkflowFromTitle(title: string | null | undefined): SessionWorkflowState | null {
+ if (!title) return null;
+ const label = workflowSuffix(title);
+ if (!label) return null;
+ const rule = WORKFLOW_RULES.find((candidate) => candidate.matches(label));
+ return {
+ key: rule?.key ?? openWorkflowKey(label),
+ label,
+ source: 'title',
+ ...(rule?.waitingOn ? { waitingOn: rule.waitingOn } : {}),
+ };
+}
+
+function resolvePhase(input: SessionActivityProjectionInput): SessionActivityPhase {
+ if (input.terminal === 'error' || input.livePhase === 'error') return 'error';
+ if (input.waitingForUser === true || input.livePhase === 'needs-interaction') {
+ return 'needs-interaction';
+ }
+ if (input.running === true || input.livePhase === 'running') return 'running';
+ if (input.terminal === 'completed' || input.livePhase === 'completed') return 'completed';
+ if (input.livePhase && input.livePhase !== 'idle') return input.livePhase;
+ return 'idle';
+}
+
+/** Build the canonical read model without persisting another status copy. */
+export function projectSessionActivity(
+ input: SessionActivityProjectionInput,
+): SessionActivitySnapshot {
+ return {
+ sessionId: input.sessionId,
+ phase: resolvePhase(input),
+ currentTurnActive: input.running === true || input.livePhase === 'running',
+ ...(input.recordStatus ? { recordStatus: input.recordStatus } : {}),
+ startedAtMs: input.startedAtMs ?? null,
+ lastActivityAtMs: input.lastActivityAtMs ?? null,
+ currentActionSummary: input.currentActionSummary?.trim() || null,
+ ...(input.interactionKind ? { interactionKind: input.interactionKind } : {}),
+ attention: input.attention === true,
+ workflow: sessionWorkflowFromTitle(input.title),
+ turnGeneration: input.turnGeneration ?? null,
+ gracefulStopState: input.gracefulStopState ?? 'none',
+ source: input.source ?? 'fallback',
+ };
+}
+
+export function isSessionActivityRunning(activity: Pick<SessionActivitySnapshot, 'phase'>): boolean {
+ return activity.phase === 'running';
+}
+
+export function isSessionActivityWaitingForUser(
+ activity: Pick<SessionActivitySnapshot, 'phase'>,
+): boolean {
+ return activity.phase === 'needs-interaction';
+}