Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 刚发送的任务立刻按运行中排序并提前开始音效 (#3082)

Dash74812cc76777
diff --git a/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts b/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts
index 43629febcb..363a1aedd7 100644
--- a/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts
+++ b/apps/desktop/src/main/__tests__/interruptedContinuationContract.test.ts
@@ -237,6 +237,34 @@ describe('interrupted continuation enqueue contract', () => {
expect(registerSource).toMatch(/supportsScheduleIntervalNullClear:\s*true/);
});
+ it('previews user enqueues to Agent Island before drain/sendToAgent', () => {
+ expect(registerSource).toContain('previewQueuedUserTurn: (sessionId, item) => {');
+ expect(registerSource).toContain("source: 'enqueue'");
+ expect(registerSource).toContain('item.text || item.persistedContent');
+ expect(registerSource).toContain('extractAgentIslandPromptText(content)');
+ const drainableHead = coordinatorSource.indexOf(
+ 'if (this.getDrainableHead(sessionId, state) === item)',
+ );
+ const enqueuePreview = coordinatorSource.indexOf('this.deps.previewQueuedUserTurn?.(sessionId, item);');
+ const drainImmediate = coordinatorSource.indexOf("void this.drain(sessionId, 'enqueue-immediate');");
+ expect(drainableHead).toBeGreaterThan(-1);
+ expect(enqueuePreview).toBeGreaterThan(drainableHead);
+ expect(drainImmediate).toBeGreaterThan(enqueuePreview);
+ expect(coordinatorSource).toContain('!automaticOrigin && !isUiContinuationItem(item)');
+ });
+
+ it('rolls back Agent Island enqueue preview when the queued item is discarded, rejected, or blocked', () => {
+ expect(registerSource).toContain(
+ "rollbackAgentIslandUserPrompt(sessionId, item.clientId, 'discarded')",
+ );
+ expect(registerSource).toContain(
+ "rollbackAgentIslandUserPrompt(sessionId, item.clientId, 'rejected')",
+ );
+ expect(registerSource).toContain(
+ "rollbackAgentIslandUserPrompt(sessionId, item.clientId, 'blocked')",
+ );
+ });
+
it('fails a pending scheduler auto-resume before dispatching unrelated user input', () => {
const userEnqueueStart = registerSource.indexOf('onUserEnqueue:');
const userEnqueueEnd = registerSource.indexOf('onDiscardedQueuedMessage:', userEnqueueStart);
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index 650fd12854..8f6ed2fd56 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -555,11 +555,12 @@ describe('sendToSession ordering', () => {
const promptPreviewBlock = extractBetween(
source,
'function notifyAgentIslandUserPrompt',
- 'function extractAgentIslandPromptText',
+ 'function dispatchAgentIslandUserPrompt',
);
expect(promptPreviewBlock).toContain('try {');
- expect(promptPreviewBlock).toContain('getAgentIslandService()?.handleUserPrompt');
+ expect(promptPreviewBlock).toContain('getAgentIslandService()');
+ expect(promptPreviewBlock).toContain('service.handleUserPrompt');
expect(promptPreviewBlock).toContain('log.warn(\'Agent Island prompt preview update failed after user message persistence\'');
expect(promptPreviewBlock).toContain('clientId: options.clientId');
expect(promptPreviewBlock).toContain('error: error instanceof Error ? error.message : String(error)');
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 c9983fa816..0c92fe0c79 100644
--- a/apps/desktop/src/main/agent-island/__tests__/service.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/service.test.ts
@@ -2239,6 +2239,123 @@ describe('AgentIslandService native publishing', () => {
expect(playSound).toHaveBeenNthCalledWith(2, customSound('complete.wav'));
});
+ it('plays the start sound on user prompt without waiting for an isRunning status event', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
+ void state;
+ void frameOrFrames;
+ return true;
+ });
+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish, playSound },
+ });
+ syncEnabledForTest(service, publish);
+ service.setSoundSettings({
+ enabled: true,
+ sounds: {
+ ...DEFAULT_AGENT_ISLAND_SOUND_SETTINGS.sounds,
+ start: customSound('start.wav'),
+ },
+ });
+ playSound.mockClear();
+
+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');
+
+ expect(playSound).toHaveBeenCalledWith(customSound('start.wav'));
+ expect(publish.mock.calls.at(-1)?.[0].sessions[0]).toMatchObject({
+ sessionId: 's1',
+ phase: 'running',
+ });
+ });
+
+ it('keeps the first rollback snapshot when the same clientId is previewed again', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
+ void state;
+ void frameOrFrames;
+ return true;
+ });
+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish, playSound },
+ });
+ syncEnabledForTest(service, publish);
+ const meta = { sessionId: 's1', agentKind: 'codex' as const };
+
+ service.handleUserPrompt(meta, 'first preview', { clientId: 'c1' });
+ playSound.mockClear();
+ service.handleUserPrompt(meta, 'persist preview', { clientId: 'c1' });
+ expect(playSound).not.toHaveBeenCalled();
+ service.rollbackUserPrompt(meta.sessionId, 'c1');
+
+ expect(publish.mock.calls.at(-1)?.[0].sessions).toEqual([]);
+ });
+
+ it('does not rewind another session reveal when rolling back a blocked preview', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
+ void state;
+ void frameOrFrames;
+ return true;
+ });
+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish, playSound },
+ });
+ syncEnabledForTest(service, publish);
+
+ service.handleUserPrompt({ sessionId: 'session-a', agentKind: 'codex' }, 'task a', {
+ clientId: 'client-a',
+ });
+ service.handleUserPrompt({ sessionId: 'session-b', agentKind: 'codex' }, 'task b', {
+ clientId: 'client-b',
+ });
+ service.rollbackUserPrompt('session-a', 'client-a');
+
+ const sessionIds = (publish.mock.calls.at(-1)?.[0].sessions ?? []).map(
+ (session) => session.sessionId,
+ );
+ expect(sessionIds).toContain('session-b');
+ expect(sessionIds).not.toContain('session-a');
+ });
+
+ it('restores the same session completion reveal after a blocked follow-up preview', async () => {
+ const { AgentIslandService } = await import('../service.js');
+ const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
+ void state;
+ void frameOrFrames;
+ return true;
+ });
+ const playSound = vi.fn<(sound: AgentIslandSoundChoice) => boolean>(() => true);
+ const service = new AgentIslandService({
+ getMainWindow: () => null,
+ nativeHost: { failed: false, publish, playSound },
+ });
+ syncEnabledForTest(service, publish);
+ service.setAppFocused(false);
+
+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'run tests');
+ service.handleAgentEvent({ sessionId: 's1', agentKind: 'codex' }, doneEvent());
+ expect(publish.mock.calls.at(-1)?.[0]).toMatchObject({
+ displaySurface: 'completionCard',
+ currentSessionId: 's1',
+ });
+
+ service.handleUserPrompt({ sessionId: 's1', agentKind: 'codex' }, 'follow up', {
+ clientId: 'follow',
+ });
+ service.rollbackUserPrompt('s1', 'follow');
+
+ expect(publish.mock.calls.at(-1)?.[0]).toMatchObject({
+ displaySurface: 'completionCard',
+ currentSessionId: 's1',
+ });
+ });
+
it('removes user-stopped sessions and ignores provider completion tails without playing completion sound', async () => {
const { AgentIslandService } = await import('../service.js');
const publish = vi.fn((state: AgentIslandDisplayState, frameOrFrames: AgentIslandNativeFrame | AgentIslandNativeFrame[]) => {
diff --git a/apps/desktop/src/main/agent-island/service.ts b/apps/desktop/src/main/agent-island/service.ts
index ecc0e303a6..11bbae7361 100644
--- a/apps/desktop/src/main/agent-island/service.ts
+++ b/apps/desktop/src/main/agent-island/service.ts
@@ -839,6 +839,12 @@ export class AgentIslandService {
handleUserPrompt(meta: AgentIslandSessionMeta, prompt: string, debugMeta: AgentIslandUserPromptDebugMeta = {}): boolean {
const receivedAt = Date.now();
const hydrated = this.hydrateMeta(meta);
+ const rollbackKey = this.userPromptRollbackKey(hydrated.sessionId, debugMeta.clientId);
+ // 入队预览和 persist 预览共用 clientId。已经预览过的第二次只确认,不再追加
+ // activity、不推进 epoch,否则岛上同一条消息出现两遍、开始音效对应的回滚基线也会被冲掉。
+ if (rollbackKey && this.userPromptRollbackTokens.has(rollbackKey)) {
+ return true;
+ }
const previousInteractionEpoch = this.interactionEpochBySession.get(hydrated.sessionId);
const wasStopped = this.stoppedSessionIds.has(hydrated.sessionId);
const wasReplacementTurnPending = this.replacementTurnPendingSessionIds.has(hydrated.sessionId);
@@ -859,7 +865,6 @@ export class AgentIslandService {
if (deferInteractionEpochUntilDispatch) {
this.replacementTurnDispatchingSessionIds.delete(hydrated.sessionId);
}
- const rollbackKey = this.userPromptRollbackKey(hydrated.sessionId, debugMeta.clientId);
if (rollbackKey) {
this.userPromptRollbackTokens.set(rollbackKey, {
state: createAgentIslandUserPromptRollbackToken(this.state, hydrated.sessionId),
diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.ts
index 456d88a88a..bf60eeb382 100644
--- a/apps/desktop/src/main/agent-island/state.ts
+++ b/apps/desktop/src/main/agent-island/state.ts
@@ -157,8 +157,6 @@ interface AgentIslandSessionState {
export interface AgentIslandUserPromptRollbackToken {
sessionId: string;
session: AgentIslandSessionState | null;
- activeTransientSessionId: string | null;
- transientRevealQueue: string[];
}
/**
@@ -478,8 +476,6 @@ export function createAgentIslandUserPromptRollbackToken(
return {
sessionId,
session: session ? cloneSession(session) : null,
- activeTransientSessionId: state.activeTransientSessionId,
- transientRevealQueue: [...state.transientRevealQueue],
};
}
@@ -487,13 +483,51 @@ export function rollbackAgentIslandUserPrompt(
state: AgentIslandState,
token: AgentIslandUserPromptRollbackToken,
): void {
+ // 只还原该 session 自己的条目和它自己的 reveal 归属。禁止整份写回
+ // activeTransientSessionId / reveal queue,否则会盖掉其它 session。
if (token.session) {
- state.sessions.set(token.sessionId, cloneSession(token.session));
- } else {
- state.sessions.delete(token.sessionId);
+ const restored = cloneSession(token.session);
+ state.sessions.set(token.sessionId, restored);
+ restoreSessionScopedReveal(state, restored, Date.now());
+ return;
+ }
+ state.sessions.delete(token.sessionId);
+ removeQueuedTransientReveal(state, token.sessionId);
+}
+
+function restoreSessionScopedReveal(
+ state: AgentIslandState,
+ session: AgentIslandSessionState,
+ now: number,
+): void {
+ const sessionId = session.sessionId;
+ const wantsActive = session.revealUntil != null
+ && session.revealUntil > now
+ && session.deferredReveal !== true;
+ const wantsQueued = session.deferredRevealReason === 'queued';
+ if (!wantsActive && !wantsQueued) return;
+
+ if (wantsActive) {
+ if (!state.activeTransientSessionId || state.activeTransientSessionId === sessionId) {
+ state.activeTransientSessionId = sessionId;
+ state.transientRevealQueue = state.transientRevealQueue.filter(
+ (queuedSessionId) => queuedSessionId !== sessionId,
+ );
+ return;
+ }
+ if (!state.transientRevealQueue.includes(sessionId)) {
+ state.transientRevealQueue.push(sessionId);
+ }
+ session.deferredReveal = true;
+ session.deferredRevealReason = 'queued';
+ session.revealUntil = null;
+ return;
+ }
+
+ if (state.activeTransientSessionId === sessionId) return;
+ if (!state.transientRevealQueue.includes(sessionId)) {
+ state.transientRevealQueue.push(sessionId);
}
- state.activeTransientSessionId = token.activeTransientSessionId;
- state.transientRevealQueue = [...token.transientRevealQueue];
}
export function applyAgentIslandEvent(
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 eb89a4fb9b..8b44a10fe6 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
@@ -267,6 +267,9 @@ function createHarness(opts?: {
NonNullable<AgentInputCoordinatorDeps['onAutomaticEnqueue']>
>(() => {});
const onUserEnqueue = vi.fn<NonNullable<AgentInputCoordinatorDeps['onUserEnqueue']>>(() => {});
+ const previewQueuedUserTurn = vi.fn<
+ NonNullable<AgentInputCoordinatorDeps['previewQueuedUserTurn']>
+ >(() => {});
const onDiscardedQueuedMessage = vi.fn<
NonNullable<AgentInputCoordinatorDeps['onDiscardedQueuedMessage']>
>(() => {});
@@ -283,6 +286,7 @@ function createHarness(opts?: {
onUiRetry,
onAutomaticEnqueue,
onUserEnqueue,
+ previewQueuedUserTurn,
onDiscardedQueuedMessage,
onRejectedUserTurn,
supersedeRetriedUserTurn,
@@ -361,6 +365,7 @@ function createHarness(opts?: {
onUiRetry,
onAutomaticEnqueue,
onUserEnqueue,
+ previewQueuedUserTurn,
onDiscardedQueuedMessage,
onRejectedUserTurn,
supersedeRetriedUserTurn,
@@ -2835,6 +2840,59 @@ describe('AgentInputCoordinator send transaction', () => {
expect(h.onUserEnqueue).toHaveBeenCalledWith(sid);
});
+ it('previews a user enqueue to Agent Island before sendToAgent starts', async () => {
+ const h = createHarness();
+ const sid = 'island-preview-before-send';
+ const sendStarted = deferred<AgentInputSendResult>();
+ h.sendToAgent.mockImplementationOnce(async () => sendStarted.promise);
+
+ h.coordinator.enqueue(sid, makeItem('q-preview', 'start this task'));
+ await flush();
+
+ expect(h.previewQueuedUserTurn).toHaveBeenCalledWith(
+ sid,
+ expect.objectContaining({ clientId: 'q-preview', text: 'start this task' }),
+ );
+ expect(h.previewQueuedUserTurn.mock.invocationCallOrder[0]).toBeLessThan(
+ h.sendToAgent.mock.invocationCallOrder[0],
+ );
+
+ sendStarted.resolve(sendSuccess());
+ await flush();
+ });
+
+ it('does not preview a user enqueue that stays queued behind an active turn', async () => {
+ const h = createHarness();
+ const sid = 'island-preview-queued-behind';
+ const sendStarted = deferred<AgentInputSendResult>();
+ h.sendToAgent.mockImplementationOnce(async () => sendStarted.promise);
+
+ h.coordinator.enqueue(sid, makeItem('q-first', 'first'));
+ await flush();
+ expect(h.previewQueuedUserTurn).toHaveBeenCalledTimes(1);
+ h.previewQueuedUserTurn.mockClear();
+
+ h.coordinator.enqueue(sid, makeItem('q-second', 'second'));
+ await flush();
+ expect(h.previewQueuedUserTurn).not.toHaveBeenCalled();
+
+ sendStarted.resolve(sendSuccess());
+ await flush();
+ });
+
+ it('does not preview automatic enqueues to Agent Island', async () => {
+ const h = createHarness();
+ const sid = 'island-preview-skip-auto';
+ h.coordinator.enqueue(
+ sid,
+ makeItem('q-orca', 'worker output', {
+ origin: { kind: 'orca', senderLabel: 'worker' },
+ }),
+ );
+ await flush();
+ expect(h.previewQueuedUserTurn).not.toHaveBeenCalled();
+ });
+
it('a deduplicated resend does not report a user enqueue', async () => {
// 弱网 / 移动端的重传带同一个 clientId, 会被幂等去重丢弃 —— 它压根没推进会话。
// 若在去重**之前**作废记账, 一条延迟到达的旧重传就会删掉之后才装上的、更新的
@@ -2906,6 +2964,7 @@ describe('AgentInputCoordinator send transaction', () => {
// text 是 CONTINUE_AFTER_ERROR_PROMPT → enqueue 入口 captureOriginalSyntheticTrigger
// 自动识别为 'continue'(isUiContinuationItem 判定),无需也不能显式赋值。
const continueItem = makeItem('q-continue', CONTINUE_AFTER_ERROR_PROMPT);
+ h.previewQueuedUserTurn.mockClear();
h.coordinator.enqueue(sid, continueItem);
await flush();
@@ -2920,6 +2979,7 @@ describe('AgentInputCoordinator send transaction', () => {
});
// queue-head 从不发 onUiRetry(与 retryLastError 语义一致)。
expect(h.onUiRetry).not.toHaveBeenCalled();
+ expect(h.previewQueuedUserTurn).not.toHaveBeenCalled();
});
it('queue-head retry never substitutes the continue prompt and redrains the original head', async () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
index 00728c6b7f..f77b6447ec 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agentHandoff.test.ts
@@ -5,6 +5,7 @@ import {
composeForkOriginHandoff,
buildHandoffText,
createAgentHandoffPendingRegistry,
+ extractAgentIslandPromptText,
extractPlainText,
prependHandoffToUserMessage,
type HandoffSourceMessage,
@@ -62,6 +63,21 @@ describe('extractPlainText', () => {
});
});
+describe('extractAgentIslandPromptText', () => {
+ it('keeps literal JSON prompts instead of treating them as envelopes', () => {
+ expect(extractAgentIslandPromptText('{"foo":"bar"}')).toBe('{"foo":"bar"}');
+ expect(extractAgentIslandPromptText('[1,2]')).toBe('[1,2]');
+ expect(extractAgentIslandPromptText('{"text":"hello"}')).toBe('{"text":"hello"}');
+ });
+
+ it('unwraps stringifyUserContent envelopes only', () => {
+ expect(
+ extractAgentIslandPromptText(JSON.stringify({ text: 'hello', images: [], files: [] })),
+ ).toBe('hello');
+ expect(extractAgentIslandPromptText({ text: 'hello', images: [], files: [] })).toBe('hello');
+ });
+});
+
describe('buildHandoffText', () => {
const opts = { fromLabel: 'Claude Code', toLabel: 'Codex' };
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 0df384880f..09e4b4f254 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -473,6 +473,11 @@ export interface AgentInputCoordinatorDeps {
* pendingQueue.unshift、不经这两个用户输入入口, 于是不会自我作废。
*/
onUserEnqueue?: (sessionId: string) => void;
+ /**
+ * 真人消息刚进队、尚未 drain / sendToAgent。灵动岛用它在 agent 进程拉起前
+ * 就进入 running 并播开始音效,避免「任务开始」跟着 isRunning 一起晚响。
+ */
+ previewQueuedUserTurn?: (sessionId: string, item: AgentInputQueuedMessage) => void;
/** 自动输入推进了会话,但不构成真人介入,也不能重置自动恢复预算。 */
onAutomaticEnqueue?: (sessionId: string) => void;
/**
@@ -1543,6 +1548,11 @@ export class AgentInputCoordinator {
// 仍有 getDrainableHead 幂等校验, 不会与既有 wake 点重复派发。agent 忙 / 队列
// 已有积压时走 else, 维持原排队语义(emit 中间态 + 异步 drain)。
if (this.getDrainableHead(sessionId, state) === item) {
+ // 只预览马上要派发的队首。排队项若也预览,删除较早项会把整份岛快照滚回去,
+ // 抹掉后来的预览和期间事件。合成 Continue 同样不预览内部 prompt。
+ if (!automaticOrigin && !isUiContinuationItem(item)) {
+ this.deps.previewQueuedUserTurn?.(sessionId, item);
+ }
void this.drain(sessionId, 'enqueue-immediate');
} else {
this.emit(sessionId);
@@ -4505,6 +4515,7 @@ export class AgentInputCoordinator {
if (!isSchedulerOriginItem(item)) this.deps.onAutomaticEnqueue?.(sessionId);
} else if (!isUiContinuationItem(item)) {
this.deps.onUserEnqueue?.(sessionId);
+ this.deps.previewQueuedUserTurn?.(sessionId, item);
}
this.abandonActiveTurnRecoveryForUserAction(state);
this.clearErrorUnlessQueueHeadBlocked(state, item.clientId);
diff --git a/apps/desktop/src/main/maker-ipc/agentHandoff.ts b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
index 613a6142ef..f2c08caebd 100644
--- a/apps/desktop/src/main/maker-ipc/agentHandoff.ts
+++ b/apps/desktop/src/main/maker-ipc/agentHandoff.ts
@@ -145,6 +145,42 @@ export function extractPlainText(content: unknown): string {
return '';
}
+function isStringifyUserContentEnvelope(
+ value: unknown,
+): value is { text: string } {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
+ const record = value as Record<string, unknown>;
+ return typeof record.text === 'string'
+ && Array.isArray(record.images)
+ && Array.isArray(record.files);
+}
+
+/** 岛上预览正文:只解开 stringifyUserContent 信封,JSON 原文提示保持原样。 */
+export function extractAgentIslandPromptText(content: unknown): string | null {
+ if (typeof content === 'string') {
+ const trimmed = content.trim();
+ if (!trimmed) return null;
+ if (trimmed.startsWith('{')) {
+ try {
+ const parsed: unknown = JSON.parse(trimmed);
+ if (isStringifyUserContentEnvelope(parsed)) {
+ const text = parsed.text.trim();
+ return text || null;
+ }
+ } catch {
+ // 用户原文就是 JSON 形字符串。
+ }
+ }
+ return trimmed;
+ }
+ if (isStringifyUserContentEnvelope(content)) {
+ const text = content.text.trim();
+ return text || null;
+ }
+ const text = extractPlainText(content).trim();
+ return text || null;
+}
+
interface Turn {
userText: string;
/** 轮内按序的展示行(assistant 文本 / 工具行 / 错误行)。 */
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 70bc287e80..146d0a371c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -694,6 +694,7 @@ import {
type MakerSessionAgentSwitchHandlerDeps,
} from './sessionAgentSwitchHandler.js';
import {
+ extractAgentIslandPromptText,
prependNoteToWireUserMessage,
prependHandoffToUserMessage,
type HandoffWireMessage,
@@ -3266,31 +3267,7 @@ function rollbackAgentIslandUserPrompt(
}
}
-function extractAgentIslandPromptText(content: unknown): string | null {
- if (typeof content === 'string') return content.trim() || null;
- if (Array.isArray(content)) return extractAgentIslandPromptTextFromBlocks(content);
- if (!content || typeof content !== 'object') return null;
- const record = content as { content?: unknown; text?: unknown };
- if (typeof record.content === 'string') return record.content.trim() || null;
- if (Array.isArray(record.content)) return extractAgentIslandPromptTextFromBlocks(record.content);
- if (typeof record.text === 'string') return record.text.trim() || null;
- return null;
-}
-
-function extractAgentIslandPromptTextFromBlocks(blocks: unknown[]): string | null {
- const text = blocks
- .map((block) => {
- if (typeof block === 'string') return block;
- if (!block || typeof block !== 'object') return '';
- const record = block as { type?: unknown; text?: unknown };
- return record.type === 'text' && typeof record.text === 'string' ? record.text : '';
- })
- .map((line) => line.trim())
- .filter(Boolean)
- .join('\n')
- .trim();
- return text || null;
-}
+
/**
* 当前是否有任意一个 session 正在跑 turn。
@@ -11697,6 +11674,17 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
failPendingSchedulerAutoResume(sessionId);
publishUiSessionIntervention(sessionId);
},
+ previewQueuedUserTurn: (sessionId, item) => {
+ notifyAgentIslandUserPrompt(
+ {
+ id: sessionId,
+ agentKind: item.createOpts?.agentKind,
+ workDir: item.workingDir,
+ },
+ item.text || item.persistedContent,
+ { source: 'enqueue', clientId: item.clientId },
+ );
+ },
onAutomaticEnqueue: (sessionId) => {
// Orca 等自动输入会推进同一会话,必须撤销旧 retry owner,避免它消费这轮事件;
// 但预算充值仍只发生在真人消息的持久化路径,自动输入不会重置 episode。
@@ -11705,6 +11693,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
publishUiSessionIntervention(sessionId);
},
onRejectedUserTurn: (sessionId, item) => {
+ rollbackAgentIslandUserPrompt(sessionId, item.clientId, 'rejected');
// Auto-resume items have an exact-token cleanup boundary below. Keep
// their attempt lease until that boundary can restore recovery and
// finalize the suppressed error; releasing it here would make a later
@@ -11714,6 +11703,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
},
// 队列项未派发即被丢弃(stop/remove/clearSession) → 释放暂存的 accepted 副作用, 防回调表泄漏。
onDiscardedQueuedMessage: (sessionId, item) => {
+ rollbackAgentIslandUserPrompt(sessionId, item.clientId, 'discarded');
discardQueuedAttachmentOwnership(sessionId, item.clientId);
orcaInterAgentDispatcher.discardQueuedOrcaInterAgentAcceptedCallback(item.clientId);
// Auto-resume cleanup must run before generic claimed-retry release:
@@ -11763,13 +11753,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
screenGhostUserMessage(sessionId, agentFacingText),
);
},
- onUserMessageBlocked: (sessionId, item, verdict) =>
+ onUserMessageBlocked: (sessionId, item, verdict) => {
+ rollbackAgentIslandUserPrompt(sessionId, item.clientId, 'blocked');
broadcastGhostMessageBlocked({
sessionId,
clientId: item.clientId,
text: item.text,
...verdict,
- }),
+ });
+ },
onUserMessageRewritten: (sessionId, item, info) =>
broadcastGhostMessageRewritten({ sessionId, clientId: item.clientId, ...info }),
beforeDispatchUserTurn: async (sessionId, item) => {
diff --git a/apps/desktop/src/renderer/__tests__/mainListModel.test.ts b/apps/desktop/src/renderer/__tests__/mainListModel.test.ts
index 467d0c204a..0350751fb2 100644
--- a/apps/desktop/src/renderer/__tests__/mainListModel.test.ts
+++ b/apps/desktop/src/renderer/__tests__/mainListModel.test.ts
@@ -389,6 +389,27 @@ describe('buildMainListEntries — 排序口径', () => {
expect(labels(entries)).toEqual(['s:needs-input', 's:done-unread', 's:running', 's:idle']);
});
+ it('keeps a just-sent session at the top of running before the agent is actually live', () => {
+ // 组装层把 starting 并进 runningSessionIds。新发送比已在跑的更新,应压在运行中档顶;
+ // 更新的空闲任务仍在其余档,不能因为它更新就插到运行中前面。
+ const justSent = session({ updatedAt: '2026-08-12T12:00:00Z', title: 'just-sent' });
+ const runningOlder = session({ updatedAt: '2026-08-12T11:00:00Z', title: 'running-older' });
+ const idleNewer = session({ updatedAt: '2026-08-12T13:00:00Z', title: 'idle-newer' });
+ const entries = buildMainListEntries({
+ projects: [],
+ dialogues: [idleNewer, runningOlder, justSent],
+ groupBy: 'project',
+ groupDialogue: false,
+ sortBy: 'priority',
+ manualProjectOrder: [],
+ priorityContext: {
+ runningSessionIds: new Set([justSent.id, runningOlder.id]),
+ attentionSessionIds: new Set<string>(),
+ },
+ });
+ expect(labels(entries)).toEqual(['s:just-sent', 's:running-older', 's:idle-newer']);
+ });
+
it('keeps the open unread task in place, then parks it at the top of the rest tier after leave', () => {
const unread = session({ updatedAt: '2026-07-01T00:00:00Z', title: 'just-read' });
const olderRest = session({ updatedAt: '2026-08-12T00:00:00Z', title: 'older-rest' });
diff --git a/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts b/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
index 7bdf08a074..ef9f67278d 100644
--- a/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
+++ b/apps/desktop/src/renderer/__tests__/newMakerWorktreeSend.test.ts
@@ -35,6 +35,15 @@ describe('NewMakerDraftRoute worktree send flow', () => {
expect(worktreeCreate).toBeGreaterThan(navigate);
});
+ it('clears starting when the first-message draft is restored after a send-before-start failure', () => {
+ const restore = source.indexOf('const restoreFirstMessageDraft = () => {');
+ const clearStarting = source.indexOf('clearSessionStarting(newSession.id)', restore);
+ const restoreEnd = source.indexOf('};', source.indexOf('emitAutoTitlePreviewCleared(newSession.id)', restore));
+ expect(restore).toBeGreaterThan(-1);
+ expect(clearStarting).toBeGreaterThan(restore);
+ expect(clearStarting).toBeLessThan(restoreEnd);
+ });
+
it('never silently downgrades an explicit worktree request to a normal session', () => {
const selected = source.indexOf('const selectedWorktree = { ...wtRef.current };');
const guard = source.indexOf(
diff --git a/apps/desktop/src/renderer/__tests__/remoteSessionActivityStore.test.ts b/apps/desktop/src/renderer/__tests__/remoteSessionActivityStore.test.ts
index 71ea453768..449836e81e 100644
--- a/apps/desktop/src/renderer/__tests__/remoteSessionActivityStore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteSessionActivityStore.test.ts
@@ -12,6 +12,7 @@ import { beforeEach, describe, expect, it } from 'vitest';
import {
applyRemoteSessionActivity,
clearRemoteSessionActivity,
+ dropStaleRemoteTerminalActivity,
getRemoteSessionActivity,
isRemoteSessionActivityActive,
removeRemoteSessionActivityEntry,
@@ -124,6 +125,32 @@ describe('remoteSessionActivityStore', () => {
expect(getRemoteSessionActivity('s2')).toBeUndefined();
});
+ it('drops unread completed/error mirrors but keeps an in-flight remote turn', () => {
+ applyRemoteSessionActivity('dev-1', {
+ sessionId: 'done',
+ phase: 'completed',
+ compactDetail: '',
+ attention: true,
+ });
+ applyRemoteSessionActivity('dev-1', {
+ sessionId: 'err',
+ phase: 'error',
+ compactDetail: '',
+ attention: true,
+ });
+ applyRemoteSessionActivity('dev-1', {
+ sessionId: 'run',
+ phase: 'running',
+ compactDetail: '',
+ });
+ dropStaleRemoteTerminalActivity('done');
+ dropStaleRemoteTerminalActivity('err');
+ dropStaleRemoteTerminalActivity('run');
+ expect(getRemoteSessionActivity('done')).toBeUndefined();
+ expect(getRemoteSessionActivity('err')).toBeUndefined();
+ expect(getRemoteSessionActivity('run')).toMatchObject({ phase: 'running' });
+ });
+
it('keeps snapshot reference stable when payload content is unchanged', () => {
applyRemoteSessionActivity('dev-1', { sessionId: 's1', phase: 'running', compactDetail: 'x' });
const first = getRemoteSessionActivity('s1');
diff --git a/apps/desktop/src/renderer/__tests__/sessionStartingStore.test.ts b/apps/desktop/src/renderer/__tests__/sessionStartingStore.test.ts
new file mode 100644
index 0000000000..21202d6ff8
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/sessionStartingStore.test.ts
@@ -0,0 +1,111 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ applyRemoteSessionActivity,
+ clearRemoteSessionActivity,
+ getRemoteSessionActivity,
+} from '@/features/device-link/remoteSessionActivityStore';
+import {
+ absorbSessionStarting,
+ clearSessionStarting,
+ getStartingSessionIds,
+ markSessionStarting,
+ resetSessionStartingStoreForTests,
+ SESSION_STARTING_TTL_MS,
+} from '@/lib/sessionStartingStore';
+
+describe('sessionStartingStore', () => {
+ beforeEach(() => {
+ resetSessionStartingStoreForTests();
+ clearRemoteSessionActivity();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ resetSessionStartingStoreForTests();
+ clearRemoteSessionActivity();
+ vi.useRealTimers();
+ });
+
+ it('marks a just-sent session until it is absorbed or cleared', () => {
+ markSessionStarting('new-task');
+ expect([...getStartingSessionIds()]).toEqual(['new-task']);
+
+ absorbSessionStarting(['new-task']);
+ expect([...getStartingSessionIds()]).toEqual([]);
+ });
+
+ it('keeps snapshot identity when remaking the same session', () => {
+ markSessionStarting('s1');
+ const first = getStartingSessionIds();
+ markSessionStarting('s1');
+ expect(getStartingSessionIds()).toBe(first);
+ });
+
+ it('does not absorb unknown ids and can clear a leftover mark', () => {
+ markSessionStarting('keep');
+ absorbSessionStarting(['other']);
+ expect([...getStartingSessionIds()]).toEqual(['keep']);
+
+ clearSessionStarting('keep');
+ expect([...getStartingSessionIds()]).toEqual([]);
+ clearSessionStarting('keep');
+ });
+
+ it('drops a stale remote completed mirror on first mark, not on TTL refresh', () => {
+ applyRemoteSessionActivity('dev-1', {
+ sessionId: 's1',
+ phase: 'completed',
+ compactDetail: '',
+ attention: true,
+ });
+ markSessionStarting('s1');
+ expect(getRemoteSessionActivity('s1')).toBeUndefined();
+ expect([...getStartingSessionIds()]).toEqual(['s1']);
+
+ applyRemoteSessionActivity('dev-1', {
+ sessionId: 's1',
+ phase: 'completed',
+ compactDetail: '',
+ attention: true,
+ });
+ markSessionStarting('s1');
+ expect(getRemoteSessionActivity('s1')).toMatchObject({ phase: 'completed' });
+ absorbSessionStarting(['s1']);
+ expect([...getStartingSessionIds()]).toEqual([]);
+ });
+
+ it('expires a starting mark that never becomes running', () => {
+ markSessionStarting('stuck');
+ vi.advanceTimersByTime(SESSION_STARTING_TTL_MS - 1);
+ expect([...getStartingSessionIds()]).toEqual(['stuck']);
+ vi.advanceTimersByTime(1);
+ expect([...getStartingSessionIds()]).toEqual([]);
+ });
+
+ it('clears starting from asynchronous remote optimistic failure settlement', () => {
+ const source = readFileSync(resolve(__dirname, '..', 'lib', 'makerChatStore.ts'), 'utf8');
+ const start = source.indexOf('function settleRemoteOptimisticFailure');
+ const end = source.indexOf('async function pumpRemoteOptimisticSends', start);
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ expect(source.slice(start, end)).toContain('clearSessionStarting(sessionId)');
+ expect(source.slice(start, end)).toContain(
+ 'if (!remoteOptimisticSendRecords(sessionId)?.size)',
+ );
+ });
+
+ it('clears starting when enqueue only parks the message in a paused or locked queue', () => {
+ const source = readFileSync(resolve(__dirname, '..', 'lib', 'makerChatStore.ts'), 'utf8');
+ const start = source.indexOf('return operation.api.input');
+ const end = source.indexOf('function compactSession', start);
+ expect(start).toBeGreaterThan(-1);
+ expect(end).toBeGreaterThan(start);
+ const enqueueResult = source.slice(start, end);
+ expect(enqueueResult).toContain('projection.queuePaused');
+ expect(enqueueResult).toContain('clearSessionStarting(sessionId)');
+ });
+});
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 671177e921..1934d9d681 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -92,6 +92,7 @@ import {
} from '@/lib/worktreeRemovalWarning';
import { useSessionRunningStatus } from '@/hooks/useSessionRunningStatus';
import { useBackgroundActivitySessionIds } from '@/lib/sessionBackgroundActivityStore';
+import { useStartingSessionIds } from '@/lib/sessionStartingStore';
import { useAttachedSessionIds } from '@/hooks/useAttachedSessionIds';
import { useActiveMainView } from '@/hooks/useActiveMainView';
import { useAnyGhostUnread } from '@/cindy-brain/ghostUnreadStore';
@@ -1223,21 +1224,35 @@ function ExpandedView({
// handleMoveSession 的运行中拦截闸门,后台活动不得静默扩大行为闸门的口径
// (move / 归档 / 通知语义都保持只认真 running)。
const backgroundActivitySessionIds = useBackgroundActivitySessionIds();
+ // 刚发送尚未 isRunning 的任务并进 display running:排序与呼吸点马上进运行中档,
+ // 但不扩大 effectiveRunningSessionIds 的归档 / 移动闸门。
+ const startingSessionIds = useStartingSessionIds(runningSessionIds);
const displayRunningSessionIds = useMemo(() => {
- if (backgroundActivitySessionIds.size === 0) return effectiveRunningSessionIds;
+ if (backgroundActivitySessionIds.size === 0 && startingSessionIds.size === 0) {
+ return effectiveRunningSessionIds;
+ }
const next = new Set(effectiveRunningSessionIds);
for (const id of backgroundActivitySessionIds) next.add(id);
+ for (const id of startingSessionIds) next.add(id);
for (const [leadSessionId, workerSessionIds] of orcaLeadWorkerMap) {
if (next.has(leadSessionId)) continue;
for (const workerSessionId of workerSessionIds) {
- if (backgroundActivitySessionIds.has(workerSessionId)) {
+ if (
+ backgroundActivitySessionIds.has(workerSessionId) ||
+ startingSessionIds.has(workerSessionId)
+ ) {
next.add(leadSessionId);
break;
}
}
}
return next;
- }, [effectiveRunningSessionIds, backgroundActivitySessionIds, orcaLeadWorkerMap]);
+ }, [
+ effectiveRunningSessionIds,
+ backgroundActivitySessionIds,
+ startingSessionIds,
+ orcaLeadWorkerMap,
+ ]);
const collapsedAttentionToneFor = useCallback(
(sessions: readonly Session[]) =>
resolveCollapsedProjectAttentionTone({
@@ -3853,6 +3868,7 @@ function CollapsedView({
const { runningSessionIds } = useSessionRunningStatus(activeSessionId);
// 后台子任务活跃会话同样点亮呼吸(与 ExpandedView 同口径,纯视觉合并)。
const backgroundActivitySessionIds = useBackgroundActivitySessionIds();
+ const startingSessionIds = useStartingSessionIds(runningSessionIds);
// 瓷砖未读点颜色按 attention kind(done 绿 / awaiting TapTap 蓝 / error 红);组件层
// 取一次,renderItem 里查表(renderItem 非组件,不能 per-item 用 hook)。
const attentionKinds = useSessionAttentionKinds();
@@ -3886,7 +3902,11 @@ function CollapsedView({
// 却不亮」(codex review)。
const orcaLeadWorkerMap = useOrcaLeadWorkerMap(sessions);
const railRunningIds = useMemo(() => {
- const next = new Set([...runningSessionIds, ...backgroundActivitySessionIds]);
+ const next = new Set([
+ ...runningSessionIds,
+ ...backgroundActivitySessionIds,
+ ...startingSessionIds,
+ ]);
for (const [leadSessionId, workerSessionIds] of orcaLeadWorkerMap) {
if (next.has(leadSessionId)) continue;
for (const workerSessionId of workerSessionIds) {
@@ -3897,7 +3917,7 @@ function CollapsedView({
}
}
return next;
- }, [runningSessionIds, backgroundActivitySessionIds, orcaLeadWorkerMap]);
+ }, [runningSessionIds, backgroundActivitySessionIds, startingSessionIds, orcaLeadWorkerMap]);
return (
<div
diff --git a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
index 99eb128df9..530f4eb6d2 100644
--- a/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/NewMakerDraftRoute.tsx
@@ -127,6 +127,7 @@ import {
import { showWorktreeError } from '@/lib/worktreeToast';
import * as sessionService from '@/lib/sessionService';
import { sessionsStore } from '@/lib/sessionsStore';
+import { clearSessionStarting, markSessionStarting } from '@/lib/sessionStartingStore';
import { emitAutoTitlePreview, emitAutoTitlePreviewCleared } from '@/lib/sessionsBus';
import { NewGoalDialog } from '@/components/new-chat/NewGoalDialog';
import { cleanupStagedChatAttachmentFiles } from '@/lib/chatAttachmentStageCleanup';
@@ -3392,6 +3393,7 @@ export function NewMakerDraftRoute() {
// (PR #1031 review P1;worktree 与 goal 两条路径各有自己的撤回点)。
let optimisticTitleSessionId: string | null = null;
let remoteOptimisticTitleSessionId: string | null = null;
+ let markedStartingSessionId: string | null = null;
const autoTitleLabels = {
image: t('ccAgent.autoTitle.image'),
file: t('ccAgent.autoTitle.file'),
@@ -3653,6 +3655,7 @@ export function NewMakerDraftRoute() {
nowIso: new Date().toISOString(),
logTag: 'draft send',
});
+ markedStartingSessionId = remoteSessionId;
// 草稿里选中的那条收藏跟着会话走(见 carryDraftFavoriteAnchorToSession)。锚点是
// **控制端的 UI 态**,与被控端无关:按对端会话 id 记在本机即可,不进任何 payload。
// 用 createArgs 里**实际提交**的 model / providerId(远程分支会按被控端目录校准)。
@@ -3799,6 +3802,8 @@ export function NewMakerDraftRoute() {
userSendAt: sendAt.toISOString(),
updatedAt: sendAt.toISOString(),
});
+ markSessionStarting(newSession.id);
+ markedStartingSessionId = newSession.id;
sessionService.touchUserSend(newSession.id, sendAt.getTime()).catch((err) => {
log.warn('[draft worktree send] touchUserSend failed', err);
});
@@ -3844,6 +3849,8 @@ export function NewMakerDraftRoute() {
// 会话永久显示一句**没发出去**的话(PR #1031 review P1)。
// 放在这里而不是各 return 前:所有「交接失败 → 还原草稿」的分支都过这一处。
emitAutoTitlePreviewCleared(newSession.id);
+ // 首条没发出去:撤销发送当下的 starting,避免未开始的任务钉在运行中档。
+ clearSessionStarting(newSession.id);
};
try {
rehomedFiles = await rehomeDraftAttachments(files, newSession.id);
@@ -4052,6 +4059,8 @@ export function NewMakerDraftRoute() {
{
const iso = new Date().toISOString();
sessionsStore.patchLocal(newSession.id, { userSendAt: iso, updatedAt: iso });
+ markSessionStarting(newSession.id);
+ markedStartingSessionId = newSession.id;
}
// F-COLLAB: draft 阶段开了协同模式 → createSession 之后立刻 enableOrca
@@ -4128,6 +4137,7 @@ export function NewMakerDraftRoute() {
if (remoteOptimisticTitleSessionId) {
remoteProjectsStore.clearPendingTitlePreview(remoteOptimisticTitleSessionId);
}
+ if (markedStartingSessionId) clearSessionStarting(markedStartingSessionId);
if (isRemotePrecreatedWorktreeOwnerChangedError(err)) return;
log.error('[draft send]', err);
toast.error(
@@ -4456,6 +4466,7 @@ export function NewMakerDraftRoute() {
if (!remoteSessionId) {
throw new Error(t('ccAgent.draft.createSessionFailed'));
}
+ goalSessionId = remoteSessionId;
{
const optimisticGoalTitle = normalizeAutoTitle(objective);
if (optimisticGoalTitle) {
@@ -4677,6 +4688,7 @@ export function NewMakerDraftRoute() {
{
const iso = new Date().toISOString();
sessionsStore.patchLocal(newSession.id, { userSendAt: iso, updatedAt: iso });
+ markSessionStarting(newSession.id);
}
// 草稿开了协同 → 新建目标路径也要拉起 Worker(与 Send 路径同口径);否则用户开了协同
// 却走「新建目标」会得到一个没有 Worker 的 lead session(codex P2)。失败 toast + 降级
@@ -4725,6 +4737,7 @@ export function NewMakerDraftRoute() {
// 不撤回的话标题预览会永久盖着 DB 里的哨兵(理由同 worktree 分支的
// restoreFirstMessageDraft)。异常照旧抛给调用方展示。
if (optimisticGoalTitle) emitAutoTitlePreviewCleared(newSession.id);
+ clearSessionStarting(newSession.id);
if (deferredUiAssignment) {
toast.error(t('newChat.collaboration.assignmentFailed'));
}
@@ -4743,6 +4756,7 @@ export function NewMakerDraftRoute() {
// 预览在 createSession 之前登记。worktree 建议名 / 建树 / 回滚失败都走这里,
// 不撤回会让空会话或未建成的 goalSessionId 一直顶着目标原文。
if (goalSessionId && optimisticGoalTitle) emitAutoTitlePreviewCleared(goalSessionId);
+ if (goalSessionId) clearSessionStarting(goalSessionId);
if (isLocalGoalWorktreeCleanupPendingError(error)) {
log.error('[draft goal] incomplete local worktree session cleanup failed', {
setupError: error.setupError,
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts b/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
index 29913235a3..88831a28d7 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
@@ -46,6 +46,10 @@ export type MainListEntry =
/** 优先级排序的运行时上下文(组装层的运行中 / 需关注集合)。 */
export interface MainListPriorityContext {
+ /**
+ * 运行中档。组装层会把「刚发送、agent 还没 isRunning」的 starting 会话并进来,
+ * 让新任务立刻排在运行中档顶,而不是先沉到其余档再跳上来。
+ */
runningSessionIds: ReadonlySet<string>;
/** 需关注(等待确认 / 完成未读等 attention 通知)的 sessionIds。 */
attentionSessionIds: ReadonlySet<string>;
diff --git a/apps/desktop/src/renderer/features/cc-agent/remoteSessionHandoff.ts b/apps/desktop/src/renderer/features/cc-agent/remoteSessionHandoff.ts
index c903b7f850..8a3b68bb2c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/remoteSessionHandoff.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/remoteSessionHandoff.ts
@@ -27,6 +27,7 @@
import { refreshRemoteDeviceSessions } from '@/features/device-link/refreshRemoteSessions';
import { remoteProjectsStore } from '@/features/device-link/remoteProjectsStore';
import { createLogger } from '@/lib/logger';
+import { markSessionStarting } from '@/lib/sessionStartingStore';
import { buildProvisionalRemoteSession, type DeviceLinkCreateArgs } from './deviceLinkCreateArgs';
@@ -67,6 +68,8 @@ export interface RemoteSessionHandoffParams {
export function commitRemoteSessionHandoff(p: RemoteSessionHandoffParams): void {
// ① 归属先落地:回流失败时它是首条消息能路由到对端的唯一依据。
remoteProjectsStore.pinSessionOrigin(p.deviceId, p.remoteSessionId);
+ // 刚提交的远程任务在对端 isRunning 回流前先按运行中排序,避免先沉底再跳顶。
+ markSessionStarting(p.remoteSessionId);
// ② 临时行:让 SessionView 的 delayed-create 交接不必等权威快照。
if (p.workDir) {
remoteProjectsStore.mergeDeviceSessions(p.deviceId, p.deviceName, [
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
index 4b879515d7..37e773a2b8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
@@ -82,8 +82,10 @@ import { useSessionAttentionKinds } from '@/lib/sessionAttentionStore';
import { useSessionAttentionUrgencySet } from '../../contexts/SessionAttentionUrgencyContext';
import {
getRemoteSessionActivity,
+ isRemoteSessionActivityActive,
useRemoteSessionActivityRevision,
} from '@/features/device-link/remoteSessionActivityStore';
+import { absorbSessionStarting } from '@/lib/sessionStartingStore';
import type { DialogueDeviceTarget } from '../../lib/dialogueCreateTarget';
import { MainListScopeHeader } from '../MainListScopeHeader';
import { SectionCollapse } from '../SectionCollapse';
@@ -464,6 +466,26 @@ export function ProjectsSection({
viewedIdForSort,
]);
+ // starting 只让位给真实 in-flight:本地 isRunning(见 useStartingSessionIds),
+ // 远程 running / needs-interaction。终态 attention 不再吸收 —— 旧终态会误伤
+ // 新发送,新终态又要代次才能和旧的区分,两边补丁会来回打。没经过 running
+ // 的快完成靠 TTL。
+ useEffect(() => {
+ const settled = new Set<string>();
+ const considerRemote = (session: Session) => {
+ if (isRemoteSessionActivityActive(getRemoteSessionActivity(session.id))) {
+ settled.add(session.id);
+ }
+ };
+ for (const project of projects) {
+ for (const session of project.sessions) considerRemote(session);
+ }
+ for (const session of dialogues) considerRemote(session);
+ for (const session of unclassified) considerRemote(session);
+ absorbSessionStarting(settled);
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- remoteActivityRevision 代表 getRemoteSessionActivity 读到的整表内容
+ }, [projects, dialogues, unclassified, remoteActivityRevision]);
+
// E 期「按设备分组」:有远程设备连接 + 开关开 → 按设备切段(本机在前,
// 远程按设备切换栏顺序);其余情况单段直渲。切段后按当前排序重排本段。
// 自定义项目顺序可以和设备分组叠加:每段内项目行按全局序的子集排,段内可拖。
diff --git a/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts b/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
index ba8c198660..84c86bb124 100644
--- a/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
+++ b/apps/desktop/src/renderer/features/device-link/remoteSessionActivityStore.ts
@@ -120,6 +120,14 @@ export function applyRemoteSessionActivity(deviceId: string, payload: unknown):
emit();
}
+/** 刚发送时丢掉上一轮 completed/error 镜像。running / needs-interaction 是本轮活档,保留。 */
+export function dropStaleRemoteTerminalActivity(sessionId: string): void {
+ const activity = activityMap.get(sessionId);
+ if (!activity) return;
+ if (activity.phase !== 'completed' && activity.phase !== 'error') return;
+ removeRemoteSessionActivityEntry(sessionId);
+}
+
/** 单会话清除(被控端删除 / 归档该会话时由 sessions:patched 路由调用)。 */
export function removeRemoteSessionActivityEntry(sessionId: string): void {
sessionDeviceIndex.delete(sessionId);
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index c607e98300..a73278446d 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -121,6 +121,7 @@ import { setMirrorEffort, setMirrorFast } from '@/state/deviceLinkModelMirror';
import type { AgentKind } from '@/hooks/useAgentCapabilities';
import type { Effort } from '@/lib/userPreferences.types';
import { emitAutoTitlePreview, emitAutoTitlePreviewCleared, emitPatch } from '@/lib/sessionsBus';
+import { clearSessionStarting, markSessionStarting } from '@/lib/sessionStartingStore';
import { createLogger } from '@/lib/logger';
import {
markSessionAutomaticHistoryLoadCompleted,
@@ -9317,6 +9318,10 @@ function settleRemoteOptimisticFailure(sessionId: string, clientId: string, erro
// Retire the outbox ref afterwards so media protection transfers without a
// cleanup-eligible gap in main's renderer registry.
clearRemoteOptimisticSend(sessionId, clientId);
+ // 同会话还有其它乐观发送在飞时不能清 starting,否则后一条会提前退出运行中档。
+ if (!remoteOptimisticSendRecords(sessionId)?.size) {
+ clearSessionStarting(sessionId);
+ }
setState(sessionId, (s) => ({
...s,
pendingQueue: s.pendingQueue.filter((item) => item.clientId !== clientId),
@@ -11440,6 +11445,8 @@ function touchSessionUserSend(sessionId: string, workingDir: string, wasFirst: b
? { workingDir, userSendAt: userSendAtIso, updatedAt: userSendAtIso }
: { userSendAt: userSendAtIso, updatedAt: userSendAtIso },
);
+ // 侧栏优先级在真实 isRunning 之前先把刚发送的任务当成 running,避免先沉底再跳顶。
+ markSessionStarting(sessionId);
}
/**
@@ -11937,6 +11944,15 @@ function sendMessage(
),
);
},
+ ).then(
+ (ok) => {
+ if (!ok) clearSessionStarting(sessionId);
+ return ok;
+ },
+ (err) => {
+ clearSessionStarting(sessionId);
+ throw err;
+ },
);
}
@@ -12114,6 +12130,16 @@ async function sendMessageCore(
}
const applied = applyInputProjectionOperationResponse(sessionId, operation, projection);
if (applied) markSessionHasUserMessage(sessionId);
+ // 暂停 / 输入锁 / 凭证切换等待只把消息收下,不会马上派发。starting
+ // 表示「预期会跑」,不能把明确未派发的任务标成运行中。
+ if (
+ projection.pendingQueue.some((item) => item.clientId === queued.clientId)
+ && (projection.queuePaused
+ || Boolean(projection.credentialSwitchWait)
+ || projection.queueInteractionLocks.length > 0)
+ ) {
+ clearSessionStarting(sessionId);
+ }
return true;
})
.catch((err) => {
diff --git a/apps/desktop/src/renderer/lib/sessionStartingStore.ts b/apps/desktop/src/renderer/lib/sessionStartingStore.ts
new file mode 100644
index 0000000000..1e3e1776ba
--- /dev/null
+++ b/apps/desktop/src/renderer/lib/sessionStartingStore.ts
@@ -0,0 +1,115 @@
+/**
+ * sessionStartingStore —— 「用户已按下发送、agent 尚未进入 isRunning」的会话集合。
+ *
+ * 侧栏按优先级排序时,running 档只认 makerChatStore 的真实 isRunning。新建 /
+ * 刚发送的任务在 worktree、hydrate、enqueue、进程拉起这段空窗里还是 rest,
+ * 会先沉到所有运行中任务下面,等真正跑起来再跳到 running 档顶 —— 列表自己
+ * 抖一下。这里把「我已经发出去了」提前记成 starting,组装层并进 display
+ * running,排序和呼吸点与运行中同档,但不碰 isRunning(done 通知 / 归档闸门 /
+ * LRU 仍只认真 running)。
+ *
+ * 生命周期:乐观 userSendAt / sendMessage 置位;真实 running、远程权威状态、
+ * 发送失败或 TTL 清除。
+ */
+
+import { useEffect, useSyncExternalStore } from 'react';
+
+import { dropStaleRemoteTerminalActivity } from '@/features/device-link/remoteSessionActivityStore';
+
+/** 发送失败 / 状态一直不到时的兜底;正常路径应在 agent 开跑时就被吸收。 */
+export const SESSION_STARTING_TTL_MS = 120_000;
+
+const listeners = new Set<() => void>();
+const startingIds = new Set<string>();
+const timers = new Map<string, ReturnType<typeof setTimeout>>();
+/** 不可变快照,只在 emit 时重建 —— 无变化时返回同一引用。 */
+let snapshot: ReadonlySet<string> = new Set();
+
+function emit(): void {
+ snapshot = new Set(startingIds);
+ for (const listener of listeners) listener();
+}
+
+function clearTimer(sessionId: string): void {
+ const timer = timers.get(sessionId);
+ if (timer === undefined) return;
+ clearTimeout(timer);
+ timers.delete(sessionId);
+}
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
+
+export function getStartingSessionIds(): ReadonlySet<string> {
+ return snapshot;
+}
+
+/** 用户已提交发送。重复标记只刷新 TTL,不抖快照。 */
+export function markSessionStarting(sessionId: string): void {
+ if (!sessionId) return;
+ const already = startingIds.has(sessionId);
+ if (!already) {
+ // 先丢掉上一轮远程终态,再置 starting。否则 absorb 会把旧 completed/error
+ // 当成新权威立刻清掉。重复 mark 只刷新 TTL,不能再删本轮新到达的终态。
+ dropStaleRemoteTerminalActivity(sessionId);
+ startingIds.add(sessionId);
+ }
+ clearTimer(sessionId);
+ timers.set(
+ sessionId,
+ setTimeout(() => {
+ timers.delete(sessionId);
+ if (!startingIds.delete(sessionId)) return;
+ emit();
+ }, SESSION_STARTING_TTL_MS),
+ );
+ if (!already) emit();
+}
+
+export function clearSessionStarting(sessionId: string): void {
+ if (!sessionId) return;
+ clearTimer(sessionId);
+ if (!startingIds.delete(sessionId)) return;
+ emit();
+}
+
+/** 会话已有权威活档(真 running / 等你处理 / 完成未读 / 远程状态)时收掉 starting。 */
+export function absorbSessionStarting(settledSessionIds: Iterable<string>): void {
+ let changed = false;
+ for (const sessionId of settledSessionIds) {
+ if (!startingIds.has(sessionId)) continue;
+ clearTimer(sessionId);
+ startingIds.delete(sessionId);
+ changed = true;
+ }
+ if (changed) emit();
+}
+
+/**
+ * 当前 starting 集合。传入 settledSessionIds 时,在 effect 里吸收已经有权威
+ * 状态的 id —— 调用方应传**真** running / attention,不要传已经并进 starting
+ * 的 display running,否则会立刻把自己清掉。
+ */
+export function useStartingSessionIds(
+ settledSessionIds?: ReadonlySet<string>,
+): ReadonlySet<string> {
+ const starting = useSyncExternalStore(subscribe, getStartingSessionIds, getStartingSessionIds);
+ useEffect(() => {
+ if (!settledSessionIds || settledSessionIds.size === 0) return;
+ absorbSessionStarting(settledSessionIds);
+ }, [settledSessionIds, starting]);
+ return starting;
+}
+
+/** 测试收尾。 */
+export function resetSessionStartingStoreForTests(): void {
+ for (const timer of timers.values()) clearTimeout(timer);
+ timers.clear();
+ startingIds.clear();
+ snapshot = new Set();
+ listeners.clear();
+}