Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
127 changes: 127 additions & 0 deletions packages/acp-bridge/src/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5997,6 +5997,133 @@ describe('createHttpAcpBridge', () => {
});
});

describe('extNotification — in-session model update (A1, #4511)', () => {
it('promotes current_model_update to model_switched when no bridge roundtrip is in flight', async () => {
let capturedConn: AgentSideConnection | undefined;
const factory: ChannelFactory = async () => {
const { clientStream, agentStream } = createInMemoryChannel();
const fakeAgent = new FakeAgent();
capturedConn = new AgentSideConnection(() => fakeAgent, agentStream);
return {
stream: clientStream,
exited: new Promise<
| { exitCode: number | null; signalCode: NodeJS.Signals | null }
| undefined
>(() => {}),
kill: async () => {},
killSync: () => {},
};
};
const bridge = makeBridge({ channelFactory: factory });
const session = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
const abort = new AbortController();
const iter = bridge.subscribeEvents(session.sessionId, {
signal: abort.signal,
});

void capturedConn!.extNotification('qwen/notify/session/model-update', {
v: 1,
sessionId: session.sessionId,
currentModelId: 'qwen-max',
previousModelId: 'qwen-plus',
});

const collected: Array<{ type: string; data: unknown }> = [];
for await (const e of iter) {
collected.push({ type: e.type, data: e.data });
if (collected.length === 1) break;
}
// Promoted to model_switched with currentModelId mapped to modelId.
expect(collected[0]?.type).toBe('model_switched');
expect(collected[0]?.data).toEqual({
sessionId: session.sessionId,
modelId: 'qwen-max',
});
abort.abort();
await bridge.shutdown();
});

it('suppresses current_model_update while a bridge model roundtrip is in flight', async () => {
// Hang the agent's unstable_setSessionModel so the bridge roundtrip
// stays in flight (modelRoundtripInFlight = true). The concurrent
// in-session current_model_update must be suppressed; only the bridge's
// own model_switched (after the roundtrip) reaches the bus.
let releaseModel: (() => void) | undefined;
let capturedConn: AgentSideConnection | undefined;
const factory: ChannelFactory = async () => {
const { clientStream, agentStream } = createInMemoryChannel();
const fakeAgent = new FakeAgent();
const augmented = new Proxy(fakeAgent, {
get(target, prop) {
if (prop === 'unstable_setSessionModel') {
return () =>
new Promise<Record<string, never>>((res) => {
releaseModel = () => res({});
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return (target as any)[prop];
},
});
capturedConn = new AgentSideConnection(
() => augmented as Agent,
agentStream,
);
return {
stream: clientStream,
exited: new Promise<
| { exitCode: number | null; signalCode: NodeJS.Signals | null }
| undefined
>(() => {}),
kill: async () => {},
killSync: () => {},
};
};
const bridge = makeBridge({ channelFactory: factory });
const session = await bridge.spawnOrAttach({ workspaceCwd: WS_A });
const abort = new AbortController();
const iter = bridge.subscribeEvents(session.sessionId, {
signal: abort.signal,
});

// Start a bridge-driven model change; it hangs → roundtrip in flight.
const modelChange = bridge
.setSessionModel(
session.sessionId,
{ sessionId: session.sessionId, modelId: 'qwen-max' },
undefined,
)
.catch(() => {});
await new Promise((r) => setTimeout(r, 10));

// Concurrent in-session notification — must be SUPPRESSED.
void capturedConn!.extNotification('qwen/notify/session/model-update', {
v: 1,
sessionId: session.sessionId,
currentModelId: 'qwen-turbo',
});
await new Promise((r) => setTimeout(r, 10));

// Release the hung roundtrip → the bridge publishes its authoritative one.
releaseModel?.();
await modelChange;

const collected: Array<{ type: string; data: unknown }> = [];
for await (const e of iter) {
collected.push({ type: e.type, data: e.data });
if (collected.length === 1) break;
}
// Exactly the bridge's model_switched (qwen-max) — the suppressed
// qwen-turbo notification did NOT produce a second model_switched.
expect(collected[0]?.type).toBe('model_switched');
expect((collected[0]?.data as { modelId?: string }).modelId).toBe(
'qwen-max',
);
abort.abort();
await bridge.shutdown();
});
});

describe('maxSessions cap (chiga0 Rec 3)', () => {
it('refuses NEW spawns past the cap with SessionLimitExceededError', async () => {
let n = 0;
Expand Down
45 changes: 35 additions & 10 deletions packages/acp-bridge/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,16 @@ interface SessionEntry {
* failures swallowed at the tail like `promptQueue`.
*/
modelChangeQueue: Promise<void>;
/**
* A1 (#4511): true while the bridge is driving a model roundtrip
* (`setSessionModel` / `applyModelServiceId`) for this session. The
* `current_model_update` extNotification demux in `BridgeClient` reads this
* to SUPPRESS promotion of the agent's notification during a bridge-driven
* change — the bridge publishes the authoritative `model_switched` itself,
* so promoting the notification too would double-publish. In-session
* `/model` (no bridge roundtrip) sees this false and IS promoted.
*/
modelRoundtripInFlight?: boolean;
/**
* Cached "transport closed" promise. The first `sendPrompt` on a
* session lazy-builds this from `channel.exited.then(throw)`; every
Expand Down Expand Up @@ -1166,6 +1176,11 @@ export function createHttpAcpBridge(opts: BridgeOptions): HttpAcpBridge {
// wedges the HTTP handler for 10s.
const transportClosed = getTransportClosedReject(entry);
const work = entry.modelChangeQueue.then(async () => {
// A1: mark a bridge-driven model roundtrip so the agent's
// `current_model_update` extNotification (this path also drives
// `Session.setModel`, which emits it) is suppressed by the demux —
// the authoritative `model_switched` is published below.
entry.modelRoundtripInFlight = true;
try {
await Promise.race([
withTimeout(
Expand Down Expand Up @@ -1197,6 +1212,8 @@ export function createHttpAcpBridge(opts: BridgeOptions): HttpAcpBridge {
...(originatorClientId ? { originatorClientId } : {}),
});
throw err;
} finally {
Comment thread
chiga0 marked this conversation as resolved.
Resolved
entry.modelRoundtripInFlight = false;
}
});
// Tail swallows failures so subsequent model changes still run; the
Expand Down Expand Up @@ -2849,16 +2866,24 @@ export function createHttpAcpBridge(opts: BridgeOptions): HttpAcpBridge {
// `model_switch_failed`). Both depend on ACP exposing a cancel
// signal for `unstable_setSessionModel`.
const transportClosed = getTransportClosedReject(entry);
const work = entry.modelChangeQueue.then(() =>
Promise.race([
withTimeout(
conn.unstable_setSessionModel(normalized),
initTimeoutMs,
'setSessionModel',
),
transportClosed,
]),
);
const work = entry.modelChangeQueue.then(async () => {
// A1: suppress the agent's current_model_update notification (this
// path drives Session.setModel, which emits it) while the bridge
// owns the change — the bridge publishes model_switched below.
entry.modelRoundtripInFlight = true;
Comment thread
chiga0 marked this conversation as resolved.
Resolved
Comment thread
chiga0 marked this conversation as resolved.
Resolved
try {
return await Promise.race([
withTimeout(
conn.unstable_setSessionModel(normalized),
initTimeoutMs,
'setSessionModel',
),
transportClosed,
]);
} finally {
entry.modelRoundtripInFlight = false;
}
});
// Tail-swallow on the queue so a model-change failure doesn't poison
// every subsequent change (matches `applyModelServiceId`'s pattern).
entry.modelChangeQueue = work.then(
Expand Down
65 changes: 65 additions & 0 deletions packages/acp-bridge/src/bridgeClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,13 @@ export interface BridgeClientSessionEntry {
events: EventBus;
pendingPermissionIds: Set<string>;
activePromptOriginatorClientId?: string;
/**
* A1 (#4511): true while the bridge drives a model roundtrip; the
* `current_model_update` extNotification demux reads it to suppress
* promotion during a bridge-driven change. Set on the full `SessionEntry`
* in `bridge.ts`; surfaced here for the demux.
*/
modelRoundtripInFlight?: boolean;
}

/**
Expand Down Expand Up @@ -492,6 +499,17 @@ export class BridgeClient implements Client {
method: string,
params: Record<string, unknown>,
): Promise<void> {
// A1 (#4511): demux an in-session model switch to a `model_switched`
// bus event. `current_model_update` is not an ACP SessionUpdate variant,
// so the agent emits it over this side-channel; the bridge promotes it
// here — except while the bridge itself is driving the change (the HTTP
// path also flows through Session.setModel), where it publishes
// `model_switched` authoritatively and this notification is suppressed to
// avoid a double publish.
if (method === 'qwen/notify/session/model-update') {
Comment thread
chiga0 marked this conversation as resolved.
Resolved
Comment thread
chiga0 marked this conversation as resolved.
Resolved
this.handleInSessionModelUpdate(params);
return;
}
if (method !== 'qwen/notify/session/mcp-budget-event') return;
const sessionId = params['sessionId'];
if (typeof sessionId !== 'string') return;
Expand Down Expand Up @@ -531,6 +549,53 @@ export class BridgeClient implements Client {
this.bufferEarlyEvent(sessionId, frame);
}

/**
* A1 (#4511): promote an in-session `current_model_update` extNotification
* to a `model_switched` bus event (field mapping: `currentModelId` →
* `data.modelId`, `sessionId` → `data.sessionId`). Suppressed while the
* bridge is driving its own model roundtrip (`entry.modelRoundtripInFlight`)
* — there the bridge publishes the authoritative `model_switched`, so
* promoting here too would double-publish. A structured log records the
* decision so the `dropped` case is observable.
*/
private handleInSessionModelUpdate(params: Record<string, unknown>): void {
const sessionId = params['sessionId'];
Comment thread
chiga0 marked this conversation as resolved.
Resolved
const currentModelId = params['currentModelId'];
if (typeof sessionId !== 'string' || typeof currentModelId !== 'string') {
return;
}
const entry = this.resolveEntry(sessionId);
if (!entry) {
// No live session — a model switch only happens on an established
// session, so unlike the MCP-budget path there is nothing to buffer.
writeStderrLine(
`[demux] session=${sessionId} type=current_model_update action=dropped reason=no_entry`,
);
return;
}
if (entry.modelRoundtripInFlight) {
// Bridge owns this change and will publish model_switched itself.
writeStderrLine(
`[demux] session=${sessionId} type=current_model_update action=suppressed reason=bridge_roundtrip_in_flight`,
);
return;
}
try {
entry.events.publish({
type: 'model_switched',
data: { sessionId, modelId: currentModelId },
...(entry.activePromptOriginatorClientId
? { originatorClientId: entry.activePromptOriginatorClientId }
: {}),
});
writeStderrLine(
Comment thread
chiga0 marked this conversation as resolved.
Resolved
Comment thread
chiga0 marked this conversation as resolved.
Resolved
`[demux] session=${sessionId} type=current_model_update action=promoted model=${currentModelId}`,
);
} catch {
/* bus closed */
}
}

/**
* PR 14b fix #1: enqueue `frame` for `sessionId`. Lazy TTL sweep
* runs first so caller doesn't pay for stale entries before
Expand Down
30 changes: 30 additions & 0 deletions packages/cli/src/acp-integration/session/Session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,36 @@ describe('Session', () => {
);
});

it('emits a current_model_update extNotification after switching (A1)', async () => {
await session.setModel({
sessionId: 'test-session-id',
modelId: `qwen3-coder-plus(${AuthType.USE_OPENAI})`,
});

expect(mockClient.extNotification).toHaveBeenCalledWith(
'qwen/notify/session/model-update',
expect.objectContaining({
v: 1,
sessionId: 'test-session-id',
currentModelId: 'qwen3-coder-plus',
}),
);
});

it('does NOT emit the model-update notification when the switch fails (A1)', async () => {
switchModelSpy.mockRejectedValueOnce(new Error('switch boom'));
await expect(
session.setModel({
sessionId: 'test-session-id',
modelId: `qwen3-coder-plus(${AuthType.USE_OPENAI})`,
}),
).rejects.toThrow();
expect(mockClient.extNotification).not.toHaveBeenCalledWith(
'qwen/notify/session/model-update',
expect.anything(),
);
});

it('rejects empty/whitespace model IDs', async () => {
await expect(
session.setModel({
Expand Down
27 changes: 27 additions & 0 deletions packages/cli/src/acp-integration/session/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1598,6 +1598,10 @@ export class Session implements SessionContext {
);
}

// Capture the pre-switch model so the notification can carry
// `previousModelId`. Read BEFORE `switchModel` mutates it.
const previousModelId = this.config.getModel();

await this.config.switchModel(
selectedAuthType,
parsed.modelId,
Expand All @@ -1607,6 +1611,29 @@ export class Session implements SessionContext {
: undefined,
);

// A1 (#4511): notify attached clients of an in-session model switch so a
// `/model` slash command or plan-mode change reaches the bus (today only
// the HTTP `POST /session/:id/model` path publishes `model_switched`).
// `current_model_update` is NOT an ACP `SessionUpdate` variant (the type
// is the external @agentclientprotocol/sdk union, which has
// `current_mode_update` but not a model equivalent), so this goes over
// the agent→bridge `extNotification` side-channel. The bridge demuxes it
// to `model_switched` and SUPPRESSES it when the bridge itself is driving
// the change (the HTTP path also flows through this method), avoiding a
// double publish. Fire-and-forget, matching the MCP-budget extNotification.
void this.client
.extNotification('qwen/notify/session/model-update', {
v: 1,
sessionId: this.sessionId,
currentModelId: parsed.modelId,
...(previousModelId && previousModelId !== parsed.modelId
? { previousModelId }
Comment thread
chiga0 marked this conversation as resolved.
Resolved
Comment thread
chiga0 marked this conversation as resolved.
Resolved
: {}),
})
.catch(() => {
// Advisory only; a failed notification must not fail the model switch.
});

if (options.persistDefault ?? true) {
const persistScope = getPersistScopeForModelSelection(this.settings);
this.settings.setValue(persistScope, 'model.name', parsed.modelId);
Expand Down