Merge branch 'feat/session-workspace-root' into feat/session-workspace-root-consumers
This commit is contained in:
commit
f9eb524891
1155 files changed
+31527
-9869
No files matched your search
@@ -15,8 +15,8 @@
|
||||
en: 1fdf707322fb6996
|
||||
zh: 0204f7e9d4aa3cce
|
||||
/session-controller/use-this-package:
|
||||
en: 8940cc886de46772
|
||||
zh: d5a204c204d444d6
|
||||
en: 958951f6e7fdc5de
|
||||
zh: 73d73a5d51b45eba
|
||||
/session-controller/client-references:
|
||||
en: c5e1bc84940f3df9
|
||||
zh: 211c69f9bbff2b84
|
||||
|
||||
@@ -27,6 +27,8 @@ Desktop analytics follows the [product collection policy](../../client/product-a
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
Fork keeps the inclusive `atSeq` request field and the default completed-turn cut. The command passes the observed history as the fork source: the stored parent prefix through `persistedEventCount`, then the child's marker and cold-read repair events. A live parent's log replaces that prefix in the factory, and a sharing backend drains the parent writer before referencing it; a parent whose stored history is shorter than the cut creates no child. See the [fork upgrade guide](../../../docs/upgrade-guide/v0.2.2-rc.3/session-fork-source/guide.md) for the creation parameters.
|
||||
|
||||
Prompt retries use the request identity in the first committed inbox insertion, including after the message is claimed or removed. Admission checks again after asynchronous attachment preparation, so concurrent retries accept one input. Acceptance acknowledges insertion, not execution or completion.
|
||||
|
||||
The controller reads a Session's recorded preset through the optional `agentPresets.presetForSession(session)` service method. A null result means no preset was recorded; an absent service means preset identity is unavailable to the controller.
|
||||
|
||||
@@ -27,6 +27,8 @@ kind: "package-reference"
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
fork 保留包含截点的 `atSeq` 请求字段,并默认选择已完成轮次的截点。命令把观察到的历史作为 fork 来源传递:截至 `persistedEventCount` 的已存储父前缀,其后是子会话的标记和冷读取修复事件。工厂用实时父会话的 log 替换该前缀,共享前缀的后端在引用前先排空父写者;父会话已存储历史短于截点时不会创建子会话。创建参数见 [fork 升级指南](../../../docs/upgrade-guide/v0.2.2-rc.3/session-fork-source/guide.zh.md)。
|
||||
|
||||
提示重试按首次已提交入队记录中的请求标识去重,消息被领取或删除后仍然有效。异步附件准备结束后再次检查,因此并发重试只接受一条输入。接受确认入队,不代表执行或完成。
|
||||
|
||||
控制器通过可选服务方法 `agentPresets.presetForSession(session)` 读取 Session 已记录的预设。null 结果表示未记录预设;服务缺席表示控制器无法获知预设身份。
|
||||
|
||||
@@ -262,6 +262,7 @@ export class SessionCommandController {
|
||||
)
|
||||
}
|
||||
const seed = buildForkSeed(source.events, boundary)
|
||||
const endSeq = SessionLogOffset(Math.min(boundary + 1, source.persistedEventCount ?? boundary + 1))
|
||||
let workspace: Workspace | undefined
|
||||
try {
|
||||
workspace = await this.forkWorkspace(source.header)
|
||||
@@ -279,6 +280,7 @@ export class SessionCommandController {
|
||||
await this.ctx.agents.create({
|
||||
sessionId: childId,
|
||||
seed,
|
||||
parentSource: { sessionId: request.sessionId, endSeq },
|
||||
inheritedEventCount: SessionLogOffset(boundary + 1),
|
||||
meta: {
|
||||
...(source.header.cwd === undefined ? {} : { cwd: source.header.cwd }),
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
/** Remote fork failures release any Agent created during setup. @module */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
import { expect, it, onTestFinished, vi } from 'vitest'
|
||||
import { createUserMessage } from '@deepseek-ai/dsh-llm'
|
||||
import { AgentRegistry } from '@deepseek-ai/dsh-agent'
|
||||
import { Session, SessionId, SessionSeq } from '@deepseek-ai/dsh-session'
|
||||
import type { SessionId as SessionIdType } from '@deepseek-ai/dsh-session'
|
||||
import * as persistence from '@deepseek-ai/dsh-session-persistence-sqlite'
|
||||
import { mountAgentLoopTestDependencies, mountAgentLoopTestHarness } from '@deepseek-ai/dsh-agent-loop-testkit'
|
||||
import { SqliteSessionHandle } from '../../../session/session-persistence-sqlite/src/sqlite.ts'
|
||||
import { MockAdapter, textResponse } from '../../../core/agent-loop/tests/mock-adapter.ts'
|
||||
import { createSessionTestRemote } from './test-remote.ts'
|
||||
|
||||
async function fixture() {
|
||||
const root = await mkdtemp(join(tmpdir(), 'dsh-remote-fork-source-'))
|
||||
onTestFinished(() => rm(root, { recursive: true, force: true }))
|
||||
const ctx = new Context()
|
||||
onTestFinished(() => ctx.fiber.dispose())
|
||||
await mountAgentLoopTestDependencies(ctx)
|
||||
await ctx.plugin(persistence, { root, compression: 'none' })
|
||||
const harness = await mountAgentLoopTestHarness(ctx)
|
||||
ctx.llm.registerAdapter(['mock'], new MockAdapter([textResponse('parent reply')]))
|
||||
ctx.provide('workspaceRegistry', { list: () => [], archivedSessionIds: [] } as never)
|
||||
const parent = await harness.create(SessionId('source'), { provider: 'mock', model: 'mock' })
|
||||
parent.followup(createUserMessage({ content: [{ type: 'text', text: 'parent history' }], source: { kind: 'user' } }))
|
||||
await parent.whenIdle()
|
||||
await ctx.sessions.flush(parent.session)
|
||||
const remote = await createSessionTestRemote(ctx, { defaultModelSelection: () => ({ provider: 'mock', model: 'mock' }), cwd: tmpdir() })
|
||||
return { ctx, parent, remote, root }
|
||||
}
|
||||
|
||||
it('releases child storage when the creation setup fails', async () => {
|
||||
const { ctx, parent, remote } = await fixture()
|
||||
const failure = new Error('child setup failed')
|
||||
let childId: SessionIdType | undefined
|
||||
// oxlint-disable-next-line typescript/unbound-method -- Called with the consumer-traced registry below.
|
||||
const create = AgentRegistry.prototype.create
|
||||
const created = vi.spyOn(ctx.agents, 'create').mockImplementation(async function (this: AgentRegistry, options) {
|
||||
childId = options.sessionId
|
||||
expect(options.parentSource).toEqual({ sessionId: parent.id, endSeq: parent.session.seq })
|
||||
expect(options.seed).toEqual([...parent.session.snapshotEvents(), expect.objectContaining({ type: 'session/end-seed', seq: parent.session.seq })])
|
||||
return create.call(this, { ...options, setup: () => { throw failure } })
|
||||
})
|
||||
onTestFinished(() => { created.mockRestore() })
|
||||
const result = await remote.fork({ sessionId: parent.id })
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('Expected failed Remote fork')
|
||||
expect(result.error.code).toBe('gateway/internal')
|
||||
expect(result.error.message).toContain(failure.message)
|
||||
expect(created).toHaveBeenCalledOnce()
|
||||
expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id])
|
||||
if (childId === undefined) throw new Error('Expected fork identity')
|
||||
const stored = await ctx.sessionPersistence.open(childId, 'write')
|
||||
await stored.close()
|
||||
})
|
||||
|
||||
it('publishes the identity requested from the creation factory', async () => {
|
||||
const { ctx, parent, remote } = await fixture()
|
||||
const created = vi.spyOn(ctx.agents, 'create')
|
||||
onTestFinished(() => { created.mockRestore() })
|
||||
const result = await remote.fork({ sessionId: parent.id })
|
||||
if (!result.ok) throw result.error
|
||||
expect(result.value.sessionId).toBe(created.mock.calls[0]?.[0].sessionId)
|
||||
expect(ctx.agents.get(result.value.sessionId)?.id).toBe(result.value.sessionId)
|
||||
expect(created).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('waits for parent durability and retains the selected cut while the parent continues', async () => {
|
||||
const { ctx, parent, remote, root } = await fixture()
|
||||
parent.session.append('session/title', { title: 'selected title', messageSeqs: [], source: { kind: 'user' } })
|
||||
const selected = parent.session.snapshotEvents()
|
||||
const entered = Promise.withResolvers<undefined>()
|
||||
const release = Promise.withResolvers<undefined>()
|
||||
// oxlint-disable-next-line typescript/unbound-method -- Called with the handle receiver below.
|
||||
const flush = SqliteSessionHandle.prototype.flush
|
||||
const flushing = vi.spyOn(SqliteSessionHandle.prototype, 'flush').mockImplementation(async function (this: SqliteSessionHandle, options) {
|
||||
if (this.id === parent.id) {
|
||||
entered.resolve(undefined)
|
||||
await release.promise
|
||||
}
|
||||
return flush.call(this, options)
|
||||
})
|
||||
const forked = remote.fork({ sessionId: parent.id })
|
||||
try {
|
||||
await entered.promise
|
||||
// The sharing backend drains the parent writer before the child row commits or publishes.
|
||||
expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id])
|
||||
expect(await ctx.sessionPersistence.list()).toHaveLength(1)
|
||||
parent.session.append('session/title', { title: 'later title', messageSeqs: [], source: { kind: 'user' } })
|
||||
release.resolve(undefined)
|
||||
const result = await forked
|
||||
if (!result.ok) throw result.error
|
||||
const child = ctx.sessions.get(result.value.sessionId)!
|
||||
expect(child.snapshotEvents().slice(0, selected.length)).toEqual(selected)
|
||||
expect(child.snapshotEvents()).toHaveLength(selected.length + 1)
|
||||
expect(child.snapshotEvents().at(-1)).toMatchObject({ type: 'session/end-seed', seq: selected.length })
|
||||
const reader = await ctx.sessionPersistence.open(child.id, 'read')
|
||||
try { expect((await reader.read()).events).toEqual(child.snapshotEvents()) } finally { await reader.close() }
|
||||
const db = new DatabaseSync(join(root, '.segments/sessions.sqlite'))
|
||||
try {
|
||||
expect(db.prepare('SELECT base_seq FROM segments WHERE segment_uuid = (SELECT tail_segment_uuid FROM traces WHERE trace_uuid = ?)').get(child.id))
|
||||
.toEqual({ base_seq: selected.length })
|
||||
} finally { db.close() }
|
||||
} finally {
|
||||
release.resolve(undefined)
|
||||
await Promise.allSettled([forked])
|
||||
flushing.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not publish a child after a parent flush failure and allows a later fork', async () => {
|
||||
const { ctx, parent, remote } = await fixture()
|
||||
const failure = new Error('parent write failed')
|
||||
parent.session.append('session/title', { title: 'unflushed title', messageSeqs: [], source: { kind: 'user' } })
|
||||
const flushing = vi.spyOn(SqliteSessionHandle.prototype, 'flush').mockImplementation(async function (this: SqliteSessionHandle) {
|
||||
if (this.id === parent.id) throw failure
|
||||
})
|
||||
const creating = vi.spyOn(ctx.sessionPersistence, 'create')
|
||||
try {
|
||||
const result = await remote.fork({ sessionId: parent.id })
|
||||
expect(result.ok).toBe(false)
|
||||
if (result.ok) throw new Error('Expected failed Remote fork')
|
||||
expect(result.error.code).toBe('gateway/internal')
|
||||
expect(result.error.message).toContain(failure.message)
|
||||
expect(creating).toHaveBeenCalledOnce()
|
||||
expect(ctx.agents.list().map(agent => agent.id)).toEqual([parent.id])
|
||||
expect((await ctx.sessionPersistence.list()).map(entry => entry.header.id)).toEqual([parent.id])
|
||||
flushing.mockRestore()
|
||||
const retried = await remote.fork({ sessionId: parent.id })
|
||||
if (!retried.ok) throw retried.error
|
||||
expect(ctx.agents.get(retried.value.sessionId)).toBeDefined()
|
||||
expect(creating).toHaveBeenCalledTimes(2)
|
||||
} finally {
|
||||
flushing.mockRestore()
|
||||
creating.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps cold read repairs in the child segment when the parent continues before creation', async () => {
|
||||
const { ctx, remote, root } = await fixture()
|
||||
const parent = Session.create(SessionId('cold-parent'))
|
||||
parent.append('turn/start', { turn: 1 })
|
||||
const writer = await ctx.sessionPersistence.create(parent.header)
|
||||
try { await writer.append(parent.snapshotEvents()) } finally { await writer.close() }
|
||||
const create = ctx.sessionPersistence.create.bind(ctx.sessionPersistence)
|
||||
const creating = vi.spyOn(ctx.sessionPersistence, 'create').mockImplementation(async (header, options) => {
|
||||
expect(options?.parentSource).toMatchObject({ sessionId: parent.id, endSeq: 1 })
|
||||
expect(options?.parentSource?.events).toMatchObject([
|
||||
{ type: 'turn/start', seq: 0 },
|
||||
{ type: 'turn/end', seq: 1, data: { reason: { kind: 'interrupted' } } },
|
||||
{ type: 'session/end-seed', seq: 2, data: { inherited: true } },
|
||||
])
|
||||
const parentWriter = await ctx.sessionPersistence.open(parent.id, 'write')
|
||||
try {
|
||||
await parentWriter.append([{ type: 'turn/end', seq: SessionSeq(1), time: 2,
|
||||
data: { turn: 1, reason: { kind: 'completed' } } }])
|
||||
} finally { await parentWriter.close() }
|
||||
return create(header, options)
|
||||
})
|
||||
onTestFinished(() => { creating.mockRestore() })
|
||||
const result = await remote.fork({ sessionId: parent.id })
|
||||
if (!result.ok) throw result.error
|
||||
const child = ctx.sessions.get(result.value.sessionId)
|
||||
expect(child?.snapshotEvents()).toMatchObject([
|
||||
{ type: 'turn/start', seq: 0 },
|
||||
{ type: 'turn/end', seq: 1, data: { reason: { kind: 'interrupted' } } },
|
||||
{ type: 'session/end-seed', seq: 2, data: { inherited: true } },
|
||||
])
|
||||
const reader = await ctx.sessionPersistence.open(result.value.sessionId, 'read')
|
||||
try { expect((await reader.read()).events).toEqual(child?.snapshotEvents()) } finally { await reader.close() }
|
||||
const db = new DatabaseSync(join(root, '.segments/sessions.sqlite'))
|
||||
try {
|
||||
expect(db.prepare('SELECT base_seq FROM segments WHERE segment_uuid = (SELECT tail_segment_uuid FROM traces WHERE trace_uuid = ?)').get(result.value.sessionId))
|
||||
.toEqual({ base_seq: 1 })
|
||||
} finally { db.close() }
|
||||
})
|
||||
@@ -167,6 +167,30 @@ describe('sessions.fork', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('shares the whole selected prefix of a live observation, which carries no persisted count', async () => {
|
||||
const ctx = await composed()
|
||||
try {
|
||||
const source = ctx.sessions.create(sid('unreported-source'), { meta: { cwd: '/proj' } })
|
||||
source.append('turn/start', { turn: 1 })
|
||||
source.append('turn/end', { turn: 1, reason: { kind: 'completed' } })
|
||||
const observe = ctx.sessionQuery.observeSession.bind(ctx.sessionQuery)
|
||||
vi.spyOn(ctx.sessionQuery, 'observeSession').mockImplementation(async (...args) => {
|
||||
const observation = await observe(...args)
|
||||
expect(observation.persistedEventCount).toBeUndefined()
|
||||
return observation
|
||||
})
|
||||
const create = vi.spyOn(ctx.agents, 'create')
|
||||
|
||||
const result = await (await remote(ctx)).fork({ sessionId: source.id, allowMigration: false })
|
||||
|
||||
if (!result.ok) throw result.error
|
||||
expect(create.mock.calls[0]?.[0].parentSource).toMatchObject({ sessionId: source.id, endSeq: 2 })
|
||||
expect(ctx.sessions.get(result.value.sessionId)?.inheritedEventCount).toBe(2)
|
||||
} finally {
|
||||
await ctx.fiber.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('forks a resident Session without consulting disk metadata or requiring a live Agent', async () => {
|
||||
const ctx = await composed()
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user