qwen-code/docs/developers
jinye 2453b82add
[codex] Add daemon session load/resume (#4222)
* feat(serve): add daemon session load resume

Adds HTTP and SDK support for restoring persisted daemon sessions through load/resume routes, including replay buffering for load and guarded concurrent restore handling.

Refs #4175

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>

* fix(serve): address review feedback on daemon session load/resume

- Gate `defaultEntry` claim in `restoreSession` on
  `defaultSessionScope === 'single'`, mirroring `doSpawn`. Without the
  gate, a restored session silently became the omitted-scope attach
  target on `'thread'`-default daemons.
- Rename advertised capability `session_resume` to
  `unstable_session_resume` to match the underlying ACP method
  (`connection.unstable_resumeSession`). `session_load` stays stable.
- Seed `lastEventId: 0` in `DaemonSessionClient.resume`, symmetric with
  `load`. The agent's `unstable_resumeSession` schedules an
  `available_commands_update` via `setTimeout(0)`; without the seed the
  SDK consumer would miss that frame.
- Add HTTP-level test for the `RestoreInProgressError → 409` envelope.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* docs(serve): adopt review feedback comments on session load/resume

- Cross-reference the `POST /session` disconnect-cleanup rationale
  from `restoreSessionHandler`'s `!res.writable` branch so future
  maintainers find the BQ9tV race + tanzhenxin attach-rollback
  context without grep.
- Document `DaemonSessionState.{models, modes, configOptions}` in
  the SDK so callers can narrow to the ACP `SessionModelState` /
  `SessionModeState` / `SessionConfigOption` shapes.
- Add JSDoc on `DaemonClient.restoreSession` explaining why
  `loadSession` and `resumeSession` collapse into one transport.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* fix(serve): preserve restore state and harden in-flight restore races

Address the four Critical findings from PR #4222 review (wenshao):

- Coalesced restore waiters now observe the same ACP state the
  original restore caller did. `state: {}` in `restoreSession`'s
  coalesce branch was clobbering the spread `restored.state`, so
  concurrent callers got different payloads based purely on timing.
  Cache the load/resume response on `SessionEntry.restoreState` and
  return it from both the existing-byId early return and the
  coalesce branch.
- Drop the `defaultEntry` promotion on restore. Explicit
  `session/load` / `session/resume` is "give me THIS id"; it must
  not become the implicit attach target for subsequent omitted-id
  `POST /session` callers under `single` scope. Reserves
  `defaultEntry` for sessions created through `doSpawn` only.
- Reserve coalesced attaches synchronously via
  `InFlightRestore.coalesceState.count` so the spawn owner's
  `requireZeroAttaches` disconnect-reaper sees a non-zero
  `attachCount` on the freshly registered entry and skips the
  kill. Without this, B's `attachCount++` happened after `await
  inFlight.promise`, leaving a window where A's HTTP-disconnect
  cleanup could reap the session out from under B.
- Include `pendingRestoreIds` in the `killSession` channel-teardown
  decision. The last live session leaving while a restore is
  in-flight on the same channel would otherwise SIGTERM the
  channel mid-restore.
- Bump `RestoreInProgressError`'s `Retry-After` from 1s to 5s
  (matches `SessionLimitExceededError`); under the default
  `initTimeoutMs` of 10s, 1s pushed clients into tight loops.

Tests: new bridge cases covering state propagation through
coalesce, the spawn-owner-disconnect race, the
pendingRestoreIds-aware channel teardown, and the no-promote-
on-restore invariant. Existing "attaches twice" test rewritten
to assert the cached restore state propagates.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* test(serve): cover acpAgent load/resume + restore route error mappings

Close the test-coverage gaps wenshao called out in PR #4222 review:

- acpAgent.test.ts gains a `QwenAgent loadSession /
  unstable_resumeSession` block that locks down the new contract
  end-to-end at the agent layer:
  * `loadSession` missing persisted session → throws
    `RequestError.resourceNotFound("session:<id>")` (code -32002
    + `data.uri`).
  * `loadSession` existing session → returns LoadSessionResponse
    AND triggers `session.replayHistory(messages)` so SSE
    subscribers see the persisted turns.
  * `unstable_resumeSession` missing session → same
    resourceNotFound contract.
  * `unstable_resumeSession` existing session → returns the
    response WITHOUT replaying history (resume restores model
    context internally; UI replay is intentionally suppressed).
  Required extending the mocked `RequestError` with
  `resourceNotFound`, and mocking `SessionService` per case.
- server.test.ts adds the missing restore-route wire mappings:
  `WorkspaceMismatchError → 400 workspace_mismatch` and
  `SessionLimitExceededError → 503 + Retry-After: 5`. Combined with
  the existing 409 case for `RestoreInProgressError`, the route
  layer now has full structured-error coverage.
- Updated the 409 test's `Retry-After` expectation from `1` to `5`
  to match the bumped retry hint.

Disconnect-cleanup tests for the restore route were intentionally
not added — the cleanup branch is line-for-line identical to
`POST /session`'s handler (which itself ships without route-level
disconnect tests due to flaky supertest + Node http close-event
timing).

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* docs(serve): document daemon session load/resume routes

Sync the docs to the routes that landed via PR #4222:

- `docs/developers/qwen-serve-protocol.md`:
  * Add `session_load` and `unstable_session_resume` to the
    advertised features list, with a note on the `unstable_`
    prefix mirroring ACP's underlying method name.
  * Document `POST /session/:id/load` and `POST /session/:id/resume`
    — request body, response shape (including the cached `state`
    field that late attachers observe), and the full error
    envelope: 404 unknown id, 400 workspace_mismatch, 503
    session_limit_exceeded (counts in-flight restores), 409
    restore_in_progress (cross-action race).
  * Note the SSE replay ring bound (4000 frames default) and the
    "subscribe immediately after load" guidance for long histories.
- `docs/users/qwen-serve.md`:
  * Add a "Loading and resuming a persisted session" section with
    the SDK example (`DaemonSessionClient.load` /
    `DaemonSessionClient.resume`) and the load-vs-resume
    decision table.
  * Update the durability model — sessions are still ephemeral
    across daemon restarts in Stage 1, but persisted sessions on
    disk can now be reloaded.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* fix(test): use _meta payload to satisfy ACP SessionConfigOption types

The two new state-propagation tests in `httpAcpBridge.test.ts` used
`{ id, name, value }` as a `SessionConfigOption`, but ACP's actual
`SessionConfigSelect` shape requires `currentValue` + `options`. vitest
runs through esbuild and skips strict typechecking, so the local
`vitest run` passed; CI's `tsc --build` (run during `npm run prepare`)
caught it.

Switch the fixture to `_meta: { tag: '...' }` instead — `_meta` is
typed as `Record<string, unknown> | null` on the ACP response shapes,
so any payload survives. The assertions only need the bridge to
forward the state object intact, which `_meta` proves equally well
without committing the test to the full SessionConfigOption union.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

* fix(serve): symmetric restore coalesce guard + transportClosed leak + defensive cleanup

Address the two new Critical findings + the test/cosmetic gaps from
wenshao's second review pass on PR #4222 (`a3f38da3a`):

- **[Critical] Symmetric coalesce guard.** The previous guard only
  rejected `load`-on-`resume`; `resume` arriving while a `load` was
  in flight silently coalesced and inherited the load's history-
  replay frames over SSE — directly violating resume's "no UI
  replay" contract (made worse by `DaemonSessionClient.resume()`
  seeding `lastEventId: 0`). Tighten the guard to
  `action !== inFlight.action` so any cross-action race throws
  `RestoreInProgressError`. Same-action coalescing is unaffected.

- **[Critical] `transportClosed` dangling rejection.** When
  `withTimeout` wins the `Promise.race` against `channel.exited`,
  the `.then(throw)` chain on `channel.exited` stays pending. A
  later channel exit (next session boundary, daemon shutdown, agent
  crash) fires the `throw` with no observer attached — Node 22 logs
  `unhandledRejection`, and `--unhandled-rejections=throw`
  deployments crash the daemon. Add `transportClosed.catch(() => {})`
  to suppress the dangling rejection after the race settles.

- **`isAcpSessionResourceNotFound` exact-match fallback.** The
  message-fallback path used `message.includes(expectedUri)`, which
  would falsely match a sessionId of `"a"` against a message
  containing `"session:abc"`. Tighten to exact equality on the
  canonical `Resource not found: <uri>` form. The primary
  `data.uri` path remains the dominant code path.

- **`loadSession` mcpServers default symmetry.** `loadSession` now
  uses `params.mcpServers ?? []` to mirror `unstable_resumeSession`.
  Defends against a future ACP schema loosening that makes
  `LoadSessionRequest.mcpServers` optional — without the
  null-coalesce, `newSessionConfig` would `TypeError` on iteration.

Tests added:
- `httpAcpBridge.test.ts`: `resume`-on-`load` rejection (mirror of
  the existing `load`-on-`resume` test); regression for the
  dangling `unhandledRejection` (resolves `channel.exited` after
  the restore promise has already settled and asserts no
  `unhandledRejection` event); shutdown-awaits-restore via
  `Promise.race`-based ordering.
- `server.test.ts`: 400 for non-string and over-length `cwd` on
  the restore routes (mirroring the equivalent `POST /session`
  cases for `parseOptionalWorkspaceCwd`).
- `acpAgent.test.ts`: load with `getResumedSessionData()` returning
  `undefined` — distinct code path that does NOT call
  `replayHistory`.

🤖 Generated with [Qwen Code](https://github.com/QwenLM/qwen-code)

---------

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
2026-05-17 12:58:47 +08:00
..
development feat(telemetry): add detailed sensitive span attributes (#4097) 2026-05-17 00:36:48 +08:00
examples refactor(serve): 1 daemon = 1 workspace (#3803 §02) (#4113) 2026-05-15 12:44:36 +08:00
tools feat(web-search): remove built-in web_search tool, replace with MCP-based approach (#3502) 2026-04-24 11:29:02 +08:00
_meta.ts feat(cli,sdk): qwen serve daemon (Stage 1) (#3889) 2026-05-13 14:47:47 +08:00
architecture.md docs: enhance architecture documentation and add contribution guidelines 2025-12-11 18:31:24 +08:00
channel-plugins.md feat(channels): add dispatch modes and prompt lifecycle hooks 2026-03-28 06:19:02 +00:00
contributing.md chore(deps): upgrade ink 6.2.3 → 7.0.2 + bump Node engine to 22 (#3860) 2026-05-11 17:29:50 +08:00
qwen-serve-protocol.md [codex] Add daemon session load/resume (#4222) 2026-05-17 12:58:47 +08:00
roadmap.md feat(cli): improve auth dialog UX with clearer three-option layout 2026-03-01 15:22:35 +08:00
sdk-java.md Fix typo in class name (#2189) 2026-04-18 11:59:36 +08:00
sdk-python.md doc[sdk-python] Expand Python SDK usage documentation (#3995) 2026-05-12 15:27:00 +08:00
sdk-typescript.md chore(deps): upgrade ink 6.2.3 → 7.0.2 + bump Node engine to 22 (#3860) 2026-05-11 17:29:50 +08:00