Merge pull request #1069 from omdsh-dev/fix/workspace-cwd
fix(host): root a detached session at its stored workspace header, not a full log read
This commit is contained in:
10 files changed
+278
-127
No files matched your search
@@ -2,6 +2,12 @@
|
||||
|
||||
> 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。
|
||||
|
||||
### Unreleased
|
||||
|
||||
- 🛡 **冷会话(detached)的 cwd 改读工作区地址,不再整份解码会话日志**:`sessionQuery.observeSession(..., { projectionMode: 'all' })` 为拿一个 `workingDirectory` 要解码整份 zstd 日志并水合全部投影;而启动期真正并发的是 **fs-watch 每监视目录一帧**、`/sidebar/file|html` 每资源一次、`/sidebar/upload|write` 每次一次——它们都绕过 0.28.1 只覆盖 `/sidebar/api` 的 `cwdOf()` 单飞,所以 39 MB 级会话在 130–180 ms 里被并发整读数十次(0.28.0 的 44 次 OOM、0.28.1 的 36 次是同一路径,不是「去重失效」)。现在 detached 会话的 cwd 走 `sessionPersistence.stat` 的 **header-only** 读(只读第一个 zstd 帧)+ 进程内 memo/在飞去重,`activeWorktreeRootOf` 对 detached 会话直接返回该地址;宿主 attach 后仍跟随 `working_directory` 与 linked worktree。
|
||||
- 代价:会话 attach 之前,侧边栏根是原始项目目录而非 agent 最后所在的子目录 / worktree;attach 后下一次 5 s 轮询切回。
|
||||
- 🧪 测试:`tests/smoke.spec.ts` 重写该组 8 例(header 优先于陈旧提示、header 只读一次、12 并发共享一次 header 读、无 `stat`/`stat` 失败回落客户端提示、live committed 优先、相对 cwd 拒绝为 `bad-request`、`defaultDirectory` 与进程 cwd 兜底)。机制与取舍见 [记录](docs/plans/2026-10-27-workspace-cwd-over-cold-reads.md)。
|
||||
|
||||
### v0.28.1
|
||||
|
||||
- 🛡 **并发同键冷读合并(OOM 修复)**:全量重启后会话全部转为 detached,12 条 `/sidebar/*` 路由共享的 cwd 解析会对同一会话各做一次宿主冷观察(整份日志读 + 解码;39MB 级会话 × 44 个并发请求 ≈ 1.7GB → OOM)。现在 `cwdOf()` 把**同一会话 + 同一客户端 cwd 提示**的并发请求合并为一次真实读,其余 await 同一结果;不引入 TTL(宿主本身按持久化 revision 缓存已完成冷读),客户端提示参与 key 以免跨提示串味。`tests/smoke.spec.ts` 新增「12 并发 → 1 次冷读」与「不同提示不合并」两例。
|
||||
|
||||
@@ -4,6 +4,12 @@
|
||||
>
|
||||
> 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current.
|
||||
|
||||
### Unreleased
|
||||
|
||||
- 🛡 **A detached session's cwd now comes from its stored workspace address instead of decoding the whole session log.** `sessionQuery.observeSession(..., { projectionMode: 'all' })` decodes the entire zstd artifact and hydrates every projection to answer with one `workingDirectory` string. The real startup fan-out never went through the 0.28.1 `cwdOf()` single-flight (which only covers `/sidebar/api`): the fs-watch socket sends **one frame per watched directory**, and `/sidebar/file|html` resolve cwd per resource, `/sidebar/upload|write` per call — so a 39 MB session was fully decoded dozens of times inside 130–180 ms (the 44-read OOM on 0.28.0 and the 36 reads reported against 0.28.1 are the same path, not a broken dedupe). The cold cwd now uses `sessionPersistence.stat` — a **header-only** read (first zstd frame) with a process-level memo and same-session in-flight sharing — and `activeWorktreeRootOf` returns that address for detached sessions. Once the host attaches the session, the committed `working_directory` and linked-worktree following resume as before.
|
||||
- Cost: until the session is attached, the sidebar roots at the original project rather than the agent's last directory/worktree; the next 5 s poll corrects it after attach.
|
||||
- 🧪 `tests/smoke.spec.ts` rewrote that group of 8 cases. Rationale and trade-offs: [record](docs/plans/2026-10-27-workspace-cwd-over-cold-reads.md).
|
||||
|
||||
### v0.28.1
|
||||
|
||||
- **Concurrent single-flight for cold cwd reads (OOM fix)**: after a full restart every session is detached, and the shared cwd resolution behind all twelve `/sidebar/*` routes ran one host observation per call (a full log read plus decode; a 39 MB session × 44 concurrent requests ≈ 1.7 GB → OOM). `cwdOf()` now shares one resolution between concurrent requests for the same session + client cwd hint; there is no TTL (the host already caches completed cold reads by persistence revision), and the hint stays in the key so different hints never leak across each other. Two new `tests/smoke.spec.ts` cases pin "12 concurrent → 1 cold read" and "different hints do not merge".
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
> 本次 alpha.5 → rc.1 上游完整树差异 355 项全部为 `package.json`、源码零变化,因此不改功能实现;伴随依赖为 Cordis peer `^4.0.5` / dev `4.0.5`、group `1.0.5`、schemastery `~3.18.5`、include `1.0.10`。RC 验证单独记录于 [适配记录](plans/2026-10-17-dsh-0.2.1-rc.1-adaptation.md),不以已发布 alpha 的测试数字替代。
|
||||
> 权威代码:`src/client/service.ts`(服务实现)、`src/client/builtins/`(内置 6 tab + 3 viewer 参考实现)、`lib/types/client/service.d.ts`(类型声明)。
|
||||
> alpha.5 已删除 `@deepseek-ai/dsh-invariants` 与上游 `/invariant` 子路径;本插件同步移除 invariant companion,不提供替代注册服务。HTTP/WS 准入遵循宿主 Connection(见 §6.2)。
|
||||
> 当前目录语义:文件 / Git / 终端与新建 sidechat 跟随会话 `working_directory`。live 读 `ctx.workingDirectory.get(session)`;cold 通过 `ctx.sessionQuery.observeSession` 的 all projections 读取并在 `finally` 释放 lease。linked worktree 仍按 base 目录记账;新 sidechat seed 尾部盖章当前 cwd,防止继承历史目录覆盖它。
|
||||
> 当前目录语义:**已 attach** 的会话里,文件 / Git / 终端与新建 sidechat 跟随会话 `working_directory`(live 读 `ctx.workingDirectory.get(session)`);**cold / detached** 会话读存储 header(`ctx.sessionPersistence.stat(id)`,只读第一个 zstd 帧,不解码日志;进程内 memo + 在飞去重),`activeWorktreeRootOf` 对 detached 直接返回该工作区地址。不要为取一个 cwd 调 `ctx.sessionQuery.observeSession`:它会解码整份会话日志并水合全部投影,启动期 fs-watch 每目录一帧的扇出会把它放大成数十次整读(详见 [2026-10-27 记录](plans/2026-10-27-workspace-cwd-over-cold-reads.md))。linked worktree 仍按 base 目录记账;新 sidechat seed 尾部盖章当前 cwd,防止继承历史目录覆盖它。
|
||||
> alpha.5 的 `TerminalBlockLabels` 要求 `commandLine(line)`;两个渲染消费者与全部 21 份词典同步。宿主兼容性优先读 `package.json#engines.dsh`,缺席才读 DSH peers;本插件没有该字段,仍用 13 条 peers(第三方 `dsh.plugin.json` 不参与)。
|
||||
> 仓库开发规则(硬约束 / CI / 发版)见 [AGENTS.md](../AGENTS.md)。
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
- **会话格式 v4 的两处形状**:`source.kind === 'plugin'` 被硬拒,插件侧一律用 `plugin:dsh-better-sidebar`(与 DSH 自己 v3→v4 迁移产出的 kind 逐字一致,历史 sidechat 会话不丢);tool 结果消息是 `role: 'tool'` + **顶层** `content` / `isError` / `toolCallId`,转录解析器**必须同时接受新旧形状**——旧分支不能删(历史日志里就是旧形状),只认新形状会静默返回空串。
|
||||
- **客户端会话快照与宿主客户端服务**:子代理目录读 `SessionListState.projectionsBySession[sid]?.values.subagentCatalog`(`mode` 有 `'unknown'` 新值);后台任务页直接读宿主**客户端** `ctx.jobs` 服务(`src/client/jobs-client.ts`:`getSnapshot()/subscribe()` 整份快照、`watchRows(sessionId)` 按会话引用计数、`observe(...)` 非消费输出流、`kill(sessionId, jobId)`)——**不要自建 `jobs.*` 路由,也不要用事件回放去读模型已读的输出**(那会动模型的 `job_output` 游标)。
|
||||
|
||||
- **会话当前执行目录**:文件 / Git / 终端及新建 sidechat 跟随 `working_directory`,不把 session header cwd 当成当前值。live 读 `ctx.workingDirectory.get(session)`;cold 经 `ctx.sessionQuery.observeSession(..., { projectionMode: 'all' })` 读取,lease 在 `finally` 中释放。同一 base 的 live 目录增量通过 epoch 失效缓存;cold 外进程同 base 变化仍沿用既有 15 s TTL。linked worktree 选择仍按 base 目录记账,不把选中的 worktree 反写为 base。sidechat 继承 seed 尾部盖章当前 cwd,避免旧 seed 的目录事件覆盖新线程的初始目录。
|
||||
- **会话当前执行目录**:文件 / Git / 终端及新建 sidechat 跟随 `working_directory`,不把 session header cwd 当成当前值——**但只对已 attach 的会话成立**。live 读 `ctx.workingDirectory.get(session)`,配合 epoch 失效缓存;**cold(detached)读存储 header**:`ctx.sessionPersistence.stat(id)` 只读第一个 zstd 帧(header-only,绝不解码日志)+ 进程内 memo/在飞去重,`activeWorktreeRootOf` 对 detached 会话直接返回这个工作区地址(不折持久化事件)。理由与代价见 [2026-10-27 记录](plans/2026-10-27-workspace-cwd-over-cold-reads.md):`ctx.sessionQuery.observeSession(..., { projectionMode: 'all' })` 为拿一个 cwd 要解码整份日志并水合全部投影,而启动期 fs-watch 是**每监视目录一帧**、`/sidebar/file|html` 是**每资源一次**、都不经过 `cwdOf()` 单飞 → 39MB 会话被并发整读数十次(0.28.0 OOM 与 0.28.1「未修复」都是这条)。会话 attach 之后,committed 目录与 linked worktree 跟随照旧。linked worktree 选择仍按 base 目录记账,不把选中的 worktree 反写为 base。sidechat 继承 seed 尾部盖章当前 cwd,避免旧 seed 的目录事件覆盖新线程的初始目录。
|
||||
- **终端 label**:alpha.5 的 `TerminalBlockLabels` 新增必填 `commandLine(line)`,两个消费者都要提供,21 份词典同步对应 key。
|
||||
|
||||
## B. 宿主契约(原 AGENTS.md §3.4 第 1–13 条)
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# 冷会话 cwd 改读工作区地址(2026-10-27)
|
||||
|
||||
> **范围**:`sessionCwdOf()` 的冷(detached)分支、`activeWorktreeRootOf()` 的 detached 分支、`/sidebar/api` 的 `cwdOf()` 注释与 `sessionQuery` 类型镜像。
|
||||
> **落点**:分支 `fix/workspace-cwd`(基线 `dev` `43db17f`)。
|
||||
> **一句话**:插件要的只是一个「工作区地址」,此前却为此付出整份会话日志的解码;改为读存储 header(只读第一个 zstd 帧)后,冷会话的读次数从「每个入口一次」降到「每个会话一次 header」。
|
||||
|
||||
---
|
||||
|
||||
## 一、背景:0.28.1 为什么没修好
|
||||
|
||||
外部对比测试(2026-10-26)在 39,886,933 字节会话上实测:启动后 13–14 s 内、130–180 ms 窗口出现 **36 次整份读取**,0.28.0 为 44 次;单飞上线后几乎没动。报告据此判「去重未生效」。
|
||||
|
||||
代码核对(宿主 0.2.1-rc.2 产物):
|
||||
|
||||
- 插件唯一的冷读入口是 `src/index.ts` 的 `sessionQuery.observeSession(id, { projectionMode: 'all' })`:宿主 `SessionObservationReader.read → loadSource → readColdSessionLog → persistence.open → requireStoredLog → readStableSnapshot → readFile`,整份读 + 全 zstd 帧解码 + 全投影水合,**插件只取其中 `workingDirectory` 一个字段**。
|
||||
- 宿主这条链**没有任何 in-flight 合并**:`SessionObservationReader` 的 5 条 LRU 与 backend 的 2 条 `coldLogMemo` 都是「读完才写」,并发未命中就是并发整读。
|
||||
- 0.28.1 的 `cwdInFlight`(`src/index.ts:651`)只包住 `/sidebar/api` 的 `cwdOf()`。**完整绕过它的有 6 个入口**:`/sidebar/upload`、`/sidebar/write`、`/sidebar/file`(每资源 GET)、`/sidebar/html`(预览 + 每相对资源)、`/sidebar/ws/fs-watch`(**每监视目录一帧**)、agent-open 回调。
|
||||
- fs-watch 的帧在 `ws.on('message')` 里各自 `void` 起跑,且服务端**先解析 cwd 再判断 op**(`src/index.ts:1924`);客户端 socket 打开时对 `[root, ...expanded]` 每个目录发一帧(`src/client/use-dir-watch.ts:113`)。所以「36 次」最自然的解释是「1 个根 + 35 个恢复的展开目录」,与单飞覆盖范围无关。
|
||||
|
||||
报告的另一个缺口:栈只截了 10 帧,止于 `SessionObservationReader.read`(此时已用掉 7–8 帧),**插件帧恰好落在截断处**;「无一帧来自插件」不能作为排除证据。
|
||||
|
||||
## 二、决定
|
||||
|
||||
**冷会话(宿主未 attach)的 cwd 取存储 header —— 即会话的工作区地址;不再调用任何会解码日志的 API。**
|
||||
|
||||
- 宿主 attach 之后(`ctx.sessions.get(id)` 有值)仍走 `workingDirectory.get(session)`,`cd` 进去的子目录和 linked worktree 照旧跟随。
|
||||
- `activeWorktreeRootOf()` 对 detached 会话直接返回 base:跟随 worktree 需要折叠日志里的工具调用,detached 时那等于再解码一次整份产物。
|
||||
- 客户端提示(session list 的 summary cwd)从「排在 observation 之后」降为「宿主答不上来时的兜底」,与它原本的定位一致。
|
||||
|
||||
## 三、代价(明确写出)
|
||||
|
||||
- 冷窗口内(启动恢复到会话 attach 之前,或从未打开过的会话)侧边栏根是**原始项目目录**,不是 agent 最后所在的子目录 / linked worktree。会话 attach 后,下一次 5 s `session.cwd` 轮询即切回 committed 目录。
|
||||
- 相对路径、`~`、绝对路径的解析基准在冷窗口内随之变为工作区根;这与「工作区地址」的语义一致。
|
||||
- 宿主若没有 `sessionPersistence.stat`(旧宿主),退化为客户端提示 → 进程 cwd;不再回退整份日志读。
|
||||
|
||||
## 四、实现
|
||||
|
||||
| 位置 | 变化 |
|
||||
| --- | --- |
|
||||
| `src/index.ts` `storedHeaderCwdOf()` | 新增:`sessionPersistence.stat()` 取 `header.cwd`,命中写进程级 `Map<sessionId, cwd>`(header 不可变,无需 TTL;上限 256),并发同会话共享一个在飞 promise;`stat` 缺失或失败返回 undefined(降级到提示,不打断路由)。 |
|
||||
| `src/index.ts` `sessionCwdOf()` | 删除 `observeSession` 分支与 `readPersistedSession` 兜底;顺序改为 live committed → 存储 header(相对路径拒绝为 `bad-request`)→ 宿主 defaultDirectory → 客户端提示 → 进程 cwd。 |
|
||||
| `src/active-worktree.ts` | `activeWorktreeRootOf()` 在 `ctx.sessions.get(id) === undefined` 时直接返回 base。 |
|
||||
| `src/context-types.ts` | `SidebarSessionPersistenceService` 增加可选 `stat`;删除已无消费者的 `sessionQuery` 镜像。 |
|
||||
| `tests/smoke.spec.ts` | 重写该组 8 例:header 优先于陈旧提示、header 只读一次、12 并发共享一次、无 `stat`/`stat` 失败回落提示、live committed 优先、相对 cwd 拒绝、defaultDirectory 兜底、进程 cwd 兜底。 |
|
||||
|
||||
## 五、验证
|
||||
|
||||
**已执行**:`pnpm typecheck` 通过;`pnpm exec vitest run tests/smoke.spec.ts tests/active-worktree.spec.ts` → 89 passed,1 failed(`serves a home-relative media path`,`mkdir $HOME/.dsh-sidebar-selftest-*` 被本会话文件沙箱拒绝;在未改动的 `dev` 上同样失败,判为环境限制)。
|
||||
|
||||
**未执行**:没有 39.9 MB 真机会话,未在本机复现「36 → ?」的读次数变化。可证伪预测:同一场景下 `readStableSnapshot` 的调用数应降到 **每个冷会话 ≤1 次**(header 读不走该函数时直接归零),且 fs-watch 帧不再触发任何整份读。
|
||||
|
||||
## 六、留下的读取面(不在本次范围)
|
||||
|
||||
- `changes.ops` 冷读整份日志(无 memo),`sidechat.events` 冷读有结果 memo 但无在飞去重。
|
||||
- 这两条只在对应页签打开时触发,不是启动期风暴源;若后续要彻底消灭整读,再单独处理。
|
||||
@@ -28,8 +28,10 @@
|
||||
* Resolutions are cached process-wide ({@link ACTIVE_ROOT_TTL_MS}), concurrent
|
||||
* callers share one in-flight resolution AND one in-flight base probe, and
|
||||
* every cache is bounded — so the client's periodic re-ask, the debounced
|
||||
* fs-watch frames and the twelve route handlers that funnel through
|
||||
* `cwdOf()` are answered without a process spawn after the first scan.
|
||||
* fs-watch frames and the route handlers that funnel through `cwdOf()` are
|
||||
* answered without a process spawn after the first scan. A DETACHED session is
|
||||
* answered with its base (the workspace address) and never folds the stored
|
||||
* log — see {@link activeWorktreeRootOf}.
|
||||
*/
|
||||
import { stat } from 'node:fs/promises'
|
||||
import { dirname, isAbsolute, join, sep } from 'node:path'
|
||||
@@ -463,6 +465,11 @@ export async function activeWorktreeRootOf(ctx: Context, sessionId: string, base
|
||||
if (base === '') return base
|
||||
const override = (process.env[ACTIVE_ROOT_OVERRIDE_ENV] ?? '').trim()
|
||||
if (override !== '' && isAbsolute(override)) return requireAbsolute(override)
|
||||
// A detached session has no live event log, and folding its STORED one means
|
||||
// decoding the whole artifact (39 MB here) for a follow-the-agent nicety the
|
||||
// workspace address already answers: while cold, the session's header cwd IS
|
||||
// the root. Attaching the session re-enables the fold on the next ask.
|
||||
if (ctx.sessions.get(sessionId) === undefined) return base
|
||||
// The comparison is on the raw base, so a session whose caller switched base
|
||||
// (a committed working_directory change) never reuses the other
|
||||
// one's root.
|
||||
|
||||
+14
-8
@@ -501,6 +501,20 @@ export interface SidebarSessionTitleService {
|
||||
*/
|
||||
export interface SidebarSessionPersistenceService {
|
||||
open(sessionId: string, access: 'read' | 'write'): Promise<SidebarSessionHandle>
|
||||
/**
|
||||
* Header-only snapshot of ONE stored session (revision + immutable header).
|
||||
* The cold cwd resolver reads the stored header through this: it is the one
|
||||
* persistence call that never decodes the log. Absent on a host without it —
|
||||
* every caller must degrade to a client hint.
|
||||
*/
|
||||
stat?(sessionId: string): Promise<{
|
||||
/** Immutable stored header (cwd / agentPreset live here). */
|
||||
header: { cwd?: string; agentPreset?: string } & Record<string, unknown>
|
||||
/** Opaque change token of the stored artifact. */
|
||||
revision?: unknown
|
||||
/** Physical artifact size in bytes, when the backend can provide it. */
|
||||
sizeBytes?: number
|
||||
} | undefined>
|
||||
}
|
||||
|
||||
/** One open channel onto a stored session (the fields this plugin reads). */
|
||||
@@ -859,14 +873,6 @@ export interface SidebarContextShape {
|
||||
readonly defaultDirectory?: string
|
||||
get(session: { header: SidebarSessionHeader }): string
|
||||
}
|
||||
/** Host-owned live/prepared observation, including cold-session projections. */
|
||||
sessionQuery: {
|
||||
observeSession(id: string, options: { projectionMode: 'all' }): Promise<{
|
||||
header: SidebarSessionHeader
|
||||
projections?: { values: { workingDirectory?: string | null } }
|
||||
[Symbol.dispose](): void
|
||||
}>
|
||||
}
|
||||
/** Native host request admission and client transport recovery. */
|
||||
connection: SidebarConnectionService
|
||||
/** The client slot registry (register/inject). */
|
||||
|
||||
+98
-39
@@ -49,7 +49,6 @@ import { buildSidechatApi } from './sidechat-routes.ts'
|
||||
import { createAssistantLiveBuffer, type AssistantLiveBuffer } from './assistant-live.ts'
|
||||
import { readJsonBody, readTextBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts'
|
||||
import { streamFileToResponse } from './file-stream.ts'
|
||||
import { readPersistedSession } from './session-store.ts'
|
||||
import { createChangesOpsApi } from './changes-ops.ts'
|
||||
import { BlockAssembler, createUserMessage, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm'
|
||||
import {
|
||||
@@ -133,31 +132,105 @@ export function mediaTypeForPath(path: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the committed execution directory before client or original-header
|
||||
* hints. Live reads are synchronous; detached reads use the host observation
|
||||
* lease and its revision-keyed projection cache, never a plugin-owned log fold
|
||||
* or TTL that could hide a working_directory change.
|
||||
* Stored header cwd per session id, kept for the process lifetime.
|
||||
*
|
||||
* A session header is immutable, so once read the workspace address cannot
|
||||
* change. The map is bounded and every entry is a short string; it exists so
|
||||
* the sidebar's re-asks (every watch frame, every 5 s poll, every route) do
|
||||
* not even pay the header read.
|
||||
*/
|
||||
const storedCwdCache = new Map<string, string>()
|
||||
/** Per-session in-flight header read (the same-key sharing for a cold burst). */
|
||||
const storedCwdInFlight = new Map<string, Promise<string | undefined>>()
|
||||
/** Bound on {@link storedCwdCache}; well above any plausible open-session set. */
|
||||
const STORED_CWD_CACHE_MAX = 256
|
||||
|
||||
/**
|
||||
* The workspace address of a session the host has not attached: the cwd stored
|
||||
* in its immutable header.
|
||||
*
|
||||
* This is a HEADER-ONLY read (`sessionPersistence.stat` reads the first zstd
|
||||
* frame, never the log). It is deliberately not `sessionQuery.observeSession`:
|
||||
* that public cold-cwd API decodes the WHOLE artifact and hydrates every
|
||||
* projection to answer with one string, and a startup burst asks dozens of
|
||||
* times in parallel (0.28.0: 39 MB × 44 ≈ 1.7 GB, OOM). The committed
|
||||
* working_directory is adopted again the moment the host attaches the session
|
||||
* (see {@link sessionCwdOf}).
|
||||
* @param ctx - host plugin context.
|
||||
* @param sessionId - the detached session to locate.
|
||||
* @returns the stored header cwd, or undefined when the host cannot answer.
|
||||
*/
|
||||
async function storedHeaderCwdOf(ctx: Context, sessionId: string): Promise<string | undefined> {
|
||||
const cached = storedCwdCache.get(sessionId)
|
||||
if (cached !== undefined) return cached
|
||||
const pending = storedCwdInFlight.get(sessionId)
|
||||
if (pending !== undefined) return pending
|
||||
const promise = (async (): Promise<string | undefined> => {
|
||||
const persistence = ctx.get('sessionPersistence')
|
||||
if (persistence?.stat === undefined) return undefined
|
||||
try {
|
||||
const snapshot = await persistence.stat(sessionId)
|
||||
const cwd = snapshot?.header.cwd
|
||||
if (cwd === undefined || cwd === '') return undefined
|
||||
storedCwdCache.set(sessionId, cwd)
|
||||
while (storedCwdCache.size > STORED_CWD_CACHE_MAX) {
|
||||
const oldest = storedCwdCache.keys().next()
|
||||
if (oldest.done) break
|
||||
storedCwdCache.delete(oldest.value)
|
||||
}
|
||||
return cwd
|
||||
} catch (error) {
|
||||
// A header read that fails must not take a whole route down: the client
|
||||
// hint below is the same workspace address in every normal deployment.
|
||||
ctx.logger.warn('dsh-better-sidebar: cannot stat stored session %s', sessionId)
|
||||
ctx.logger.warn(error)
|
||||
return undefined
|
||||
}
|
||||
})()
|
||||
storedCwdInFlight.set(sessionId, promise)
|
||||
try {
|
||||
return await promise
|
||||
} finally {
|
||||
storedCwdInFlight.delete(sessionId)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the directory a session's file/Git routes are rooted at.
|
||||
*
|
||||
* An attached session answers from the host's committed working directory
|
||||
* (following `cd` and linked worktrees), synchronously. A DETACHED session
|
||||
* answers from its stored header — the workspace address — because the only
|
||||
* public cold-cwd API decodes the whole log for that one string (see
|
||||
* {@link storedHeaderCwdOf}); the committed directory takes over again on the
|
||||
* next ask after the host attaches the session.
|
||||
* @param ctx - host plugin context.
|
||||
* @param sessionId - the session whose workspace is resolved.
|
||||
* @param clientCwd - the client's summary cwd, used only when the host cannot
|
||||
* answer at all.
|
||||
* @returns the absolute workspace directory.
|
||||
*/
|
||||
async function sessionCwdOf(ctx: Context, sessionId: string, clientCwd?: string): Promise<string> {
|
||||
const session = ctx.sessions.get(sessionId)
|
||||
// The immutable header is the original project, not the current execution
|
||||
// directory. Read the host's committed value on every request (no TTL).
|
||||
// The immutable header here is the fallback, not the authority: the host's
|
||||
// committed value tracks `cd` and wins whenever it is available.
|
||||
if (session !== undefined) {
|
||||
const cwd = ctx.get('workingDirectory')?.get(session) ?? session.header.cwd
|
||||
if (cwd !== undefined && cwd !== '') return cwd
|
||||
}
|
||||
const query = ctx.get('sessionQuery')
|
||||
if (query !== undefined) {
|
||||
const observation = await query.observeSession(sessionId, { projectionMode: 'all' })
|
||||
const stored = await storedHeaderCwdOf(ctx, sessionId)
|
||||
if (stored !== undefined) {
|
||||
// A corrupt relative cwd must be refused here: resolving it against the
|
||||
// host process cwd is exactly the "outside workspace" misclassification
|
||||
// the header read exists to avoid.
|
||||
try {
|
||||
const cwd = observation.projections?.values.workingDirectory
|
||||
?? observation.header.cwd
|
||||
?? ctx.get('workingDirectory')?.defaultDirectory
|
||||
if (cwd !== undefined && cwd !== '') return requireAbsolute(cwd)
|
||||
} finally {
|
||||
observation[Symbol.dispose]()
|
||||
return requireAbsolute(stored)
|
||||
} catch {
|
||||
throw new SidebarError('bad-request', `invalid working directory "${stored}"`)
|
||||
}
|
||||
}
|
||||
const defaultDirectory = ctx.get('workingDirectory')?.defaultDirectory
|
||||
if (defaultDirectory !== undefined && defaultDirectory !== '') return requireAbsolute(defaultDirectory)
|
||||
if (clientCwd !== undefined && clientCwd !== '') {
|
||||
try {
|
||||
return requireAbsolute(clientCwd)
|
||||
@@ -165,18 +238,6 @@ async function sessionCwdOf(ctx: Context, sessionId: string, clientCwd?: string)
|
||||
throw new SidebarError('bad-request', `invalid working directory "${clientCwd}"`)
|
||||
}
|
||||
}
|
||||
const persistence = ctx.get('sessionPersistence')
|
||||
if (persistence !== undefined) {
|
||||
const persisted = await readPersistedSession(persistence, sessionId)
|
||||
const metaCwd = persisted.header.cwd
|
||||
if (metaCwd !== undefined && metaCwd !== '') {
|
||||
try {
|
||||
return requireAbsolute(metaCwd)
|
||||
} catch {
|
||||
throw new SidebarError('bad-request', `invalid working directory "${metaCwd}"`)
|
||||
}
|
||||
}
|
||||
}
|
||||
return process.cwd()
|
||||
}
|
||||
|
||||
@@ -636,17 +697,15 @@ function buildApi(
|
||||
archiveTasks: ArchiveTasks,
|
||||
): Record<string, ApiMethod> {
|
||||
/**
|
||||
* Same-key sharing for the shared cwd path. All twelve routes below resolve
|
||||
* the session cwd through here, and a session switch fires them at once. A
|
||||
* detached (cold) session costs one host observation per call — a full log
|
||||
* read plus decode, e.g. 39 MB for a large session — and the host's cold
|
||||
* cache only helps AFTER a read completes; concurrent same-key asks all miss
|
||||
* it. A client burst therefore used to decode the same log N times in
|
||||
* parallel (44 × 39 MB ≈ 1.7 GB, OOM on 0.28.0). Concurrent asks for the same
|
||||
* session + client hint now share ONE resolution; the hint is part of the key
|
||||
* because it is a fallback the result depends on. No TTL: the host already
|
||||
* caches completed cold reads by persistence revision, so the leader's result
|
||||
* is what every follower and every later ask reuses.
|
||||
* Same-key sharing for the shared cwd path. Every file/Git route below
|
||||
* resolves the session cwd through here, and a session switch fires them at
|
||||
* once. Cold resolution is now a header-only read (see `storedHeaderCwdOf`),
|
||||
* but the whole resolution still folds the active-worktree scan, so sharing
|
||||
* one leader keeps a burst from repeating that too. Concurrent asks for the
|
||||
* same session + client hint share ONE resolution; the hint is part of the
|
||||
* key because it is a fallback the result depends on. No TTL: the stored
|
||||
* header is memoized, and a live session's committed directory is re-read on
|
||||
* every ask after this short-lived entry is dropped.
|
||||
*/
|
||||
const cwdInFlight = new Map<string, Promise<{ sessionId: string; cwd: string }>>()
|
||||
const cwdOf = async (payload: unknown): Promise<{ sessionId: string; cwd: string }> => {
|
||||
|
||||
@@ -162,6 +162,24 @@ describe('active worktree root', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('answers a detached session with its base and never reads the stored log', async () => {
|
||||
// A detached session has no live events; folding the STORED log would decode
|
||||
// the whole artifact for a follow-the-agent nicety the workspace address
|
||||
// already answers. The guard must return before any persistence read or git
|
||||
// probe — this is what removes the startup read storm.
|
||||
const opened: string[] = []
|
||||
probed.length = 0
|
||||
const ctx = {
|
||||
sessions: { get: () => undefined },
|
||||
get: (key: string) => key === 'sessionPersistence'
|
||||
? { open: async (id: string) => { opened.push(id); throw new Error('a detached session must not be read') } }
|
||||
: undefined,
|
||||
} as never
|
||||
await expect(activeWorktreeRootOf(ctx, 's-detached', '/tmp/workspace-address')).resolves.toBe('/tmp/workspace-address')
|
||||
expect(opened, 'no persistence read for a detached session').toEqual([])
|
||||
expect(probed, 'no git probe once the base is the answer').toEqual([])
|
||||
})
|
||||
|
||||
it('probes the REAL path, never its case-folded identity (Linux is case-sensitive)', async () => {
|
||||
// `addActivePath` keys candidates by a lowercased identity; probing that
|
||||
// KEY instead of the path silently drops every candidate whose path has an
|
||||
|
||||
+70
-76
@@ -496,9 +496,11 @@ describe('git destructive operations (scratch repository)', () => {
|
||||
describe('session cwd resolution over the API route', () => {
|
||||
interface CtxOverrides {
|
||||
workingDirectory?: { readonly defaultDirectory?: string; get: (session: { header: { cwd?: string } }) => string }
|
||||
sessionQuery?: { observeSession: (id: string, options: { projectionMode: 'all' }) => Promise<{ header: { cwd?: string }; projections?: { values: { workingDirectory?: string | null } }; [Symbol.dispose](): void }> }
|
||||
sessions?: { get: (id: string) => { header: { cwd?: string } } | undefined }
|
||||
sessionPersistence?: { open: (id: string, access: 'read' | 'write') => Promise<{ header: { cwd?: string }; read: () => Promise<{ events: never[] }>; close: () => Promise<void> }> }
|
||||
sessionPersistence?: {
|
||||
open?: (id: string, access: 'read' | 'write') => Promise<{ header: { cwd?: string }; read: () => Promise<{ events: never[] }>; close: () => Promise<void> }>
|
||||
stat?: (id: string) => Promise<{ header: { cwd?: string } } | undefined>
|
||||
}
|
||||
}
|
||||
|
||||
const mountAll = (overrides: CtxOverrides = {}): SidebarWebRoute[] => {
|
||||
@@ -520,6 +522,7 @@ describe('session cwd resolution over the API route', () => {
|
||||
on: () => () => {},
|
||||
// No jobs/agents services in the smoke context: the routes degrade.
|
||||
get: (key: string) => overrides[key as keyof CtxOverrides],
|
||||
logger: { info: () => {}, warn: () => {}, debug: () => {}, error: () => {} },
|
||||
}
|
||||
apply(ctx as never)
|
||||
return routes
|
||||
@@ -785,56 +788,64 @@ describe('session cwd resolution over the API route', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('uses cold observation working-directory projections before stale client/header hints and releases every lease', async () => {
|
||||
let current = resolvePath('/cold-execution-first')
|
||||
let releases = 0
|
||||
const route = mount({ sessionQuery: {
|
||||
observeSession: async (id, options) => {
|
||||
expect(id).toBe('wd-cold')
|
||||
expect(options).toEqual({ projectionMode: 'all' })
|
||||
return {
|
||||
header: { cwd: resolvePath('/original-project') },
|
||||
projections: { values: { workingDirectory: current } },
|
||||
[Symbol.dispose]: () => { releases += 1 },
|
||||
}
|
||||
},
|
||||
} })
|
||||
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-cold', cwd: '/stale-client' })).toMatchObject({ ok: true, value: { cwd: current } })
|
||||
current = resolvePath('/cold-execution-second')
|
||||
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-cold', cwd: '/stale-client' })).toMatchObject({ ok: true, value: { cwd: current } })
|
||||
expect(releases).toBe(2)
|
||||
it('roots a detached session at its stored header cwd (the workspace address) before a stale client hint', async () => {
|
||||
const reads: string[] = []
|
||||
const route = mount({ sessionPersistence: { stat: async (id) => {
|
||||
reads.push(id)
|
||||
return { header: { cwd: resolvePath('/stored-workspace') } }
|
||||
} } })
|
||||
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-stored', cwd: '/stale-client' })).toMatchObject({
|
||||
ok: true, value: { cwd: resolvePath('/stored-workspace') },
|
||||
})
|
||||
expect(reads).toEqual(['wd-stored'])
|
||||
})
|
||||
|
||||
it('shares one cold observation between concurrent same-session cwd calls', async () => {
|
||||
it('memoizes the stored header so later asks never read it again', async () => {
|
||||
let reads = 0
|
||||
const route = mount({ sessionPersistence: { stat: async () => {
|
||||
reads += 1
|
||||
return { header: { cwd: resolvePath('/stored-memo') } }
|
||||
} } })
|
||||
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-memo' })).toMatchObject({ ok: true, value: { cwd: resolvePath('/stored-memo') } })
|
||||
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-memo' })).toMatchObject({ ok: true, value: { cwd: resolvePath('/stored-memo') } })
|
||||
// A session header is immutable: one read answers every later ask.
|
||||
expect(reads).toBe(1)
|
||||
})
|
||||
|
||||
it('shares one stored-header read between concurrent same-session cwd calls', async () => {
|
||||
let reads = 0
|
||||
let releases = 0
|
||||
let unblock!: () => void
|
||||
const gate = new Promise<void>((resolve) => { unblock = resolve })
|
||||
const shared = resolvePath('/cold-shared-execution')
|
||||
const route = mount({ sessionQuery: {
|
||||
observeSession: async () => {
|
||||
reads += 1
|
||||
await gate
|
||||
return {
|
||||
header: { cwd: resolvePath('/original-project') },
|
||||
projections: { values: { workingDirectory: shared } },
|
||||
[Symbol.dispose]: () => { releases += 1 },
|
||||
}
|
||||
},
|
||||
} })
|
||||
// A session switch fires the twelve routes at once; every one needs cwd.
|
||||
const shared = resolvePath('/stored-shared')
|
||||
const route = mount({ sessionPersistence: { stat: async () => {
|
||||
reads += 1
|
||||
await gate
|
||||
return { header: { cwd: shared } }
|
||||
} } })
|
||||
// A cold burst (a session switch, or one watch socket's reconcile) fires
|
||||
// many asks at once; every one must not cost its own header read.
|
||||
const calls = Array.from({ length: 12 }, () =>
|
||||
invoke(route, 'session.cwd', { sessionId: 'wd-shared', cwd: '/stale-client' }))
|
||||
await Promise.resolve()
|
||||
unblock()
|
||||
const results = await Promise.all(calls)
|
||||
expect(reads, 'concurrent same-key asks must share ONE cold read').toBe(1)
|
||||
expect(releases, 'the shared observation is released once').toBe(1)
|
||||
expect(reads, 'concurrent same-session asks must share ONE header read').toBe(1)
|
||||
for (const result of results) {
|
||||
expect(result).toMatchObject({ ok: true, value: { cwd: shared } })
|
||||
}
|
||||
})
|
||||
|
||||
it('falls back to the client hint when the host cannot stat the session', async () => {
|
||||
const absent = mount()
|
||||
expect(await invoke(absent, 'session.cwd', { sessionId: 'wd-no-stat', cwd: '/tmp/hint-absent' })).toMatchObject({
|
||||
ok: true, value: { cwd: resolvePath('/tmp/hint-absent') },
|
||||
})
|
||||
const failing = mount({ sessionPersistence: { stat: async () => { throw new Error('stored artifact unreadable') } } })
|
||||
expect(await invoke(failing, 'session.cwd', { sessionId: 'wd-stat-error', cwd: '/tmp/hint-failing' })).toMatchObject({
|
||||
ok: true, value: { cwd: resolvePath('/tmp/hint-failing') },
|
||||
})
|
||||
})
|
||||
|
||||
it('does not share a resolution across different client cwd hints', async () => {
|
||||
const route = mount({})
|
||||
const [first, second] = await Promise.all([
|
||||
@@ -845,36 +856,29 @@ describe('session cwd resolution over the API route', () => {
|
||||
expect(second).toMatchObject({ ok: true, value: { cwd: resolvePath('/hint-b') } })
|
||||
})
|
||||
|
||||
it('uses the host custom default for a null cold working-directory projection before a stale client hint', async () => {
|
||||
it('uses the host custom default when the stored header carries no cwd', async () => {
|
||||
const defaultDirectory = resolvePath('/configured-execution-default')
|
||||
let releases = 0
|
||||
const route = mount({
|
||||
workingDirectory: { defaultDirectory, get: () => { throw new Error('cold reads must not call get without a live session') } },
|
||||
sessionQuery: { observeSession: async () => ({
|
||||
header: {}, projections: { values: { workingDirectory: null } },
|
||||
[Symbol.dispose]: () => { releases += 1 },
|
||||
}) },
|
||||
workingDirectory: { defaultDirectory, get: () => { throw new Error('a detached session must not call get') } },
|
||||
sessionPersistence: { stat: async () => ({ header: {} }) },
|
||||
})
|
||||
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-cold-default', cwd: '/stale-client' })).toMatchObject({
|
||||
ok: true, value: { cwd: defaultDirectory },
|
||||
})
|
||||
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-cold-default', cwd: '/stale-client' })).toMatchObject({ ok: true, value: { cwd: defaultDirectory } })
|
||||
expect(releases).toBe(1)
|
||||
})
|
||||
|
||||
it('releases the cold observation lease when the working-directory projection cannot be read', async () => {
|
||||
let releases = 0
|
||||
const route = mount({ sessionQuery: {
|
||||
observeSession: async () => ({
|
||||
header: { cwd: resolvePath('/original-project') },
|
||||
get projections(): never { throw new Error('working-directory projection failed') },
|
||||
[Symbol.dispose]: () => { releases += 1 },
|
||||
}),
|
||||
} })
|
||||
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-projection-failure', cwd: '/stale-client' })).toMatchObject({
|
||||
ok: false, error: { message: 'working-directory projection failed' },
|
||||
it('keeps the live committed directory ahead of the stored header', async () => {
|
||||
const route = mount({
|
||||
sessions: { get: () => ({ header: { cwd: resolvePath('/original-project') } }) },
|
||||
workingDirectory: { get: () => resolvePath('/committed-execution') },
|
||||
sessionPersistence: { stat: async () => { throw new Error('a live session must not be statted') } },
|
||||
})
|
||||
expect(await invoke(route, 'session.cwd', { sessionId: 'wd-live-committed', cwd: '/stale-client' })).toMatchObject({
|
||||
ok: true, value: { cwd: resolvePath('/committed-execution') },
|
||||
})
|
||||
expect(releases).toBe(1)
|
||||
})
|
||||
|
||||
it('does not mask failed authoritative working-directory reads with stale header or client hints', async () => {
|
||||
it('does not mask a failed live working-directory read with a stale hint', async () => {
|
||||
const live = mount({
|
||||
sessions: { get: () => ({ header: { cwd: resolvePath('/original-project') } }) },
|
||||
workingDirectory: { get: () => { throw new Error('working-directory service failed') } },
|
||||
@@ -882,12 +886,6 @@ describe('session cwd resolution over the API route', () => {
|
||||
expect(await invoke(live, 'session.cwd', { sessionId: 'wd-live-error', cwd: '/stale-client' })).toMatchObject({
|
||||
ok: false, error: { message: 'working-directory service failed' },
|
||||
})
|
||||
const cold = mount({ sessionQuery: {
|
||||
observeSession: async () => { throw new Error('working-directory observation failed') },
|
||||
} })
|
||||
expect(await invoke(cold, 'session.cwd', { sessionId: 'wd-cold-error', cwd: '/stale-client' })).toMatchObject({
|
||||
ok: false, error: { message: 'working-directory observation failed' },
|
||||
})
|
||||
})
|
||||
|
||||
it('uses the client summary cwd while the session is detached', async () => {
|
||||
@@ -937,20 +935,16 @@ describe('session cwd resolution over the API route', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('resolves a cold (detached) session cwd through the persistence index', async () => {
|
||||
it('resolves a cold (detached) session cwd from its stored header', async () => {
|
||||
// Regression: a detached first request (session not yet attached, no
|
||||
// client cwd) must resolve the cwd from the session-persistence index
|
||||
// client cwd) must resolve the cwd from the session-persistence header
|
||||
// instead of the host process cwd. On Windows the host process cwd is
|
||||
// the DSH source root (dsh.cmd's `pushd`), so every user-project path
|
||||
// was misclassified as "outside workspace" by the realpath guard.
|
||||
const coldCwd = resolvePath('/cold-project-cwd')
|
||||
const route = mount({
|
||||
sessionPersistence: {
|
||||
open: async (id) => ({
|
||||
header: id === 's-cold' ? { cwd: coldCwd } : {},
|
||||
read: async () => ({ events: [] }),
|
||||
close: async () => {},
|
||||
}),
|
||||
stat: async (id) => ({ header: id === 's-cold' ? { cwd: coldCwd } : {} }),
|
||||
},
|
||||
})
|
||||
const result = await invoke(route, 'session.cwd', { sessionId: 's-cold' })
|
||||
@@ -958,14 +952,14 @@ describe('session cwd resolution over the API route', () => {
|
||||
expect(result.value?.cwd).toBe(coldCwd)
|
||||
})
|
||||
|
||||
it('rejects a relative cwd from the persistence index', async () => {
|
||||
it('rejects a relative cwd from the stored header', async () => {
|
||||
// A buggy / corrupt persistence layer that stored a relative cwd must
|
||||
// be rejected by requireAbsolute instead of flowing into the workspace
|
||||
// guard, where it would be resolved against the host process cwd and
|
||||
// potentially recreate the original "outside workspace" misclassification.
|
||||
const route = mount({
|
||||
sessionPersistence: {
|
||||
open: async () => ({ header: { cwd: 'relative/path' }, read: async () => ({ events: [] }), close: async () => {} }),
|
||||
stat: async () => ({ header: { cwd: 'relative/path' } }),
|
||||
},
|
||||
})
|
||||
const result = await invoke(route, 'session.cwd', { sessionId: 's-bad' })
|
||||
@@ -973,10 +967,10 @@ describe('session cwd resolution over the API route', () => {
|
||||
expect(result.error?.message).toMatch(/invalid working directory/)
|
||||
})
|
||||
|
||||
it('falls back to the process cwd when persistence has no cwd for the session', async () => {
|
||||
it('falls back to the process cwd when the stored header has no cwd for the session', async () => {
|
||||
const route = mount({
|
||||
sessionPersistence: {
|
||||
open: async () => ({ header: {}, read: async () => ({ events: [] }), close: async () => {} }),
|
||||
stat: async () => ({ header: {} }),
|
||||
},
|
||||
})
|
||||
const result = await invoke(route, 'session.cwd', { sessionId: 's-blank' })
|
||||
|
||||
Reference in new issue
Block a user