Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/cli/src/acp-integration/session/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8813,6 +8813,11 @@ export class Session implements SessionContext {
throw new Error(unsupportedError);
}

case 'goal_control':
throw new Error(
'Canonical Goal control is not available in ACP integration yet.',
);

case 'no_command':
// No command was found or executed, resolve the original prompt
// through the standard path that handles all block types. promptLast
Expand Down
109 changes: 109 additions & 0 deletions packages/cli/src/nonInteractive/io/StreamJsonOutputAdapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import type {
Config,
GoalSnapshotV2,
ServerGeminiStreamEvent,
} from '@qwen-code/qwen-code-core';
import { GeminiEventType } from '@qwen-code/qwen-code-core';
Expand All @@ -20,6 +21,23 @@ function createMockConfig(): Config {
} as unknown as Config;
}

const goalSnapshot: GoalSnapshotV2 = {
v: 2,
activity: 'running',
goal: {
goalId: 'goal-1',
revision: 2,
objective: 'finish the refactor',
status: 'active',
evidenceCursor: { recordId: 'record-1' },
turnCount: 3,
activeTimeMs: 12_000,
createdAt: 1,
updatedAt: 2,
lastReason: 'keep going',
},
};

describe('StreamJsonOutputAdapter', () => {
let adapter: StreamJsonOutputAdapter;
let mockConfig: Config;
Expand Down Expand Up @@ -153,6 +171,67 @@ describe('StreamJsonOutputAdapter', () => {
]);
});

it('emits v2 goal_state before the gated legacy projection', () => {
adapter.processEvent({
type: GeminiEventType.GoalState,
value: goalSnapshot,
cause: 'edit',
});
adapter.processEvent({
type: GeminiEventType.ActiveGoal,
value: {
condition: 'finish the refactor',
iterations: 3,
setAt: 1,
tokensAtStart: 0,
hookId: 'goal-v2:goal-1:2',
lastReason: 'keep going',
},
});

const goalEvents = stdoutWriteSpy.mock.calls
.map((call: unknown[]) => JSON.parse(call[0] as string))
.filter(
(message: { type?: string; event?: { type?: string } }) =>
message.type === 'stream_event' &&
(message.event?.type === 'goal_state' ||
message.event?.type === 'active_goal'),
);

expect(
goalEvents.map(
(message: { event: { type: string } }) => message.event.type,
),
).toEqual(['goal_state', 'active_goal']);
expect(goalEvents[0]).toMatchObject({
session_id: 'test-session-id',
parent_tool_use_id: null,
event: {
type: 'goal_state',
goal_state: goalSnapshot,
},
});
});

it('does not emit duplicate v2 goal snapshots from overlapping sources', () => {
adapter.processEvent({
type: GeminiEventType.GoalState,
value: goalSnapshot,
});
adapter.processEvent({
type: GeminiEventType.GoalState,
value: structuredClone(goalSnapshot),
});

const goalEvents = stdoutWriteSpy.mock.calls
.map((call: unknown[]) => JSON.parse(call[0] as string))
.filter(
(message: { event?: { type?: string } }) =>
message.event?.type === 'goal_state',
);
expect(goalEvents).toHaveLength(1);
});

it('should emit message_start event on first content', () => {
adapter.processEvent({
type: GeminiEventType.Content,
Expand Down Expand Up @@ -302,6 +381,36 @@ describe('StreamJsonOutputAdapter', () => {
expect(activeGoalEventCall).toBeUndefined();
});

it('still emits v2 goal_state without the partial-message gate', () => {
adapter.processEvent({
type: GeminiEventType.GoalState,
value: goalSnapshot,
cause: 'edit',
});
adapter.processEvent({
type: GeminiEventType.ActiveGoal,
value: {
condition: 'finish the refactor',
iterations: 3,
setAt: 1,
tokensAtStart: 0,
hookId: 'goal-v2:goal-1:2',
lastReason: 'keep going',
},
});

const events = stdoutWriteSpy.mock.calls
.map((call: unknown[]) => JSON.parse(call[0] as string))
.filter(
(message: { type?: string }) => message.type === 'stream_event',
);
expect(events).toHaveLength(1);
expect(events[0].event).toEqual({
type: 'goal_state',
goal_state: goalSnapshot,
});
});

it('should still emit final assistant message', () => {
adapter.startAssistantMessage();
adapter.processEvent({
Expand Down
19 changes: 19 additions & 0 deletions packages/cli/src/nonInteractive/io/StreamJsonOutputAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export class StreamJsonOutputAdapter
implements JsonOutputAdapterInterface
{
private mainTurnMessageStartEmitted = false;
private lastGoalStateSignature: string | undefined;
private readonly outputStream: NodeJS.WritableStream;

constructor(
Expand Down Expand Up @@ -126,6 +127,24 @@ export class StreamJsonOutputAdapter
}

override processEvent(event: ServerGeminiStreamEvent): void {
if (event.type === GeminiEventType.GoalState) {
const signature = JSON.stringify(event.value);
if (signature === this.lastGoalStateSignature) return;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] Prevent the second source from replaying stale canonical Goal states. runNonInteractive subscribes directly to the runtime through observeGoalRuntime, while Core's sendMessageStream also subscribes and later drains the same queued GoalState sequence. This comparison removes only consecutive duplicates. On a no-tool active Goal segment, finishTurn broadcasts idle and synchronously schedules the next permit/broadcasts running; the direct listener emits both, then Core drains its queued copy. A probe against this exact head produced idle → running → idle → running, so a consumer treating goal_state as authoritative regresses from running to stale idle and processes both transitions twice. Please make one source authoritative (while preserving explicit status/no-model emission), or dedupe using source/transition sequencing rather than only the last payload, and add a regression where source A emits [idle, running] before source B replays [idle, running].

中文说明

[严重] 防止第二个事件源重放陈旧的 canonical Goal 状态。 runNonInteractive 通过 observeGoalRuntime 直接订阅 runtime,而 Core 的 sendMessageStream 也会订阅并在稍后排空同一组 GoalState。这里仅能去掉相邻重复。在没有工具调用的 active Goal segment 结束时,finishTurn 会先广播 idle,随后同步调度下一个 permit 并广播 running;直订阅先输出两者,然后 Core 再排空其缓存副本。在当前精确 head 上的最小复现实际得到 idle → running → idle → running,因此把 goal_state 当作权威状态的消费者会从 running 倒退到陈旧 idle,并重复处理两次状态转换。请让一个来源成为权威来源(同时保留显式 status/no-model 输出),或按来源/转换序列去重,而不是只比较最后一个 payload;并补一个回归测试:来源 A 先输出 [idle, running],来源 B 随后重放 [idle, running]。

this.lastGoalStateSignature = signature;
const partial: CLIPartialAssistantMessage = {
type: 'stream_event',
uuid: randomUUID(),
session_id: this.getSessionId(),
parent_tool_use_id: null,
event: {
type: 'goal_state',
goal_state: event.value,
},
};
this.emitMessageImpl(partial);
return;
}

// Active goal updates are session-level metadata, not message content.
// They intentionally bypass the base finalized guard so late goal state
// changes can still reach stream consumers.
Expand Down
7 changes: 7 additions & 0 deletions packages/cli/src/nonInteractive/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type {
ActiveGoal,
GoalSnapshotV2,
SubagentConfig,
McpToolProgressData,
ShellProgressData,
Expand Down Expand Up @@ -254,13 +255,19 @@ export interface ActiveGoalStreamEvent {
active_goal: ActiveGoal | null;
}

export interface GoalStateStreamEvent {
type: 'goal_state';
goal_state: GoalSnapshotV2;
}

export type StreamEvent =
| MessageStartStreamEvent
| ContentBlockStartEvent
| ContentBlockDeltaEvent
| ContentBlockStopEvent
| MessageStopStreamEvent
| ToolProgressStreamEvent
| GoalStateStreamEvent
| ActiveGoalStreamEvent;

export interface CLIPartialAssistantMessage {
Expand Down
Loading
Loading