Skip to content
Merged
10 changes: 7 additions & 3 deletions docs/developers/qwen-serve-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,14 @@ with status `400`.
`SessionNotFoundError` for an unknown session id returns:

```json
{ "error": "No session with id \"<sid>\"", "sessionId": "<sid>" }
{
"error": "No session with id \"<sid>\"",
"sessionId": "<sid>",
"code": "session_not_found"
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
}
```

with status `404`.
with status `404`. A concurrent close uses `code: "session_closing"`.

`WorkspaceMismatchError` for a `POST /session` whose `cwd` doesn't canonicalize to a registered workspace returns `400` with:

Expand Down Expand Up @@ -2481,7 +2485,7 @@ curl -X DELETE http://127.0.0.1:4170/session/$SID
# → 204 No Content
```

Idempotent: returns `404` for unknown sessions (same `SessionNotFoundError` shape as other routes).
Idempotent: returns `404` for unknown sessions. The error envelope uses `code: "session_not_found"`; a concurrent close may return `code: "session_closing"`, which clients may treat as the same successful terminal state for this route.

> **`session_closed` event.** SSE subscribers receive a terminal `session_closed` event with `{ sessionId, reason: 'client_close', closedBy?: '<clientId>' }` before the stream ends. SDK reducers treat this identically to `session_died` (sets `alive: false`, clears `pendingPermissions`).

Expand Down
4 changes: 3 additions & 1 deletion packages/acp-bridge/src/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4307,7 +4307,9 @@ describe('createAcpSessionBridge', () => {
hasMore: false,
});

await expect(refresh).rejects.toBeInstanceOf(SessionNotFoundError);
await expect(refresh).rejects.toMatchObject({
code: 'session_closing',
});
closeResult.resolve({});
await close;
await bridge.shutdown();
Expand Down
23 changes: 18 additions & 5 deletions packages/acp-bridge/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5063,6 +5063,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
throw new SessionNotFoundError(
req.sessionId,
'The session is closing; retry after close completes',
'session_closing',
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
);
}
const replayFields =
Expand All @@ -5077,12 +5078,16 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
action === 'load'
? await resolveHistoryAnchorRecordId(existing, replayFields)
: undefined;
if (
byId.get(req.sessionId) !== existing ||
isClosingOrAuthorizingClose(existing)
) {
if (byId.get(req.sessionId) !== existing) {
throw new SessionNotFoundError(req.sessionId);
}
if (isClosingOrAuthorizingClose(existing)) {
throw new SessionNotFoundError(
req.sessionId,
'The session is closing; retry after close completes',
'session_closing',
);
}
existing.attachCount++;
const clientId = registerClient(existing, req.clientId);
recordAttachRef(existing, clientId);
Expand Down Expand Up @@ -5580,6 +5585,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
throw new SessionNotFoundError(
req.sessionId,
'The session is closing; retry after close completes',
'session_closing',
);
}
// Self + any coalescers we accumulated while the restore was
Expand Down Expand Up @@ -5818,6 +5824,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
throw new SessionNotFoundError(
sessionId,
'The session is already closing',
'session_closing',
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
);
}
let originatorClientId: string | undefined;
Expand Down Expand Up @@ -6188,6 +6195,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
throw new SessionNotFoundError(
existing.sessionId,
'The session is closing; retry after close completes',
'session_closing',
);
}
// BRSCi: bump attach counter BEFORE any await so the
Expand Down Expand Up @@ -6455,6 +6463,7 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
new SessionNotFoundError(
sessionId,
'The session is closing; retry after close completes',
'session_closing',
),
);
}
Expand Down Expand Up @@ -9210,7 +9219,11 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
const entry = byId.get(sessionId);
if (!entry) throw new SessionNotFoundError(sessionId);
if (isClosingOrAuthorizingClose(entry)) {
throw new SessionNotFoundError(sessionId, 'The session is closing');
throw new SessionNotFoundError(
sessionId,
'The session is closing; retry after close completes',
'session_closing',
);
}
const info = channelInfoForEntry(entry);
if (!info || info.isDying) throw new SessionNotFoundError(sessionId);
Expand Down
8 changes: 7 additions & 1 deletion packages/acp-bridge/src/bridgeErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,16 @@ function isNotCurrentlyGeneratingText(value: unknown): boolean {

export class SessionNotFoundError extends Error {
readonly sessionId: string;
constructor(sessionId: string, extra?: string) {
readonly code: 'session_not_found' | 'session_closing';
constructor(
sessionId: string,
extra?: string,
code: 'session_not_found' | 'session_closing' = 'session_not_found',
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
) {
super(`No session with id "${sessionId}"` + (extra ? `. ${extra}` : ''));
this.name = 'SessionNotFoundError';
this.sessionId = sessionId;
this.code = code;
}
}

Expand Down
21 changes: 21 additions & 0 deletions packages/cli/src/serve/server/error-response.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import type { Response } from 'express';
import { describe, expect, it, vi } from 'vitest';
import { SessionNotFoundError } from '@qwen-code/acp-bridge/bridgeErrors';
import {
SessionTranscriptChangedError,
SessionWriterConflictError,
Expand All @@ -29,6 +30,26 @@ function responseMock(): {
}

describe('sendBridgeError session writer errors', () => {
it('serializes the structured session-closing code', () => {
const { response, status, json } = responseMock();

sendBridgeError(
response,
new SessionNotFoundError(
'session-1',
'The session is closing',
'session_closing',
),
);

expect(status).toHaveBeenCalledWith(404);
expect(json).toHaveBeenCalledWith({
error: 'No session with id "session-1". The session is closing',
code: 'session_closing',
sessionId: 'session-1',
});
});

it('maps sealed session maintenance to daemon_draining', () => {
const { response, status, json } = responseMock();

Expand Down
4 changes: 3 additions & 1 deletion packages/cli/src/serve/server/error-response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,9 @@ export function sendBridgeError(
return;
}
if (err instanceof SessionNotFoundError) {
res.status(404).json({ error: err.message, sessionId: err.sessionId });
res
.status(404)
.json({ error: err.message, code: err.code, sessionId: err.sessionId });
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
return;
}
if (err instanceof SessionArchivedError) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,8 @@ private boolean isCurrentSessionNotFound(HttpSupport.Response response) {
String responseSessionId = JsonSupport.optionalString(body, "sessionId");
String code = JsonSupport.optionalString(body, "code");
return session.getSessionId().equals(responseSessionId)
&& (code == null || "session_not_found".equals(code));
&& (code == null || "session_not_found".equals(code)
|| "session_closing".equals(code));
Comment thread
yiliang114 marked this conversation as resolved.
Resolved
} catch (DaemonProtocolException e) {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1680,6 +1680,18 @@ void destroyAfterDetachOmitsRetiredClientIdAndAcceptsNotFound() {
assertEquals(null, deleteClientId.get());
}

@Test
void destroyAcceptsAlreadyClosingForCurrentSession() {
server.createContext("/session/session-1", exchange ->
sendJson(exchange, 404,
"{\"error\":\"closing\",\"code\":\"session_closing\",\"sessionId\":\"session-1\"}"));

try (DaemonClient daemon = newClient()) {
DaemonSessionClient session = daemon.createSession();
session.destroySession();
}
}

@Test
void destroyDoesNotTreatGenericNotFoundAsAlreadyDeleted() {
server.createContext("/session/session-1", exchange ->
Expand Down
38 changes: 38 additions & 0 deletions packages/webui/src/daemon/session/DaemonSessionProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7274,6 +7274,7 @@ describe('DaemonSessionProvider', () => {
const closingError = new DaemonHttpError(
404,
{
code: 'session_closing',
error:
'No session with id "session-b". The session is closing; retry after close completes',
sessionId: 'session-b',
Expand Down Expand Up @@ -7348,6 +7349,7 @@ describe('DaemonSessionProvider', () => {
new DaemonHttpError(
404,
{
code: 'session_closing',
error:
'No session with id "session-b". The session is closing; retry after close completes',
sessionId: 'session-b',
Expand All @@ -7362,6 +7364,41 @@ describe('DaemonSessionProvider', () => {
expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledTimes(1);
});

it('does not retry a missing session', async () => {
sdkMocks.sessions.push(createMockSession({ sessionId: 'session-a' }));
let actions: DaemonSessionActions | undefined;

function Harness() {
actions = useDaemonActions();
return null;
}

await renderWithProvider(<Harness />, {
autoConnect: true,
sessionId: 'session-a',
});
await act(async () => {
await flushPromises();
});
sdkMocks.MockDaemonSessionClient.load.mockClear();
sdkMocks.MockDaemonSessionClient.load.mockRejectedValueOnce(
new DaemonHttpError(
404,
{
code: 'session_not_found',
error: 'No session with id "session-b"',
sessionId: 'session-b',
},
'POST /session/:id/load: No session with id "session-b"',
),
);

await expect(
requireActions(actions).loadSession('session-b'),
).rejects.toThrow();
expect(sdkMocks.MockDaemonSessionClient.load).toHaveBeenCalledTimes(1);
});

it('does not retry a closing session after a newer switch', async () => {
sdkMocks.sessions.push(createMockSession({ sessionId: 'session-a' }));
let actions: DaemonSessionActions | undefined;
Expand All @@ -7385,6 +7422,7 @@ describe('DaemonSessionProvider', () => {
new DaemonHttpError(
404,
{
code: 'session_closing',
error:
'No session with id "session-b". The session is closing; retry after close completes',
sessionId: 'session-b',
Expand Down
5 changes: 1 addition & 4 deletions packages/webui/src/daemon/session/DaemonSessionProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2372,10 +2372,7 @@ export function DaemonSessionProvider(props: DaemonSessionProviderProps) {
pendingLoad?.sessionId === restoreSessionId &&
error instanceof DaemonHttpError &&
error.status === 404 &&
typeof errorBody?.['error'] === 'string' &&
errorBody['error'].endsWith(
'The session is closing; retry after close completes',
)
errorBody?.['code'] === 'session_closing'
) {
reconnectAttempt += 1;
const reconnectConfig = reconnectConfigRef.current;
Expand Down
Loading