fix(session-controller): wait for initializing local agents

This commit is contained in:
_Kerman committed 2026-10-22 17:04:51 +08:00
1 parent aeb1078126
commit e5b68798b9
6 files changed
+267 -4

No files matched your search

+31 -1
View File
@@ -5,6 +5,7 @@ import { dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { zstdCompressSync, zstdDecompressSync } from 'node:zlib'
import { describe, expect, it } from 'vitest'
import { installModelSelection } from '@deepseek-ai/dsh-agent'
import { SESSION_FORMAT_VERSION, SessionId } from '@deepseek-ai/dsh-session'
import { generationLogPath } from '../../../packages/session/session-persistence-jsonl/src/format.ts'
import { scanZstdFrames } from '../../../packages/session/session-persistence-jsonl/src/zstd.ts'
@@ -69,7 +70,36 @@ describe.skipIf(webSnapshotMode() === 'record')('historical preset restoration t
}
await expect(readFile(successor)).rejects.toMatchObject({ code: 'ENOENT' })
const resolved = await scaffold.ctx.sessionController.resolveAgent(id)
const setupEntered = Promise.withResolvers<undefined>()
const releaseSetup = Promise.withResolvers<undefined>()
const initialization = scaffold.ctx.agents.resume({
resumeSessionId: id,
setup: async (ctx) => {
installModelSelection(ctx)
await scaffold.ctx.agentPresets.mount(ctx, 'ptc')
setupEntered.resolve(undefined)
await releaseSetup.promise
},
})
const resolved = await (async () => {
try {
await Promise.race([setupEntered.promise, initialization])
expect(scaffold.ctx.agents.get(id)).toBeUndefined()
const lookup = scaffold.ctx.sessionController.resolveAgent(id)
releaseSetup.resolve(undefined)
const original = await initialization
const result = await lookup
expect({ sameAgent: 'agent' in result && result.agent === original.agent }).toMatchInlineSnapshot(`
{
"sameAgent": true,
}
`)
return result
} finally {
releaseSetup.resolve(undefined)
await initialization
}
})()
if ('error' in resolved) throw resolved.error
expect(scaffold.ctx.agentPresets.composedPreset(resolved.agent.ctx)).toBe('ptc')
expect(resolved.agent.session.header.agentPreset).toBe('ptc')
@@ -15,8 +15,8 @@
en: 1fdf707322fb6996
zh: 0204f7e9d4aa3cce
/session-controller/use-this-package:
en: aabd5be911e477f5
zh: 2f7fdb44bc8777bc
en: 9064eec15b81c07d
zh: 1100fa805d019bbc
/session-controller/client-references:
en: 41bdda1ac32df558
zh: aa5d0e325924066b
@@ -53,6 +53,8 @@ Projection reads retain loading and failure state independently of their values.
Accepted prompts and observed running keep their Client display conversion across list refresh, reconnect, and Session-object replacement. The Manager retains these observations by Session id; they do not establish durable history. Drafts, projection stores, and sidebar display rules retain their existing behavior. The [blank rollback decision](../../../.agents/notes/implemented/bug-fix/2026-09-15-client-session-blank-reconciliation.md) defines retention and late-response handling.
Session history is readable before its Agent is ready; the summary reports `agentAvailable: false` during setup. Agent operations and named blank reuse wait for the same local initialization, without acquiring its disposal ownership. Bare Sessions and external writers remain subject to the existing writer-conflict behavior.
The Client adapter exposes `SessionEventStream`, a Gateway `RemoteJournalStream` bound to one ordinary or direct-subagent address. It opens follow before the initial page, publishes only contiguous `replace`, `prepend`, `append`, and `settle-assistant` changes, and repairs reconnect or sequence gaps through a tail page. Backwards paging has two verbs: `loadOlder()` pulls one Turn-aligned page, and `loadThrough(seq)` — the turn-jump loader — loops Turn-aligned pages until the window covers the target seq, lowering a shared target on repeated calls, stopping on a page that makes no progress, and reporting busy through the same `loadingOlder` snapshot bit. The Web adapter explicitly opts into cursorless Assistant frames: each opening carries the active attempt's `startedAfterSeq`, `nextIndex`, and compact stream, and every stream member becomes a Client-only `assistant/live-chunk` entry ordered between durable cursors. The Host captures a follower-local arrival ordinal with that baseline and suppresses buffered frames at or before the cut; a replacement Agent may restart frame revision at one. A durable `assistant/message` or `assistant/attempt` arriving after an active opening stays staged only when its seq follows `startedAfterSeq` and its Turn and Step match; the matching end type, seq, and index releases the durable entry. A successful message retains its transient rows until the owning `step/end`, so pending tool identities remain available for dispatch. Failed or interrupted settlements retire their rows immediately; earlier same-step retries remain visible. Revision, dense-index, or settlement gaps for a known attempt reopen follow, while a controller that missed the start ignores unknown-attempt frames and publishes their durable settlement normally. An abandoned end publishes a settlement delta without a durable entry so its transient rows retire immediately. A durable gap-repair page has no Assistant baseline, so its held notification reopens follow once for a paired page and baseline. Every history record covers exactly its event seq. A business, persistence, or unresolved continuity failure terminates the stream, while only physical carrier loss selects automatic resumption. `SessionControlStream` is a Gateway `RemoteSnapshotStream`; every generation opens with a complete process-local baseline, so reconnect replaces projection state instead of treating transient values as durable events. At each ready Host generation, a synchronous Client subscription clears retained projection values and watermarks before refreshing queries and restarting the control stream, including Sessions absent from the control baseline. The first control stream waits for generation readiness, so its opening values cannot precede invalidation. Outstanding list responses from the previous generation cannot republish those values. Within a generation, a delayed control baseline cannot overwrite or clear newer sequenced values, whether they arrived through a live Session's list block, a history page, or a frame; a cached list block, viewed from the projection cache for a cold Session, yields to the connected Session's baseline whatever watermark it carries. The durable `inbox` projection carries both pending lists through the same cold-read and reconnect path as other projections. Client Agent contexts provide the identity used by the independent [`fileUpload`](../../client/file-upload/README.md) service; Session objects expose lifecycle, prompt, queue, and history operations rather than file transfer.
The Session object also carries local submission echoes: `session.beginSubmission` inserts one into `SessionSnapshot.pendingSubmissions` synchronously, before the caller serializes and prompts, so a conversation UI can show the message on the submit click's own frame. The echo stores ordered image previews and durable file references. Session derives its `transcript`, `queued`, or `steering` placement from the current running state and requested delivery mode, then retains that placement until the display handoff. The prompt's `requestId` is the correlation identity: the Host echoes it as the durable user source's `rpcId`, including pending messages in the `inbox` projection. Queued echoes retire one animation frame after queue acceptance; Chat echoes follow the admission rule below. Identified failures and abandonment retire unadmitted echoes immediately. Disposal preserves observed admission and fails other unsettled submissions. Each retirement fires `onRetire` exactly once; an observed retirement includes the ordered durable attachment references so the composer can release successful cards while preserving failed drafts. Echoes are Client memory only; reload and reconnect rebuild the conversation from durable events alone.
@@ -53,6 +53,8 @@ Client 列表刷新保留未变化的行对象,并在顺序和值均相同时
已受理的提示词与已观察到的运行,会使客户端展示转换跨列表刷新、重连及 Session 对象替换保留。Manager 按 Session id 保留这些观察;它们不证明持久历史已经产生。草稿、投影存储和侧边栏展示规则保留原有行为。[blank 回退修复决策](../../../.agents/notes/implemented/bug-fix/2026-09-15-client-session-blank-reconciliation.zh.md) 定义保留期限及迟到响应处理。
Session 历史在 Agent 就绪前即可读取;setup 期间,摘要中的 `agentAvailable` 为 `false`。Agent 操作和命名空白会话复用会等待同一次本地初始化,不取得其销毁权限。裸 Session 和外部写入者仍遵循现有的写入冲突行为。
Client 适配器提供 `SessionEventStream`,即绑定到一个普通 Session 或 direct subagent address 的 Gateway `RemoteJournalStream`。它在读取首个 page 前打开 follow,只发布连续的 `replace`、`prepend`、`append` 与 `settle-assistant` 变更,并通过 tail page 修复重连或 seq 缺口。向后分页有两个动词:`loadOlder()` 拉一页按轮次开头对齐的历史,而 `loadThrough(seq)`——轮次跳转加载器——按轮次开头对齐页面循环拉取直到窗口覆盖目标 seq,重复调用会下调共享目标,遇到无进展的页即停止,忙碌状态复用同一个 `loadingOlder` 快照位。Web 适配器显式选择接收无 cursor 的 Assistant frame:每个 opening 携带活跃 attempt 的 `startedAfterSeq`、`nextIndex` 与紧凑 stream,每个 stream member 都成为排在持久 cursor 之间的 Client-only `assistant/live-chunk` 条目。Host 会随该 baseline 捕获 follower 本地到达序号,并抑制该 cut 及之前的 buffered frame;replacement Agent 可以从 revision 一重新开始。活跃 opening 之后到达的持久 `assistant/message` 或 `assistant/attempt` 只有在其 seq 晚于 `startedAfterSeq` 且轮次与步骤匹配时才会保持暂存;匹配的 end type、seq 与 index 会发布持久条目。成功消息的瞬态 row 保留到所属 `step/end`,让待派发工具的身份持续可用;失败或中断的 settlement 立即移除对应 row,同一步骤中更早的 retry 仍然保留。已知 attempt 的 revision、密集 index 或 settlement 缺口会重新打开 follow;若 controller 错过 start,则忽略 unknown-attempt frame,并正常发布其持久 settlement。Abandoned end 会发布不含持久条目的 settlement delta,使瞬态 row 立即退出。持久缺口修复 page 不携带 Assistant baseline,因此 held notification 会重新打开 follow 一次,以取得配对的 page 与 baseline。每条历史 record 只覆盖自身的事件 seq。业务、persistence 或无法恢复的连续性错误会终止 stream,只有物理载体断开才触发自动恢复。`SessionControlStream` 是 Gateway `RemoteSnapshotStream`;每代都以完整的进程本地 baseline 开始,因此重连会替换 projection 状态,而不会把瞬态值当作 durable event。每次 Host generation 就绪时,同步的 Client 订阅会先清除保留的投影值及其水位,再刷新查询并重新打开 control stream,其中也包括 control baseline 中没有列出的 Session。首次 control stream 会等待 generation 就绪,确保其 opening 值不会先于旧状态清理到达。上一代尚未完成的 list 响应无法重新发布这些值。同一 generation 内,延迟到达的 control baseline 不能覆盖或清除较新的 sequenced 值,无论它们来自活 Session 的 list block、history page 还是 frame;冷 Session 从 projection cache 看出来的 cached list block 则不论水位都让位于建连 Session 的 baseline。持久 `inbox` 投影通过与其他投影相同的冷读取和重连路径传输两份待处理列表。Client Agent 上下文提供独立 [`fileUpload`](../../client/file-upload/README.zh.md) 服务使用的身份;Session 对象提供生命周期、prompt、queue 与历史操作,不提供文件传输。
Session 对象还承载本地提交回显:`session.beginSubmission` 在调用方序列化与提示词之前,同步把一条回显写入 `SessionSnapshot.pendingSubmissions`,会话 UI 因此能在点击提交的当帧显示消息。回显按顺序存放图片预览与持久文件引用。Session 根据当前运行状态与请求的投递模式推导其 `transcript`、`queued` 或 `steering` 位置,并保留该位置直到展示接管。提示词的 `requestId` 是关联标识:Host 把它回显为 durable user source 的 `rpcId`,`inbox` 投影中的待处理消息也保留同一 source。排队回显在队列接受后延迟一个动画帧退休;Chat 回显遵循下述入档规则。尚未入档的回显在带标识的提示词失败或被放弃时立即退休。销毁时保留已观察到的入档结果,其余未结算提交按 failed 退休。每次退休恰好触发一次 `onRetire`;observed 退休还会携带有序的持久附件引用,让 composer 释放成功卡片并保留失败草稿。回显只存在于 Client 内存;刷新与重连只从持久事件重建会话。
+38 -1
View File
@@ -8,6 +8,7 @@ import type {} from '@deepseek-ai/dsh-agent-default-model'
import { installModelSelection } from '@deepseek-ai/dsh-agent'
import type {} from '@deepseek-ai/dsh-agent-preset-registry'
import { brandString } from '@deepseek-ai/dsh-brand'
import { carrierKeyOf } from '@deepseek-ai/dsh-scope'
import type { Session, SessionId } from '@deepseek-ai/dsh-session'
import type { SessionInspection } from '@deepseek-ai/dsh-session-persistence'
import { SessionQueryError, type SessionObservation } from '@deepseek-ai/dsh-session-query'
@@ -159,6 +160,7 @@ export async function inspectApiSession(
/** Owns every operation that may create, resume, or configure a Web Agent. */
export class ApiSessionAgentController {
private readonly initializing = new Map<Session, PromiseWithResolvers<Agent | undefined>>()
private readonly resumes = new Map<SessionId, Promise<Agent>>()
private readonly claims = new Map<SessionId, Promise<void>>()
private readonly imageAdmissionChains = new WeakMap<Agent, Promise<void>>()
@@ -171,6 +173,25 @@ export class ApiSessionAgentController {
*/
initialize(): void {
const ctx = this.ctx
const initializing = this.initializing
ctx.on('session/created', function (session) {
// AgentLoop publishes through its own Agent scope; bare Sessions and
// Sessions created by another Agent do not announce their own readiness.
const owner = carrierKeyOf(this) as Agent | undefined
if (owner?.session === session) initializing.set(session, Promise.withResolvers())
})
ctx.on('agent/created', ({ agent }) => {
initializing.get(agent.session)?.resolve(agent)
initializing.delete(agent.session)
})
ctx.on('session/disposed', (session) => {
initializing.get(session)?.resolve(undefined)
initializing.delete(session)
})
ctx.effect(() => () => {
for (const pending of initializing.values()) pending.resolve(undefined)
initializing.clear()
}, 'session-controller: Agent readiness')
ctx.typert.lookups.configure('agent', async (sessionId: SessionId) => {
const found = await this.resolveAgent(sessionId)
if ('error' in found) throw found.error
@@ -219,7 +240,8 @@ export class ApiSessionAgentController {
let resume = this.resumes.get(sessionId)
if (resume === undefined) {
resume = this.resume(sessionId, observation).finally(() => { this.resumes.delete(sessionId) })
resume = (this.pendingAgent(sessionId) ?? this.resume(sessionId, observation))
.finally(() => { this.resumes.delete(sessionId) })
this.resumes.set(sessionId, resume)
}
try {
@@ -238,6 +260,7 @@ export class ApiSessionAgentController {
const raced = this.liveAgent(sessionId)
if (raced !== undefined) return raced
const racedSession = this.ctx.sessions.get(sessionId)
if (racedSession !== undefined && this.initializing.has(racedSession)) return this.resolve(sessionId)
if (racedSession !== undefined && hasApiSessionSubagentOwner(this.ctx, racedSession, undefined)) {
return { error: apiSessionSubagentOwnershipError(sessionId) }
}
@@ -254,6 +277,16 @@ export class ApiSessionAgentController {
}
}
/** Observe Web readiness without acquiring the initializing Agent's disposal capability. */
private pendingAgent(sessionId: SessionId): Promise<Agent> | undefined {
const session = this.ctx.sessions.get(sessionId)
const pending = session === undefined ? undefined : this.initializing.get(session)
return pending?.promise.then((agent) => {
if (agent === undefined) throw new ApiSessionNotFound(`session "${sessionId}" initialization did not complete`)
return agent
})
}
/**
* Create a Session for a new conversation, reusing the named blank Session
* while it is still reusable. A reused Session runs the requested preset, or
@@ -351,6 +384,8 @@ export class ApiSessionAgentController {
throw new ApiSessionSubagentOwnership(sessionId)
}
const composition = await this.composeAgent(this.presetForObservation(observation))
const pending = this.pendingAgent(sessionId)
if (pending !== undefined) return pending
const published = this.ctx.sessions.get(sessionId)
const live = this.ctx.agents.get(sessionId)
if (published !== undefined && hasApiSessionSubagentOwner(this.ctx, published, live)) {
@@ -376,6 +411,7 @@ export class ApiSessionAgentController {
/** @returns the reused Session, a new Session under `sessionId` when none is stored, or a new Session under a minted identity. */
private async claim(sessionId: SessionId, request: ApiSessionCreateRequest): Promise<Agent> {
await this.pendingAgent(sessionId)
const attached = this.ctx.sessions.get(sessionId)
const live = this.ctx.agents.get(sessionId)
if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, live)) {
@@ -419,6 +455,7 @@ export class ApiSessionAgentController {
if (error instanceof ApiSessionStartedSinceObserved) return this.createMinted(request.cwd, composition)
if (!(error instanceof Error) || error.name !== 'SessionAlreadyOwnedError') throw error
// Another resume in this process may hold the writer for the Agent it published.
await this.pendingAgent(sessionId)
return this.ctx.agents.get(sessionId) === undefined
? this.createMinted(request.cwd, composition)
: this.claim(sessionId, request)
@@ -0,0 +1,192 @@
/** Web operations join the original Agent setup while history remains readable. */
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Context } from '@deepseek-ai/cordis'
import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit'
import { SessionId, SessionSeq, type SessionEvent } from '@deepseek-ai/dsh-session'
import * as JsonlPersistence from '@deepseek-ai/dsh-session-persistence-jsonl'
import SessionTitle from '@deepseek-ai/dsh-session-title'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
import type { SessionRequestId } from '../src/types.ts'
import { createSessionTestController, createSessionTestRemote } from './test-remote.ts'
const seed: SessionEvent[] = [
{ type: 'turn/start', seq: SessionSeq(0), time: 1, data: { turn: 1 } },
{ type: 'turn/end', seq: SessionSeq(1), time: 2, data: { turn: 1, reason: { kind: 'completed' } } },
]
async function harness() {
const root = await mkdtemp(join(tmpdir(), 'dsh-web-readiness-'))
const ctx = new Context()
onTestFinished(async () => {
await ctx.fiber.dispose()
await rm(root, { recursive: true, force: true })
})
await mountAgentLoopTestDependencies(ctx)
await ctx.plugin(JsonlPersistence, { root })
await mountAgentLoopTestHarness(ctx)
await ctx.plugin(SessionTitle, { fallbackMaxWords: 5, fallbackMaxBytes: 40, maxTitleBytes: 80 })
ctx.provide('workspaceRegistry', { get: () => undefined, list: () => [], archivedSessionIds: [] } as never)
ctx.on('agent/pre-step', async () => ({ kind: 'reject' }))
const defaults = { defaultModelSelection: () => ({ provider: 'fixture', model: 'fixture' }), cwd: root }
const api = ctx.plugin({
inject: ['agents', 'sessions', 'sessionProjections', 'llm', 'workspaceRegistry', 'sessionPersistence', 'sessionTitle'],
apply() {},
})
await api
const controller = await createSessionTestController(api.ctx, defaults)
const remote = await createSessionTestRemote(api.ctx, defaults)
return { ctx, root, controller, remote, api }
}
describe('Web Agent initialization', () => {
it.each(['create', 'resume'] as const)('keeps %s history readable and joins setup for mutations', async (mode) => {
const { ctx, root, controller, remote } = await harness()
const sessionId = SessionId('initializing')
if (mode === 'resume') {
const previous = await ctx.agents.create({ sessionId, meta: { cwd: root }, seed })
await previous.dispose()
}
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
const setup = async (): Promise<void> => { entered.resolve(undefined); await release.promise }
const creation = mode === 'create'
? ctx.agents.create({ sessionId, meta: { cwd: root }, seed, setup })
: ctx.agents.resume({ resumeSessionId: sessionId, setup })
onTestFinished(async () => { release.resolve(undefined); await creation })
await entered.promise
const resume = vi.spyOn(ctx.agents, 'resume')
const abort = new AbortController()
const iterator = controller.follow({ address: { kind: 'session', sessionId } }, abort.signal)
[Symbol.asyncIterator]()
try {
expect(ctx.sessions.get(sessionId)).toBeDefined()
expect(ctx.agents.get(sessionId)).toBeUndefined()
expect((await controller.list({}, abort.signal)).items.find(item => item.sessionId === sessionId))
.toMatchObject({ blank: false, agentAvailable: false })
const snapshot = await iterator.next()
if (snapshot.done || snapshot.value.type !== 'snapshot') throw new Error('missing history snapshot')
expect(snapshot.value.records.slice(0, 2).map(record => record.event)).toEqual(seed)
const resolved = controller.resolveAgent(sessionId)
const renamed = remote.rename({ sessionId, title: 'Ready title' })
const prompted = remote.prompt({
requestId: 'ready-prompt' as SessionRequestId, sessionId, mode: 'queue',
content: [{ type: 'text', text: 'hello' }], clientTimeZone: 'UTC',
})
release.resolve(undefined)
const handle = await creation
const resolution = await resolved
expect('agent' in resolution && resolution.agent).toBe(handle.agent)
await expect(renamed).resolves.toMatchObject({ ok: true, value: { title: 'Ready title' } })
await expect(prompted).resolves.toMatchObject({ ok: true })
expect(resume).not.toHaveBeenCalled()
await ctx.sessions.flush(handle.agent.session)
await using stored = await ctx.sessionPersistence.open(sessionId, 'read')
expect((await stored.read()).events.findLast(event => event.type === 'session/title')?.data)
.toMatchObject({ title: 'Ready title' })
} finally {
release.resolve(undefined)
abort.abort()
await iterator.return?.()
resume.mockRestore()
}
})
it('reuses a named blank after its original setup completes', async () => {
const { ctx, root, remote } = await harness()
const sessionId = SessionId('blank-initializing')
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
const creation = ctx.agents.create({
sessionId, meta: { cwd: root },
setup: async () => { entered.resolve(undefined); await release.promise },
})
const resume = vi.spyOn(ctx.agents, 'resume')
try {
await entered.promise
const reused = remote.create({ sessionId, cwd: root })
release.resolve(undefined)
await creation
const result = await reused
if (!result.ok) throw result.error
expect(result.value.sessionId).toBe(sessionId)
expect(ctx.agents.list()).toHaveLength(1)
expect(resume).not.toHaveBeenCalled()
} finally {
release.resolve(undefined)
await creation
resume.mockRestore()
}
})
it.each(['failure', 'cancel'] as const)('ends waiters after initialization %s releases its writer', async (outcome) => {
const { ctx, root, controller } = await harness()
const sessionId = SessionId('failed-initializing')
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
const cancellation = new AbortController()
const creation = ctx.agents.create({
sessionId, meta: { cwd: root }, seed, signal: cancellation.signal,
setup: async () => { entered.resolve(undefined); await release.promise; throw new Error('setup failed') },
})
const failed = expect(creation).rejects.toThrow()
try {
await entered.promise
const resolution = controller.resolveAgent(sessionId)
if (outcome === 'cancel') cancellation.abort(new Error('cancelled'))
release.resolve(undefined)
await failed
await expect(resolution).resolves.toMatchObject({ error: { code: 'session/not-found' } })
expect(ctx.agents.get(sessionId)).toBeUndefined()
await using writer = await ctx.sessionPersistence.open(sessionId, 'write')
expect(writer.id).toBe(sessionId)
} finally {
release.resolve(undefined)
await failed
}
})
it('does not wait for a bare Session whose writer belongs to another owner', async () => {
const { ctx, root, controller } = await harness()
const sessionId = SessionId('bare-session')
const session = ctx.sessions.create(sessionId, { meta: { cwd: root } })
await using writer = await ctx.sessionPersistence.create(session.header)
expect(writer.id).toBe(sessionId)
await expect(controller.resolveAgent(sessionId)).resolves.toMatchObject({ error: { code: 'session/writer-held' } })
})
it('releases Controller waiters without disposing the original Agent owner', async () => {
const { ctx, root, controller, api } = await harness()
const sessionId = SessionId('independently-owned')
const previous = await ctx.agents.create({ sessionId, meta: { cwd: root }, seed })
await previous.dispose()
const abort = new AbortController()
const iterator = controller.follow({ address: { kind: 'session', sessionId } }, abort.signal)[Symbol.asyncIterator]()
await iterator.next()
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
const creation = ctx.agents.resume({
resumeSessionId: sessionId,
setup: async () => { entered.resolve(undefined); await release.promise },
})
try {
await entered.promise
// Continuing the cold follow starts its background promotion while the original resume owns setup.
const following = iterator.next()
const resolving = controller.resolveAgent(sessionId)
await api.dispose()
await following
await expect(resolving).resolves.toMatchObject({ error: { code: 'session/not-found' } })
expect(ctx.sessions.get(sessionId)).toBeDefined()
release.resolve(undefined)
const handle = await creation
expect(ctx.agents.get(sessionId)).toBe(handle.agent)
} finally {
release.resolve(undefined)
abort.abort()
await iterator.return?.()
await creation
}
})
})