diff --git a/AGENTS.md b/AGENTS.md index 7f7a89f..0f8656b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,6 +39,7 @@ 8. **e2e scratch profile 的 `minimumReleaseAgeExclude` 含 `'@deepseek-ai/*'`**(`scripts/e2e-mount.sh` / `e2e-aggregate-mount.sh`,与仓库根 `pnpm-workspace.yaml` 同策):alpha 版本常在发布后 24h 内跑 lane,pnpm 11 的 `minimumReleaseAge` 默认会拒装新鲜包。 9. **插件开发树的 dsh-* 传递 peer 需提升为 devDependencies**(alpha.3 首见):`dsh-subagent` 等 npm 包把 `dsh-attachment` 等 dsh-* 姊妹包全部声明为 peerDependencies(由宿主 bundle 树统一提供,宿主侧无此问题),插件仓库若只直接依赖其中一部分,其余 peer 在 pnpm 下会解析到树上残留的旧版——如 `dsh-attachment@0.1.1-rc.1` 缺 `admitPromptContent` 导出、`dsh-subagent` 产物 import 它时测试加载即崩。因此 devDependencies 需涵盖 dev 树实际触达的全部 peer(attachment / code-runtime / scope / session-projection / system-prompt / user-approval / util-time 七个即为此提升,与直接依赖同款精确钉版);`@deepseek-ai/cordis` peer 自 alpha.3 起要求 `^4.0.2`(上游全线 peer 已升)。适配新 alpha 版本时先跑 `pnpm peers check`,把新失配的传递 peer 一并提升进 devDependencies。例外:**`dsh-client-locale` 的 peer/devDep 允许落后于基线**(alpha.5 时上游停在 0.1.2-alpha.3 未发新版)——peer 下限 `^0.1.2-alpha.3` 天然容纳同 tuple 的 alpha.5 运行时,此时保持旧钉版并在 `pnpm-workspace.yaml` 注明,待上游发版再追平;rc.1 起上游恢复发版,peer/devDep 已与基线一并钉 `0.1.2-rc.1`,该例外消除。 10. **聊天文件打开漏斗是 `remote.session.openWorkspacePath`**(`ctx.workspaces.openPath` 已随 alpha 删除,`IWorkspaces` 无此方法):「聊天区文件在侧边栏打开」拦截在 `ctx.inject(['remote.session'], …)` 内以 **defineProperty 数据属性遮蔽**该命名空间方法(gateway client 的方法是 accessor 属性、异步挂载、contribution 重挂载时服务重建——inject 回调重跑即自愈);实现见 `src/client/openpath-intercept.ts`,设计见 [docs/plans/2026-08-31-openpath-intercept-alpha-design.md](docs/plans/2026-08-31-openpath-intercept-alpha-design.md)。 +11. **自定义种子必须带 fork 标记对(`meta.isSeeded: true` + `inheritedEventCount`)**:dsh-session 契约「只给 seed 不标 isSeeded,种子算重放历史而非继承前缀」——缺标记时 `Session.ownEvents()` 含整个种子,子会话 `Inbox` 构造器重放种子里的 `agent/inbox/spliced`,**继承父会话切割时刻未领取的 inbox 输入**(排队用户消息 next-turn、长回合中工具结果上下文/steering next-step——后者即「上下文很长时侧边对话先把之前的 User msg 发出去」的根因,幽灵消息排在 boundary 之前最先发给模型)。宿主 `session.fork`(api-session-controller)的调用即规范形态;回归由 `tests/sidechat-seed-validation.spec.ts`(真实 `Session.create` + `Inbox`)守护。0.1.2-rc.1 复评:无更优雅的 sidechat 宿主 API(`ContinuableStartSpec` 仍无 seed 字段),`AgentRegistry.create` 接缝补齐标记即为规范用法。 --- diff --git a/docs/plans/2026-08-20-sidechat-tab-design.md b/docs/plans/2026-08-20-sidechat-tab-design.md index 26461ad..18bd9d3 100644 --- a/docs/plans/2026-08-20-sidechat-tab-design.md +++ b/docs/plans/2026-08-20-sidechat-tab-design.md @@ -96,3 +96,5 @@ 3. 重开线程 Tab 丢工具行:根因**不在宿主**(`session.history` cold 路径原样返回 `tool/call`,见 `api-proxy.ts:749` 与 `chunk-rows.ts` 的无损 chunk 压缩)而在首挂回源窗口——旧实现 8 事件/页 × 32 页 = 256 事件上限,而 cold 读会把 chunk-rows 展开回每个流式 delta 一条事件,一轮回答动辄数百事件,较早的 `tool/call` 掉出窗口(settled 文本靠最终 `assistant/message` 幸存)。修复 = 抽出 `collectOwnEvents`(200 事件/页 × 40 页帽、日志穷尽/无标记时落定 `seedBoundary:0` 停止每轮重走),单测覆盖四分支。 4. Subagent 页「目录损坏」行:见 §5 修正——种子追加 descriptor + SubagentView/subagent-detect 按前缀过滤(`isSideThreadSummary` 同时修好 autoOpenSubagent 误触发与计数膨胀)。旧版创建的线程仍是 corrupt 诊断行,由 SubagentView 的标题前缀过滤兜底隐藏。 - **转录传输迁至自有路由(DSH 0.1.2-alpha.1 适配)**:§6 原设计的时间线轮询走通用 `connection.api.sessions.history` RPC——该客户端面(`ctx.connection.api`)在 0.1.2-alpha.1 的 Remote-gateway 迁移中被整体移除,且其继任者(`session/follow`/`session/page`)对 `origin:'subagent'` 会话强制 subagent 地址寻址(普通 `{kind:'session'}` 地址被 `agent-busy` 拒绝),纯分页也拿不到最新尾页(`throughSeq` 不得超当前游标)。修复 = 新增 **`sidechat.events`** 路由(`src/sidechat-routes.ts`):host 侧读线程日志(live 走 `agent.session.events`,冷线程走 `ctx.get('sessionPersistence').inspect`——两版 DSH 同形,alpha.1 的 inspect 返回展开后的逻辑日志而非磁盘上的打包 chunk-row),服务端切 `session/end-seed`(`threadOwnLogEvents`,`collectOwnEvents` 的 walk 语义下沉),`afterSeq` 增量 + 8000 事件尾部帽(对齐旧 walk 上限 40×200)。客户端 `fetchThread` 单路径化,删除 `collectOwnEvents` 与 `ctx.connection` 镜像/inject。种子切割仍由 `transcriptRows` 客户端二次防御。挂载冒烟补 live+冷读两条断言。 +- **种子缺 fork 标记 → 子会话继承父会话未领取的 inbox 消息(2026-09-05,用户实测「上下文很长时侧边对话会把之前的 User msg 先发送出去」)**:`sidechat.start` 原只传 `seed` 不传 `meta.isSeeded: true` + `inheritedEventCount`。dsh-session 契约:**只给 seed 不标 isSeeded,种子算重放历史而非继承前缀** → `Session.ownEvents()` 含整个种子 → 子会话 `Inbox` 构造器(重放 `ownEvents()` 中的 `agent/inbox/spliced`)继承父会话切割时刻**任何未领取的 inbox 输入**。两个触发窗口(均以真实 0.1.2-rc.1 包 `Session.create` + `Inbox` 实验证实):① next-turn——父会话排队中的用户消息(长回合运行中补发);② **next-step(用户实测场景:父会话运行中、用户队列已清空)**——长回合里工具结果上下文/steering/运行时快照在步骤边界之间插入 next-step、尚未领取;上下文越长回合越久窗口越宽。后果:首条 `sidechat.prompt` 的 claim 顺序为 `[幽灵消息, boundary, question]`——幽灵消息排在 boundary 之前最先发给模型(工具上下文常为「工具完成,接下来做 X」,模型先继续父会话任务),并在子会话日志落成 `user/message`。修复 = create 补 `meta.isSeeded: true` + `inheritedEventCount: SessionLogOffset(seed.length)`(宿主自己的 `session.fork`——api-session-controller——的规范调用形态;`createAgent` 工厂逐字段透传 `sessions.prepare`)。`threadOwnLogEvents` 按 end-seed 标记切割,标记位置不变,转录行为不变;冷恢复按持久化 header 切割,一致。回归测试进 `tests/sidechat-seed-validation.spec.ts`(真实 Session + Inbox 双向锁定:旧形态继承幽灵 / 新形态两队列皆空)。用户拍板:不迁移既有线程、不加 inbox.clear() 兜底(修复后新线程为无操作;旧「从未发过消息」空线程首次使用可能仍先答一次旧消息,之后自愈)。 +- **「更优雅 API」复评(2026-09-05,0.1.2-rc.1 = npm latest)**:无 sidechat/sidechain 宿主 API;`ContinuableStartSpec`(`ctx.subagents.startContinuable`)仍无 seed 字段;`session/create` RPC 只建全新会话。§3 的自建结论继续成立,`AgentRegistry.create` 接缝即宿主 fork 自用的公开接缝——补齐 fork 标记即为规范用法。 diff --git a/src/sidechat-routes.ts b/src/sidechat-routes.ts index acdeadb..a0252b3 100644 --- a/src/sidechat-routes.ts +++ b/src/sidechat-routes.ts @@ -27,6 +27,7 @@ import type { Agent, AgentSetup, CreateAgentOptions, ResumeAgentOptions } from ' import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import type { Context as CordisContext } from '@deepseek-ai/cordis' import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session' +import { SessionLogOffset } from '@deepseek-ai/dsh-session' import type { Context, SidebarAgentPresetsService, @@ -238,16 +239,28 @@ export function buildSidechatApi(ctx: Context): SidechatRoutes { data: descriptor as unknown as Record, } const seed = [...inheritance.seed, descriptorEvent] + // Fork-marker fields (the exact shape the host's own session.fork uses, + // api-session-controller): without `isSeeded` + `inheritedEventCount` the + // session treats the whole seed as the child's OWN events, so the child's + // Inbox constructor replays the parent's `agent/inbox/spliced` events and + // inherits whatever input sat UNCLAIMED in the parent at the click moment + // (a queued follow-up, or a tool-result context spliced into next-step + // between step boundaries of a long-running turn). The first side prompt + // would then claim and send that stale message BEFORE the boundary + + // question. The marker keeps `ownEvents()` at the end-seed boundary, so + // the inherited inbox replays to empty. const options: CreateAgentOptions = { sessionId: childId, meta: { ...(parentSession.header.cwd === undefined ? {} : { cwd: parentSession.header.cwd }), parentSession: parentSession.id, + isSeeded: true, origin: 'subagent', delegationDepth: (parentSession.header.delegationDepth ?? 0) + 1, ...(agentPreset === undefined ? {} : { agentPreset }), }, seed: seed as unknown as readonly SessionEvent[], + inheritedEventCount: SessionLogOffset(seed.length), agentOptions: { ...parent.options }, setup, signal: AbortSignal.timeout(CREATE_TIMEOUT_MS), diff --git a/tests/sidechat-routes.spec.ts b/tests/sidechat-routes.spec.ts index ddce8af..4f939c6 100644 --- a/tests/sidechat-routes.spec.ts +++ b/tests/sidechat-routes.spec.ts @@ -113,6 +113,7 @@ describe('sidechat.start', () => { sessionId: string meta: Record seed: readonly { type: string; data: Record }[] + inheritedEventCount: number agentOptions: { provider: string; model: string } setup: unknown } @@ -120,10 +121,15 @@ describe('sidechat.start', () => { expect(options.meta).toMatchObject({ parentSession: 'parent', origin: 'subagent', + isSeeded: true, delegationDepth: 1, agentPreset: 'preset-a', cwd: '/p', }) + // The fork-marker pair is load-bearing: without it the child's Inbox + // replays the parent's seed inbox splices and inherits whatever input sat + // unclaimed in the parent (see sidechat-seed-validation.spec.ts). + expect(options.inheritedEventCount).toBe(options.seed.length) expect(options.agentOptions).toEqual({ provider: 'test', model: 'model-x' }) // The child carries the parent's completed turns as a verbatim seed, // closed by the durable subagent descriptor (honest catalog citizenship: @@ -221,6 +227,16 @@ describe('sidechat.start', () => { const { childId } = await api['sidechat.start']({ sessionId: 'parent', question: ' ' }) + // The empty thread carries the same fork-marker pair (isSeeded + + // inheritedEventCount = seed length) as the prompted create. + const options = services.create.mock.calls[0]![0] as { + meta: Record + seed: readonly { type: string }[] + inheritedEventCount: number + } + expect(options.meta.isSeeded).toBe(true) + expect(options.inheritedEventCount).toBe(options.seed.length) + // No prompt yet: the composer owns the first message; the placeholder // label is pinned and the in-progress snapshot is parked for it. expect(child.inject).not.toHaveBeenCalled() diff --git a/tests/sidechat-seed-validation.spec.ts b/tests/sidechat-seed-validation.spec.ts index 3f929d4..f828701 100644 --- a/tests/sidechat-seed-validation.spec.ts +++ b/tests/sidechat-seed-validation.spec.ts @@ -10,8 +10,9 @@ * not a mock, so the class of bug cannot silently return. */ import { describe, expect, it } from 'vitest' -import { Session } from '@deepseek-ai/dsh-session' +import { Session, SessionLogOffset } from '@deepseek-ai/dsh-session' import type { SessionId } from '@deepseek-ai/dsh-session' +import { Inbox } from '@deepseek-ai/dsh-agent' import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import type { SidebarSessionEvent } from '../src/context-types.ts' import { buildSidechatInheritance } from '../src/sidechat-core.ts' @@ -111,3 +112,115 @@ describe('sidechat seed against the real dsh-session validator', () => { expect(types.at(-1)).toBe('session/end-seed') }) }) + +describe('sidechat seed fork markers vs the real dsh-agent Inbox replay', () => { + /** + * Regression: the thread-create call originally passed `seed` WITHOUT the + * fork-marker pair (`meta.isSeeded: true` + `inheritedEventCount`). A seed + * without them is REPLAY history, not an inherited prefix, so the child's + * ownEvents() includes the whole seed and its Inbox constructor replays the + * parent's `agent/inbox/spliced` events — inheriting whatever input sat + * UNCLAIMED in the parent at the click moment (a queued follow-up, or a + * tool-result context spliced into next-step between step boundaries of a + * long-running turn). The first side prompt then claimed and SENT that stale + * message before the boundary + question. These tests run the REAL + * dsh-session Session and dsh-agent Inbox. + */ + const pendingMessage = (id: string, kind: string, text: string) => ({ + id, + role: 'user', + content: [{ type: 'text', text }], + source: { kind }, + }) + const inboxOver = (session: Session): { nextTurn: number; nextStep: number } => { + const inbox = new Inbox(session, { inserted() {}, discarded() {}, claimed() {} }) + return { nextTurn: inbox.nextTurn.length, nextStep: inbox.nextStep.length } + } + /** The shape the routes pass since the fix: isSeeded + inheritedEventCount. */ + const forkMarkedSession = (id: string, seed: readonly SidebarSessionEvent[]): Session => + Session.create( + id as SessionId, + seed as never, + { version: 0, id: id as SessionId, createdAt: Date.now(), isSeeded: true }, + SessionLogOffset(seed.length), + ) + /** Real loop order: inbox insert → turn/start → claim deletion → step/start + * → user/message. One completed, fully claimed turn (seq 0-7). */ + const completedTurnLog = (): SidebarSessionEvent[] => [ + ev('agent/inbox/spliced', 0, { target: 'next-turn', start: 0, inserted: [pendingMessage('m-q', 'user', 'q')] }), + ev('turn/start', 1, { turn: 1 }), + ev('agent/inbox/spliced', 2, { target: 'next-turn', start: 0, removedCount: 1, inserted: [] }), + ev('step/start', 3, { turn: 1, step: 1 }), + ev('user/message', 4, pendingMessage('m-q', 'user', 'q')), + ev('assistant/message', 5, { turn: 1, step: 1, message: assistantMessage('a') }), + ev('step/end', 6, { turn: 1, step: 1 }), + ev('turn/end', 7, { turn: 1, reason: { kind: 'completed' } }), + ] + /** Mid-turn with an UNCLAIMED tool-result context in next-step (seq 15). */ + const midTurnLog = (): SidebarSessionEvent[] => [ + ...completedTurnLog(), + ev('agent/inbox/spliced', 8, { target: 'next-turn', start: 0, inserted: [pendingMessage('m-q2', 'user', 'q2')] }), + ev('turn/start', 9, { turn: 2 }), + ev('agent/inbox/spliced', 10, { target: 'next-turn', start: 0, removedCount: 1, inserted: [] }), + ev('step/start', 11, { turn: 2, step: 1 }), + ev('user/message', 12, pendingMessage('m-q2', 'user', 'q2')), + ev('tool/call', 13, { turn: 2, step: 1, callId: 'c1', name: 'bash', arguments: '{}' }), + ev('tool/result', 14, { + turn: 2, step: 1, + message: { + id: 'm-r', + role: 'user', + content: [{ type: 'tool-result', toolCallId: 'c1', content: [{ type: 'text', text: 'ok' }] }], + source: { kind: 'tool', callId: 'c1' }, + }, + }), + ev('agent/inbox/spliced', 15, { + target: 'next-step', + start: 0, + inserted: [pendingMessage('m-ctx', 'tool', 'tool bash finished: exit 0 ... now continue the plan')], + }), + ] + + it('inherits the parent\'s UNCLAIMED next-step tool context without the fork markers (root cause)', () => { + // Parent mid-turn (user queue empty): the bash tool returned and spliced + // its follow-up context into next-step; the next step boundary has not + // claimed it yet. The reported long-context scenario. + const { seed } = buildSidechatInheritance(midTurnLog()) + // OLD call shape (seed only): the whole seed counts as own events and the + // phantom context is inherited as pending input. + const unmarked = Session.create('session-inbox-unmarked' as SessionId, seed as never) + expect(unmarked.ownEvents().length).toBe(seed.length + 1) + expect(inboxOver(unmarked)).toEqual({ nextTurn: 0, nextStep: 1 }) + }) + + it('inherits the parent\'s QUEUED follow-up (next-turn) without the fork markers', () => { + const queued = pendingMessage('m-queued', 'user', 'queued second message') + const log: SidebarSessionEvent[] = [ + ...completedTurnLog(), + ev('agent/inbox/spliced', 8, { target: 'next-turn', start: 0, inserted: [queued] }), + ] + const { seed } = buildSidechatInheritance(log) + const unmarked = Session.create('session-inbox-unmarked-turn' as SessionId, seed as never) + expect(inboxOver(unmarked)).toEqual({ nextTurn: 1, nextStep: 0 }) + }) + + it('the fork-marker pair (isSeeded + inheritedEventCount) leaves the inherited inbox empty', () => { + // Same mid-turn log as the root-cause case, plus the descriptor the + // routes append — exactly what sidechat.start passes to agents.create. + const { seed } = buildSidechatInheritance(midTurnLog()) + const withDescriptor = [ + ...seed, + { + type: 'subagent/descriptor', + seq: seed.length, + time: Date.now(), + data: snapshotSubagentDescriptor({ mode: 'continuable', provider: 'sidechat', label: 'Side: test' }), + } as unknown as SidebarSessionEvent, + ] + const marked = forkMarkedSession('session-inbox-marked', withDescriptor) + // Only the end-seed marker is own; the transcript cut is unchanged. + expect(marked.ownEvents().map(event => event.type)).toEqual(['session/end-seed']) + expect(marked.snapshotEvents().map(event => event.type).at(-1)).toBe('session/end-seed') + expect(inboxOver(marked)).toEqual({ nextTurn: 0, nextStep: 0 }) + }) +})