fix(session-controller): adopt a named Session requested through a symlinked directory

`session.create` records the canonical spelling of the project directory in the
Session header, and compared a later request's own spelling with it. A second
request for the same explicit Session id through a symlinked path, such as a
macOS temporary directory, failed with `session/conflict`.

The check now accepts the recorded spelling or one whose canonical form the
header records. The ACP image-offload expectation compares the model-visible
directory with the canonical spelling of the scenario directory.
This commit is contained in:
LegGasai committed 2026-11-16 22:43:00 +08:00
1 parent f9513796b8
commit 5dfdf834d7
6 files changed
+49 -12

No files matched your search

@@ -1,7 +1,8 @@
import { fileURLToPath } from 'node:url'
import { realpathSync } from 'node:fs'
import { createServer } from 'node:http'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { join } from 'node:path'
import { basename, dirname, join } from 'node:path'
import { expect, it } from 'vitest'
import {
runScenario,
@@ -140,8 +141,9 @@ it('pins Messages Files offload and inline fallback in assembled requests', asyn
const fileImage = { type: 'image', source: { type: 'file', file_id: 'file-api-snapshot-1' } }
const offloadedImage = `[image omitted to fit request image limits; ${attachmentId}.${normalizedAccess}]`
const imageHandle = `Image ${attachmentId}; request preview 1x1px.${normalizedAccess}`
// The Session header records the canonical spelling of the scenario's directory, which is removed by now.
const runtimeContext = (cwd: string): string => '<system-reminder>\nThe following information describes your current session:\n\n'
+ `Current working directory: ${JSON.stringify(cwd)}.\n\n`
+ `Current working directory: ${JSON.stringify(join(realpathSync.native(dirname(cwd)), basename(cwd)))}.\n\n`
+ 'Current DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\n\n'
+ 'Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\n'
+ 'You are the root agent. Your name is "lead".\n\n'
@@ -15,8 +15,8 @@
en: 1fdf707322fb6996
zh: 0204f7e9d4aa3cce
/session-controller/use-this-package:
en: 15d6cb30e1e7f5e2
zh: 21fe7028a4ed4aef
en: 8940cc886de46772
zh: d5a204c204d444d6
/session-controller/client-references:
en: e8979a803ec3e194
zh: c567efcd971728ba
+1 -1
View File
@@ -47,7 +47,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`; 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.
`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. A symlinked spelling of the recorded directory names the same directory. 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
@@ -47,7 +47,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`;这两项检查先于 preset 解析。指明同一标识的创建请求按到达顺序执行,preset 解析也包含在内,每个响应报告其自身请求完成时该 Session 运行的 preset。`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。
+17 -6
View File
@@ -337,7 +337,7 @@ export class ApiSessionAgentController {
throw new ApiSessionSubagentOwnership(sessionId)
}
if (live !== undefined) {
if (live.session.header.cwd !== request.cwd) {
if (!await this.namesDirectory(live.session.header.cwd, request.cwd)) {
throw new ApiSessionCwdConflict(live.id, request.cwd, live.session.header.cwd)
}
const composition = await this.composeAgent(request.agentPreset)
@@ -356,7 +356,7 @@ export class ApiSessionAgentController {
if (hasApiSessionSubagentOwner({ header: observed.header })) {
throw new ApiSessionSubagentOwnership(sessionId)
}
if (observed.header.cwd !== request.cwd) {
if (!await this.namesDirectory(observed.header.cwd, request.cwd)) {
throw new ApiSessionCwdConflict(sessionId, request.cwd, observed.header.cwd)
}
reusable = request.reusable(sessionId) && !observed.events.some(event => event.type === 'turn/start')
@@ -440,20 +440,31 @@ export class ApiSessionAgentController {
} catch (error: unknown) {
throw new Error(`failed to ensure project directory "${cwd}": ${String(error)}`, { cause: error })
}
// The header records the canonical spelling of the project directory; see SessionHeader.cwd.
const fs = this.ctx.get('fs')
const canonical = fs === undefined ? cwd : fs.processPath(await fs.resolve(cwd))
return (await this.ctx.agents.create({
sessionId,
agentOptions: this.agentOptions(),
meta: {
cwd: canonical,
cwd: await this.canonical(cwd),
...(composition.agentPreset === undefined ? {} : { agentPreset: composition.agentPreset }),
},
setup: composition.setup,
})).agent
}
/** The canonical spelling of a project directory, which new headers record; see SessionHeader.cwd. */
private async canonical(cwd: string): Promise<string> {
const fs = this.ctx.get('fs')
return fs === undefined ? cwd : fs.processPath(await fs.resolve(cwd))
}
/**
* Whether a request names the directory a Session header records: by the recorded spelling, or by a
* spelling such as a symlink whose canonical form the header records.
*/
private async namesDirectory(recorded: string | undefined, requested: string): Promise<boolean> {
return recorded === requested || (recorded !== undefined && recorded === await this.canonical(requested))
}
private agentOptions(): AgentOptions {
const defaults = this.ctx.agentDefaultModel
// A Session that records no selection or request follows default changes.
@@ -217,6 +217,12 @@ describe('session.create Agent preset identity', () => {
await remote.create({ sessionId: brandString<SessionId>('canonical'), cwd: link })
// The filesystem canonicalizes with native semantics, which also expands Windows short names.
expect(ctx.agents.get(brandString<SessionId>('canonical'))?.session.header.cwd).toBe(realpathSync.native(real))
// The same request names that Session again; another directory does not, whether or not it exists.
expect(await remote.create({ sessionId: brandString<SessionId>('canonical'), cwd: link }))
.toMatchObject({ ok: true, value: { sessionId: 'canonical' } })
expect(await remote.create({ sessionId: brandString<SessionId>('canonical'), cwd: join(cwd, 'missing') }))
.toMatchObject({ ok: false, error: { code: 'session/conflict', details: { existingCwd: realpathSync.native(real) } } })
expect(ctx.agents.list().map(agent => agent.id)).toEqual(['canonical'])
})
it('records the requested preset on the Session header', async () => {
@@ -464,6 +470,24 @@ describe('session.create reuse of a live blank Session', () => {
})
describe('session.create reuse of a stored blank Session', () => {
it('resumes a blank Session whose header records the canonical spelling of a symlinked request', async () => {
const draft = brandString<SessionId>('linked-draft')
const base = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))
tempDirs.push(base)
const real = join(base, 'real')
const link = join(base, 'link')
mkdirSync(real)
symlinkSync(real, link)
const { ctx, remote, resumed } = await harness({
presets: ['standard'],
stored: new Map([[draft, { header: storedHeader(draft, realpathSync.native(real)), events: [modelSelection(0)] }]]),
})
await ctx.plugin(LocalFileSystem, { cwd: base })
expect(await remote.create({ sessionId: draft, cwd: link })).toMatchObject({ ok: true, value: { sessionId: 'linked-draft' } })
expect(resumed).toEqual(['linked-draft'])
})
it('resumes a blank Session whose recorded preset is no longer declared under the default', async () => {
const draft = brandString<SessionId>('stale-draft')
const cwd = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-session-preset-stored-')))