fix(session): claim named Sessions in arrival order before resolving presets

session.create resolved the requested preset before queueing on the named
identity, so a later request whose preset resolved first could run first, and
an undeclared preset masked the directory conflict the README promises.
Queue first, check the named Session's directory and ownership, then resolve
the preset inside the queue, and report the preset each request left the
Session running instead of reading it after the queue moved on. The no-roster
conflict message now names its actual cause.
This commit is contained in:
Yichen Jiang committed 2026-10-09 11:29:04 +08:00
1 parent 64c47c6306
commit 1b8a55116e
8 files changed
+95 -41

No files matched your search

@@ -15,8 +15,8 @@
en: 1fdf707322fb6996
zh: 0204f7e9d4aa3cce
/session-controller/use-this-package:
en: 8f0f101a28713cff
zh: 3758b8c85fc6bf1a
en: 627c5d4120758422
zh: fe0798b103e3526b
/session-controller/client-references:
en: 41bdda1ac32df558
zh: aa5d0e325924066b
+1 -1
View File
@@ -37,7 +37,7 @@ Host list generation yields between complete rows only when its configured work
Client list rows and resident Sessions use the current `sessionListMetadata` projection to reject stale blank-session hints; recency is the later of the summary timestamp and the projected last user prompt. When SessionManager creates an instance before its list row arrives, it reconciles blankness with metadata already retained for that Session. An opened conversation is therefore not reused by New Session even when an older list response still marks it blank.
`session.create` returns a Session for a new conversation, and its response names the Session actually used. A named `sessionId` is reused while it is blank (no turn has started), belongs to the requested directory, is an unarchived member of the requested Workspace, and is not written by another owner; a live Session is reused in place, and a persisted one is resumed while retaining its writer lock. The reused Session runs the requested `agentPreset`, or the configured default when the request names none: its recorded preset is not resolved, and a change is logged as `agent-preset/selected` before the Agent is published. A named Session that has started, fails the Workspace placement, or is written by another owner stays unchanged, and a new Session is created instead. A `sessionId` with no stored Session becomes the new Session's identity. A named Session in another directory fails with `session/conflict`, and one owned by subagent routing with `session/agent-busy`. Creations naming one identity run in request order. `session.list` includes persisted blanks using cached metadata, without opening cold log bodies.
`session.create` returns a Session for a new conversation, and its response names the Session actually used. A named `sessionId` is reused while it is blank (no turn has started), belongs to the requested directory, is an unarchived member of the requested Workspace, and is not written by another owner; a live Session is reused in place, and a persisted one is resumed while retaining its writer lock. The reused Session runs the requested `agentPreset`, or the configured default when the request names none: its recorded preset is not resolved, and a change is logged as `agent-preset/selected` before the Agent is published. A named Session that has started, fails the Workspace placement, or is written by another owner stays unchanged, and a new Session is created instead. A `sessionId` with no stored Session becomes the new Session's identity. A named Session in another directory fails with `session/conflict`, and one owned by subagent routing with `session/agent-busy`; both checks precede preset resolution. Creations naming one identity run in arrival order, including their preset resolution, and each response reports the preset its own request left the Session running. `session.list` includes persisted blanks using cached metadata, without opening cold log bodies.
Client list refreshes retain unchanged row objects and reuse the items array when order and values match. Each row's `retainedBy` contains positive local reference-source counts; Host metadata refreshes cannot overwrite them. Cache membership checks use a per-refresh ID set, so reconciliation grows linearly with the current list and retained cache sizes. Host summary updates replace running and Agent availability; local create/fork responses only fill missing metadata on existing rows. Removed ordinary Sessions retain projection stores only when their catalogs contain children.
+1 -1
View File
@@ -37,7 +37,7 @@ Host 仅在配置的工作时间片耗尽时,于完整条目之间让出事件
Client 列表行和驻留 Session 使用当前 `sessionListMetadata` 投影纠正过期的空白会话提示;最近活动时间取摘要时间戳与投影中最后一次用户提示词时间的较晚值。当 SessionManager 在列表行到达前创建实例时,会使用已保留的该 Session 元数据对账空白状态。因此,即使旧列表响应仍将已有对话标为空白,新会话操作也不会复用已经打开过的对话。
`session.create` 返回一个用于新对话的 Session,响应指明实际使用的 Session。请求指明的 `sessionId` 在满足以下条件时被复用:仍为空白(尚未开始任何轮次)、属于请求的目录、是请求的工作区中未归档的成员,且未被其他写者占用;活动 Session 原地复用,持久化 Session 被恢复并持续持有其写锁。被复用的 Session 运行请求的 `agentPreset`,请求未指明时运行配置的默认 preset:不解析它记录的 preset,变更在 Agent 发布前记录为 `agent-preset/selected`。指明的 Session 若已开始、不满足工作区归属,或被其他写者占用,则保持不变,改为新建 Session。没有对应已存储 Session 的 `sessionId` 成为新 Session 的标识。指明其他目录中的 Session 返回 `session/conflict`,指明由 subagent 路由拥有的 Session 返回 `session/agent-busy`。指明同一标识的创建请求按请求顺序执行。`session.list` 根据缓存元数据列出持久化空白会话,不打开冷日志正文。
`session.create` 返回一个用于新对话的 Session,响应指明实际使用的 Session。请求指明的 `sessionId` 在满足以下条件时被复用:仍为空白(尚未开始任何轮次)、属于请求的目录、是请求的工作区中未归档的成员,且未被其他写者占用;活动 Session 原地复用,持久化 Session 被恢复并持续持有其写锁。被复用的 Session 运行请求的 `agentPreset`,请求未指明时运行配置的默认 preset:不解析它记录的 preset,变更在 Agent 发布前记录为 `agent-preset/selected`。指明的 Session 若已开始、不满足工作区归属,或被其他写者占用,则保持不变,改为新建 Session。没有对应已存储 Session 的 `sessionId` 成为新 Session 的标识。指明其他目录中的 Session 返回 `session/conflict`,指明由 subagent 路由拥有的 Session 返回 `session/agent-busy`;这两项检查先于 preset 解析。指明同一标识的创建请求按到达顺序执行,preset 解析也包含在内,每个响应报告其自身请求完成时该 Session 运行的 preset。`session.list` 根据缓存元数据列出持久化空白会话,不打开冷日志正文。
Client 列表刷新保留未变化的行对象,并在顺序和值均相同时复用条目数组。每行的 `retainedBy` 包含正数的本地引用来源计数,Host 元数据刷新不能覆盖它们。缓存成员检查使用每次刷新构建的 ID 集合,因此对账成本随当前列表和保留缓存的规模线性增长。 Host 摘要更新会替换运行状态与 Agent 可用性;本地 create/fork 响应只补充已有行缺失的元数据。普通 Session 被移除后,仅在目录仍有子项时保留其投影 store。
+44 -26
View File
@@ -50,7 +50,7 @@ export class ApiSessionPresetConflict extends Error {
readonly sessionId: SessionId,
readonly requestedPreset: string,
) {
super(`session "${sessionId}" records no agent preset and cannot be adopted under "${requestedPreset}"`)
super(`the deployment composes no agent preset roster, so session "${sessionId}" cannot run preset "${requestedPreset}"`)
}
}
@@ -73,6 +73,14 @@ export interface ApiSessionCreateRequest {
readonly reusable: (sessionId: SessionId) => boolean
}
/** The Session one creation request created or reused. */
export interface ApiSessionCreated {
/** Live Agent of the Session. */
readonly agent: Agent
/** Preset the Session ran when the request finished, before a later request for the same identity; absent without a roster. */
readonly agentPreset: string | undefined
}
/** Resolved preset and pre-publication Agent setup for one create or resume. */
interface ApiSessionComposition {
readonly agentPreset?: string
@@ -257,22 +265,20 @@ export class ApiSessionAgentController {
* is not resolved, and a change is logged as `agent-preset/selected` before
* the Agent is published. A named Session that has started a turn, fails the
* caller's placement rule, or is written by another owner stays unchanged,
* and a new Session is created instead. Claims on one identity run in
* request order.
* and a new Session is created instead. Requests naming one identity run in
* arrival order, including their preset resolution, and check the named
* Session's directory and ownership before resolving the preset.
* @param request - optional Session to reuse, directory, preset, and placement rule.
* @returns the live Agent of the reused or created Session.
* @throws RemoteError `agent-preset/not-found` or `agent-preset/invalid` for the requested or default preset.
* @returns the reused or created Session and the preset it ran when this request finished.
* @throws ApiSessionCwdConflict when the named Session belongs to another directory.
* @throws ApiSessionSubagentOwnership when subagent routing owns the named Session.
* @throws RemoteError `agent-preset/not-found` or `agent-preset/invalid` for the requested or default preset.
* @throws ApiSessionPresetConflict when no roster is composed and the request names a preset for a reused Session.
*/
async createSession(request: ApiSessionCreateRequest): Promise<Agent> {
const composition = await this.composeAgent(request.agentPreset)
async createSession(request: ApiSessionCreateRequest): Promise<ApiSessionCreated> {
const named = request.sessionId
const reused = named === undefined
? undefined
: await this.inOrder(named, () => this.claim(named, request, composition))
return reused ?? this.createAgent(brandString<SessionId>(`session-${randomUUID()}`), request.cwd, composition)
if (named === undefined) return this.created(await this.createMinted(request.cwd, await this.composeAgent(request.agentPreset)))
return this.inOrder(named, async () => this.created(await this.claim(named, request)))
}
/**
@@ -449,25 +455,28 @@ export class ApiSessionAgentController {
}
}
/** @returns the reused or newly created Session under `sessionId`, or undefined when it cannot be reused. */
private async claim(
sessionId: SessionId,
request: ApiSessionCreateRequest,
composition: ApiSessionComposition,
): Promise<Agent | undefined> {
/** @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> {
const attached = this.ctx.sessions.get(sessionId)
const live = this.ctx.agents.get(sessionId)
if (attached !== undefined && hasApiSessionSubagentOwner(this.ctx, attached, live)) {
throw new ApiSessionSubagentOwnership(sessionId)
}
if (live !== undefined) return this.reuseLive(live, request, composition)
if (live !== undefined) {
if (live.session.header.cwd !== request.cwd) {
throw new ApiSessionCwdConflict(live.id, request.cwd, live.session.header.cwd)
}
const composition = await this.composeAgent(request.agentPreset)
return await this.reuseLive(live, request, composition) ?? this.createMinted(request.cwd, composition)
}
let observation: SessionObservation
try {
observation = await this.ctx.sessionQuery.observeSession(sessionId)
} catch (error: unknown) {
if (!(error instanceof SessionQueryError) || error.code !== 'SESSION_QUERY_SESSION_NOT_FOUND') throw error
return this.createAgent(sessionId, request.cwd, composition)
return this.createAgent(sessionId, request.cwd, await this.composeAgent(request.agentPreset))
}
let reusable: boolean
{
using observed = observation
if (hasApiSessionSubagentOwner(this.ctx, { header: observed.header }, undefined)) {
@@ -476,9 +485,11 @@ export class ApiSessionAgentController {
if (observed.header.cwd !== request.cwd) {
throw new ApiSessionCwdConflict(sessionId, request.cwd, observed.header.cwd)
}
if (!request.reusable(sessionId) || observed.events.some(event => event.type === 'turn/start')) return undefined
this.assertPresetApplicable(sessionId, request.agentPreset)
reusable = request.reusable(sessionId) && !observed.events.some(event => event.type === 'turn/start')
}
const composition = await this.composeAgent(request.agentPreset)
if (!reusable) return this.createMinted(request.cwd, composition)
this.assertPresetApplicable(sessionId, request.agentPreset)
try {
return (await this.ctx.agents.resume({
resumeSessionId: sessionId,
@@ -486,10 +497,12 @@ export class ApiSessionAgentController {
setup: this.reuseSetup(composition),
})).agent
} catch (error: unknown) {
if (error instanceof ApiSessionStartedSinceObserved) return undefined
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.
return this.ctx.agents.get(sessionId) === undefined ? undefined : this.claim(sessionId, request, composition)
return this.ctx.agents.get(sessionId) === undefined
? this.createMinted(request.cwd, composition)
: this.claim(sessionId, request)
}
}
@@ -499,9 +512,6 @@ export class ApiSessionAgentController {
request: ApiSessionCreateRequest,
composition: ApiSessionComposition,
): Promise<Agent | undefined> {
if (live.session.header.cwd !== request.cwd) {
throw new ApiSessionCwdConflict(live.id, request.cwd, live.session.header.cwd)
}
if (!request.reusable(live.id) || !this.isBlank(live.session)) return undefined
this.assertPresetApplicable(live.id, request.agentPreset)
const current = this.presetForSession(live.session)
@@ -542,6 +552,14 @@ export class ApiSessionAgentController {
throw new ApiSessionPresetConflict(sessionId, requested)
}
private created(agent: Agent): ApiSessionCreated {
return { agent, agentPreset: this.presetForSession(agent.session) }
}
private createMinted(cwd: string, composition: ApiSessionComposition): Promise<Agent> {
return this.createAgent(brandString<SessionId>(`session-${randomUUID()}`), cwd, composition)
}
private async createAgent(sessionId: SessionId, cwd: string, composition: ApiSessionComposition): Promise<Agent> {
try {
await mkdir(cwd, { recursive: true })
@@ -494,8 +494,8 @@ export class SessionManager {
} = {},
): Promise<RemoteResult<{ sessionId: SessionId }>> {
const shared = {
...opts.sessionId === undefined ? {} : { sessionId: opts.sessionId },
...opts.agentPreset === undefined ? {} : { agentPreset: opts.agentPreset },
...(opts.sessionId === undefined ? {} : { sessionId: opts.sessionId }),
...(opts.agentPreset === undefined ? {} : { agentPreset: opts.agentPreset }),
}
const payload = opts.workspaceId !== undefined
? { workspaceId: opts.workspaceId, ...shared }
@@ -33,6 +33,7 @@ import {
apiSessionSubagentOwnershipError,
hasApiSessionSubagentOwner,
inspectApiSession,
type ApiSessionCreated,
} from './agent.ts'
import type {
SessionAttachmentRequest,
@@ -117,9 +118,9 @@ export class SessionCommandController {
}
}
const cwd = workspace?.path ?? request.cwd ?? this.defaultCwd
let adopted: Agent
let created: ApiSessionCreated
try {
adopted = await this.agents.createSession({
created = await this.agents.createSession({
...(request.sessionId === undefined ? {} : { sessionId: request.sessionId }),
cwd,
...(request.agentPreset === undefined ? {} : { agentPreset: request.agentPreset }),
@@ -129,7 +130,7 @@ export class SessionCommandController {
} catch (error) {
this.rejectCreation(error)
}
const sessionId = adopted.id
const sessionId = created.agent.id
if (workspace !== undefined) {
try {
await workspace.attachSession(sessionId)
@@ -141,8 +142,7 @@ export class SessionCommandController {
)
}
}
const agentPreset = this.agents.presetForSession(adopted.session)
return { sessionId, ...(agentPreset === undefined ? {} : { agentPreset }) }
return { sessionId, ...(created.agentPreset === undefined ? {} : { agentPreset: created.agentPreset }) }
}
/**
@@ -11,6 +11,7 @@ import { describe, expect, it, vi } from 'vitest'
import {
ApiSessionAgentController,
ApiSessionCwdConflict,
type ApiSessionCreated,
type ApiSessionCreateRequest,
} from '../src/agent.ts'
import { SessionCommandController } from '../src/commands.ts'
@@ -36,9 +37,9 @@ function controllerAgents(
/** A creation outcome that publishes `sessionId` in `cwd` as a stand-in Agent. */
function publishedSession(ctx: Context, sessionId: SessionId) {
return (request: ApiSessionCreateRequest): Promise<Agent> => {
return (request: ApiSessionCreateRequest): Promise<ApiSessionCreated> => {
const session = ctx.sessions.create(sessionId, { meta: { cwd: request.cwd } })
return Promise.resolve({ id: session.id, session, status: 'idle', ctx } as Agent)
return Promise.resolve({ agent: { id: session.id, session, status: 'idle', ctx } as Agent, agentPreset: undefined })
}
}
@@ -50,6 +50,8 @@ interface HarnessOptions {
readonly locked?: ReadonlySet<SessionId>
/** Declared presets whose activation failed. */
readonly broken?: ReadonlySet<string>
/** Requested presets whose resolution waits for the paired promise. */
readonly resolving?: ReadonlyMap<string, Promise<void>>
/** Workspace placement served to `workspaceId` requests. */
readonly workspace?: { readonly members: readonly SessionId[]; readonly archived: readonly SessionId[] }
}
@@ -85,7 +87,8 @@ async function harness(options: HarnessOptions = {}) {
}
ctx.provide('agentPresets', {
defaultId: presets[0],
resolve: (id?: string) => Promise.resolve().then(() => ({ id: known(id) })),
resolve: (id?: string) => Promise.resolve(id === undefined ? undefined : options.resolving?.get(id))
.then(() => ({ id: known(id) })),
mount: (_ctx: Context, id?: string) => Promise.resolve().then(() => ({ id: usable(id) })),
select: async (agent: Agent, agentPreset: string) => {
usable(agentPreset)
@@ -336,6 +339,27 @@ describe('session.create reuse of a live blank Session', () => {
expect(presetOf(SessionId('draft'))).toBe('standard')
})
it('claims one Session in arrival order when an earlier preset resolves later', async () => {
const minimal = Promise.withResolvers<undefined>()
const { remote, selections, presetOf } = await harness({
presets: ['standard', 'minimal'], resolving: new Map([['minimal', minimal.promise]]),
})
await remote.create({ sessionId: SessionId('draft') })
const first = remote.create({ sessionId: SessionId('draft'), agentPreset: 'minimal' })
const second = remote.create({ sessionId: SessionId('draft') })
await new Promise(resolve => setTimeout(resolve, 0))
minimal.resolve(undefined)
expect(await first).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'minimal' } })
expect(await second).toMatchObject({ ok: true, value: { sessionId: 'draft', agentPreset: 'standard' } })
expect(selections).toEqual([
{ sessionId: 'draft', agentPreset: 'minimal' },
{ sessionId: 'draft', agentPreset: 'standard' },
])
expect(presetOf(SessionId('draft'))).toBe('standard')
})
it('shares one creation between concurrent callers of a new identity', async () => {
const { ctx, remote } = await harness({ presets: ['standard'] })
@@ -366,6 +390,17 @@ describe('session.create reuse of a live blank Session', () => {
expect(ctx.agents.list().map(agent => agent.id)).toEqual(['other'])
})
it('refuses a Session in another directory before resolving the requested preset', async () => {
const { remote } = await harness({ presets: ['standard'] })
const elsewhere = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-elsewhere-')))
tempDirs.push(elsewhere)
await remote.create({ sessionId: SessionId('other'), cwd: elsewhere })
const response = await remote.create({ sessionId: SessionId('other'), agentPreset: 'nope' })
expect(response).toMatchObject({ ok: false, error: { code: 'session/conflict', details: { sessionId: 'other' } } })
})
it('leaves a subagent identity to subagent routing', async () => {
const { ctx, remote, cwd } = await harness({ presets: ['standard'] })
ctx.sessions.create(SessionId('child'), {
@@ -405,7 +440,7 @@ describe('session.create reuse of a live blank Session', () => {
})
if (response.ok) throw new Error('unreachable')
expect('existingPreset' in response.error.details).toBe(false)
expect(response.error.message).toContain('records no agent preset')
expect(response.error.message).toBe('the deployment composes no agent preset roster, so session "s7" cannot run preset "standard"')
})
})