A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 切 Project 不再显示、也不再询问上一个 Project 的 Agent(上游 #1165)
lmlihengad30575f63b2
diff --git a/changelog/unreleased/2026-10-18-project-switch-isolation.md b/changelog/unreleased/2026-10-18-project-switch-isolation.mdnew file mode 100644index 00000000..8301b931--- /dev/null+++ b/changelog/unreleased/2026-10-18-project-switch-isolation.md@@ -0,0 +1,40 @@+# Switching Projects no longer shows, or asks about, the previous Project's Agents++- **Date:** 2026-10-18+- **Type:** fix+- **Scope:** `web`++[中文版](2026-10-18-project-switch-isolation.zh.md)++Port of upstream PenguinHarness #1165 (commit `61cd00bb`), adapted to this tree. Switching Projects+in the Web App could show the Agents of the Project just left — the Agents page listed them under+the new Project and opened their settings — and send requests that paired the new Project with an+Agent it does not have, which answered 「该 Agent 已不存在。」 / "This agent no longer exists." A+conversation open at the switch stayed on screen under the new Project. All of it happened more+often on a slow machine, where lists answer out of order and renders lag behind the network.++## Details++- Every Project-scoped answer now carries the Project it was asked for and is applied only while+ that Project is still current, and state held for a Project is published only under that Project+ (`lib/project-scope.ts`). This covers the Project's Agent list, the Session list (its reloads,+ its next pages and the rows handed to it), the machines' Agents the list asks about, the+ organizations' desk and ticket Sessions, the Agents page's machine Agents and the chat page's+ model configuration.+- A Project that disappears from a refreshed Project list is left the way a switch leaves it: the+ Project the app falls back to never shows the old Agents.+- The conversation the route names is shown only under its own Project, whether it came from the+ list, from a direct lookup or was held through a refetch; after a switch the page opens the new+ Project's latest conversation or a new chat.+- An Agent's settings page leaves for the new Project's Agents list on a Project switch instead of+ asking the new Project about that Agent. A late config answer for another Agent is no longer+ shown on the page.+- An Agent's memory listing is keyed by its Project too, so the `default_agent` of one Project no+ longer stands in for another's.+- The cost center's Agent filter belongs to the Project it was chosen in — the `?agentId=` deep+ link to the Project the page was opened in — so after a switch the page reads the new Project+ unfiltered. A usage answer for the Project just left, or for filters changed since, is dropped.+- A Benchmark's page leaves for the new Project's Benchmarks list on a Project switch instead of+ asking the new Project about that Benchmark.+- The sidebar swaps its per-Project groups, pins and registered Workspaces in the render that sees+ the switch instead of in an effect one commit later.diff --git a/changelog/unreleased/2026-10-18-project-switch-isolation.zh.md b/changelog/unreleased/2026-10-18-project-switch-isolation.zh.mdnew file mode 100644index 00000000..15b87d99--- /dev/null+++ b/changelog/unreleased/2026-10-18-project-switch-isolation.zh.md@@ -0,0 +1,20 @@+# 切换 Project 不再显示或请求上一个 Project 的 Agent++- **Date:** 2026-10-18+- **Type:** fix+- **Scope:** `web`++[English](2026-10-18-project-switch-isolation.md)++移植自上游 PenguinHarness #1165(提交 `61cd00bb`),按本树改写。在 Web App 里切换 Project 时,可能出现刚离开的 Project 的 Agent:智能体页把它们列在新 Project 下,还能打开其设置;同时会发出把新 Project 与它并不拥有的 Agent 配对的请求,得到「该 Agent 已不存在。」。切换时打开着的对话也会留在新 Project 下。机器越慢越常见:列表的应答次序被打乱,渲染落后于网络。++## 细节++- 每个 Project 范围的应答都带上发起请求时的 Project,只在该 Project 仍是当前 Project 时才生效;为某个 Project 保存的状态也只在该 Project 下发布(`lib/project-scope.ts`)。覆盖 Project 的 Agent 列表、会话列表(重新加载、翻页与外部交给它的行)、会话列表询问的机器 Agent、组织的工位与工单会话、智能体页的机器 Agent,以及对话页的模型配置。+- 当前 Project 从刷新后的 Project 列表中消失时,按切换 Project 的方式离开:回退到的 Project 不会显示旧 Project 的 Agent。+- 路由指向的对话只在其所属 Project 下显示,无论它来自列表、直接查询,还是在重新加载期间被保留;切换后页面打开新 Project 最近的对话或新对话。+- Agent 设置页在切换 Project 时转到新 Project 的智能体列表,不再向新 Project 询问该 Agent;另一个 Agent 迟到的配置应答也不再显示在页面上。+- Agent 的记忆列表同样按 Project 区分,一个 Project 的 `default_agent` 不再顶替另一个 Project 的。+- 成本中心的 Agent 筛选归属于选定它时的 Project(`?agentId=` 深链接归属于打开页面时的 Project),切换后页面按新 Project 不加筛选读取;刚离开的 Project 的用量应答,或筛选已改变后才到的应答,一律丢弃。+- Benchmark 详情页在切换 Project 时转到新 Project 的 Benchmark 列表,不再向新 Project 询问该 Benchmark。+- 侧栏改为在看见切换的那一次渲染里换上该 Project 的分组、固定项与注册过的 Workspace,而不是晚一个提交的 effect。diff --git a/docs/FORK-PROGRESS.md b/docs/FORK-PROGRESS.mdindex 0a1b5c08..2bdaca9d 100644--- a/docs/FORK-PROGRESS.md+++ b/docs/FORK-PROGRESS.md@@ -973,6 +973,22 @@ mock 路由导入序、`chat-page.tsx` 的旧探针体),自带 4 份用例本地化:只因本树把 status 推导放在路由里、标签走 `scheduleFilterLabels()`,两处按本树写法手写解决(`scheduleStatus()` 移到 `runtime/scheduler.ts` 由路由导入;标签仍从字典读)。changelog 按本仓写法改名到本轮日期、去掉上游 PR 行、写明移植来源。细节与实测见「第七十七轮」一节。+- [x] **5.49 切 Project 不再显示、也不再询问上一个 Project 的 Agent**(上游 `61cd00bb` `#1165`,+ **2026-10-18 第七十九轮落地**,提交见该节):一条规则(`lib/project-scope.ts` 的+ `scoped` / `scopedValue` / `scopeKey` / `isCurrentProject` / `ofProject`)覆盖所有 Project 范围的+ 读取 —— Agent 列表只应用最新一次询问且 Project 仍是当前的那份,Project 从刷新后的列表消失时按切换+ 处理;会话列表的 reload / 翻页 / 外部交来的行都核对 Project,Provider 只发布当前 Project 的列表;+ 路由对话只在其所属 Project 下显示(`resolveRoutedSession` / `heldRouteSession` 多一个 `projectId`);+ Agent 设置页与 Benchmark 详情页在切换时离开(`lib/use-opened-in-project.ts`);成本中心的 Agent+ 筛选带着选定它的 Project、只应用最新一次读取;草稿的 Agent 读取等列表确认该 id 后才发;记忆列表按+ Project + Agent 打标;公司会话、智能体页的机器 Agent、会话 Provider 的机器 Agent 与对话页的模型+ 配置同样打标;侧栏改在看见切换的渲染里换上该 Project 的分组 / 固定项 / Workspace(本树的侧栏结构+ 比上游那版新,冲突按本树保留并把声明提前)。**有意未取**:上游新写的页面级单测+ `test/project-switch.test.ts`(要本树没有的 `helpers/dom.ts`、`helpers/admin-settings.ts`、+ `helpers/agent-app.ts` 三件套)、重写后的 `e2e/project-switch.spec.mjs`(同上,依赖两 Project 的+ 新夹具)与 CI 里那条浏览器作业(流水线属 4.x)—— 改为本树自己的 `test/project-scope.test.ts`+ 纯逻辑用例 + `session-project` / `route-session-hold` 的 Project 参数用例,以及真浏览器两态探针。+ 细节与验证见「第七十九轮」一节。- **量过、本轮没移植的一条**:`#834`(`661a7bb2`,web 3 文件 / +53,把对话页的渲染 Agent 从「当前 Agent」换成「路由 Session 自己的 Agent」)。它在**本树可达的状态里都改变不了行为**,理由是可复现的:`agentOf()` 对未知 id 会回退到 `default_agent`、再回退到列表第一个(`#450` 起就是这样),所以@@ -1639,6 +1655,7 @@ v0.2.2」——它只加台账里 v0.2.2 那一节与两行表格,**跟本轮| 2026-10-17 | 7.2(仍未完成) | **浏览器 e2e 的 10 条红压到 3 条**(8 条是夹具/探针结论翻转,**只有 dock 拖拽带是真缺陷**:下侧栏边界拖拽带伸到框架外的一半被框架自己的 `overflow-hidden` 裁掉,改 `ResizeHandle` 贴内侧 `top-0`,连同 `dock-panel.tsx` 注释与 ui 单测、一对 changelog;另修 `theme-shots.mjs` 的陈旧键 `concise title`)。逐条:project-switch 夹具只卸了一个技能、layout 的重叠/底色/工作区选择器、outline 量到按钮、compaction 第二层开合、chat 分组折叠与设置对话框与行菜单时序、compact-abort 的斜杠菜单竞态、skills 的标题同文 | 开工复核 26 条里 10 红与台账逐条对上;修完整套 **76 条 73 通过 / 3 失败**,只剩 `llm-errors` 三条;六包 `typecheck` **EXIT=0**(`ifaces.json unchanged`,192 接口 / 587 类型);`npx oxlint` **0 警告 0 错误**(2209 文件);逐包 test 全绿 —— core **1396** / 6 跳过 · ui **1043** · cli **561** · web **3187** / 2 跳过 · server **2937** / 4 跳过(hmr 无测试);真浏览器两态验证 dock 拖拽:改前带子中心命中框架、拖 120 px 高度变化 0,改后命中带子、**276 → 394**;端口只用 8950 / 8952,数据根 `/root/adelie-fork-data/r76-*` | 见本行提交 || 2026-10-18 | 5.48 | **结束的定时任务移入 `schedule/expired/`**(上游 `4b10a219` `#1159` 移植,照改动落、不是合分支;27 文件 / +644 −92,含 changelog 一对):`done` / `missed` / `expired` 三种状态统称 settled,文件**原样**移进 `agent_state/schedule/expired/` 并清掉运行状态,三处调用(对账、`listAgent`、`send` 的 `markFired` 之后与 `schedule_fired` 之前);同名不覆盖(UTC 戳后缀,再冲突 `-2`…),移动失败记 `schedule_archive_failed` 留着下轮再试;状态推导从路由搬进 `runtime/scheduler.ts`(`scheduleStatus()` / `isSettledStatus()`);**破坏性**:`POST` / `PUT` 对过去时刻的一次性任务与过去 `end_at` 返回 400(过去 API 写入的这类任务会立刻执行一次);Web 定时任务面板去掉「已完成」筛选、两份词典删 `filterCompleted`;CLI 帮助、AI 创建提示词、`penguin-orchestration` 技能与五份引擎文档(中英)跟上。**本树两处手写解决**:路由里那份 `statusOf()` 改导入共享函数;标签仍走 `scheduleFilterLabels()` 只删 `completed` 键 | 六包 `typecheck` **`EXIT=0`**(`src/ifaces.json unchanged`,192 接口 / 587 类型)· `npx oxlint` **0 警告 0 错误**(2209 文件)· 改动文件 `prettier --check` 干净 · `git diff --check` 干净 · 逐包 test **`EXIT=0`、0 失败**:server **201 文件 / 2946 通过 / 4 跳过**(+9 即本笔新用例)· core **1396** / 6 跳过 · ui **1043** · cli **561** · web **259 文件 / 3187 通过 / 2 跳过** · docs **62** · **真服务(8977,一次性数据根 `r77`)**:过去 `startAt` 的一次性任务 **400**、过去 `endAt` 的周期任务 **400**、合法周期任务 **201**;手写的过期一次性任务在下一次读取时已移入 `expired/`、**字节与原文相同**,`schedule/` 只剩周期任务,`scheduleCount` 与列表都只剩它 · **真界面**:`/schedules` 页与停靠栏面板都只剩 全部 / 生效中 / 已暂停(无「已完成」),两态 console **0 error**、无一条 ≥400,截图 `r77/{schedules-page,dock-schedules}.png` · 端口只用 8977(跑完即停),3003 / 3004 / 4000 / 7364 / 7369 一个没碰 | 见本行提交 || 2026-10-18 | 7.2 | **浏览器 e2e 整 77 条全绿**(不是移植,是三条陈旧夹具跟上上游 #458 的四级停止原因;3 个跟踪文件 + 一对 changelog,**无产品行为改动**):`mock-llm.mjs` 的三个配额分支换成两条可重试失败(截断流 → `malformed`;持续 503 供放弃那条)+ 一条配额致命 403;`llm-errors.spec.mjs` 四条按今天的语义重写 —— ①截断流 → 倒计时(2 秒退避基数)→ 秒数真的在减 →「立即重试」→ 成功,Trace `retryable/malformed/retry_in_ms=2000`;②放弃 → `[已中断]` +「第 N 次尝试后放弃」+ abort `backoff_interrupted`;③新增配额 403 致命用例(一次尝试、`fatal/rejected`、提供方原文、无重试行、输入框可用);④认证 401 改为 `fatal/auth` + 错误横幅带 `invalid_api_key` 原文、改 key 后同一会话继续。`isAuthenticationError()` 那段与致命判定矛盾的注释一并改正。**关键发现**:第七十六轮记的「要用户拍板 A/B」不成立 —— 403 致命是 #458 定下、`core/test/llm.test.ts` 一直钉着的口径,旧用例里的「模型 API 认证失败」提示在上游与本树都不存在 | 六包 `typecheck` **`EXIT=0`**(`src/ifaces.json unchanged`,192 接口 / 587 类型)· 逐包 test **`EXIT=0`、0 失败**:core **1396** / 6 跳过 · ui **1043** · cli **561** · server **201 文件 / 2946 通过 / 4 跳过** · web **259 文件 / 3187 通过 / 2 跳过** · **真服务端 + 真浏览器整套**(数据根 `/root/adelie-fork-data/r78-full`、`localhost:8930` + mock `8931`):**77 passed (5.7m)、0 failed**;四条 `llm-errors` 单独跑 4/4(9.2s)· **反证**:改前同一套实测 **3 failed**(配额两条没有 `[重试]`、认证一条没有 `已中断`);用 HTTP 503 代替截断流时页面无重试行、Trace 无 `request_end`(5xx 被 SDK 内部吞掉,约 0.4s)· 端口只用 8930 / 8931(跑完已停),3003 / 3004 / 4000 / 7364 / 7369 一个没碰 | `ca164b0f` |+| 2026-10-18 | 5.49 | **切 Project 不再显示、也不再询问上一个 Project 的 Agent**(上游 `61cd00bb` `#1165` 移植,照改动落、不是合分支;17 文件 / +约 560 −约 120,含 changelog 一对,另加本树自己的 `test/project-scope.test.ts`):新增 `lib/project-scope.ts`(`scoped` / `scopedValue` / `scopeKey` / `isCurrentProject` / `ofProject`)与 `lib/use-opened-in-project.ts`(页面在切换时离开);`state/project.tsx` 的 Agent 列表改为打标 + 只应用最新一次询问、Project 消失按切换处理;`state/sessions.tsx` 的 reload / 翻页 / 外部行核对 Project,Provider 只发布当前 Project 的列表、机器 Agent 也打标;`resolveRoutedSession` / `heldRouteSession` 多一个 `projectId`;Agent 设置页与 Benchmark 详情页切换即离开;成本中心的 Agent 筛选带 Project 且只应用最新读取;草稿等列表确认 Agent 后才读其配置 / 技能;记忆列表按 Project + Agent 打标;公司会话、智能体页机器 Agent、对话页模型配置同样打标;侧栏改在渲染期换分组。**本树手写解决三处**:`workbench-tabs` / `machine-models` / `agent-employment` / `create-agent-dialog` 等本树没有的导入按缺件剔除;`useMemoryListing` 与 `getAgentConfig` / `getAgentSkills` 本树没有 machineId 参数,只保留 Project 打标;`save` 保持 `Promise<void>`(本树各页签的 `SaveFn` 如此)。**有意未取**:上游页面级单测、重写后的 `project-switch.spec.mjs` 与 CI 作业(要本树没有的测试辅助三件套 / 属 4.x) | 六包 `typecheck` **`EXIT=0`**(web / core / server / ui / cli / hmr;`src/ifaces.json unchanged`,192 接口 / 587 类型)· `npx oxlint` **0 警告 0 错误**(2212 文件)· 改动文件 `prettier --check` 干净 · 逐包 test **`EXIT=0`、0 失败**:web **260 文件 / 3202 通过 / 2 跳过**(+1 文件 / +15 用例)· core **1399** / 6 跳过 · ui **1043** · cli **561** · server **201 文件 / 2946 通过 / 4 跳过** · **真服务 + 真浏览器整套 e2e**(一次性数据根 `r79-full2`、`localhost:8983` + mock `8981`):**77 passed(5.9m)、0 failed** · **反证(同一探针两态)**:用户 A 有 `default_agent` + `Alpha A`、B 只有 `default_agent`,A 的 Agent 列表用 3 s 路由延迟压住、页面停在 `/agents` 时切到 B —— 把守卫临时去掉重建后,B 的智能体页**出现 `Alpha A`**(`alphaUnderB: 1`);恢复守卫重建后同一操作 **0**,console 两态各 0 error,只有非管理员预期的 `machines` 403 · 端口只用 8980 / 8981 / 8982 / 8983(跑完都已停),3003 / 3004 / 4000 / 7364 / 7369 一个没碰;数据只落在 `/root/adelie-fork-data/r79-*` | 见本行提交 |> **2026-10-11 与另一条线的交汇(第三十七轮)**:定时任务触发时(07:00)`git status --short` **不干净**> —— 另一条线(会话 `session-2026-10-05-20-32-50-2ee69aba`)正在做**用户点单**的「回复能复制成纯文本」@@ -10543,3 +10560,93 @@ Escape 再来一次,四次的预算。连跑三次稳定。- **可选的新决定(用户若要才做)**:让 403 配额错误回到重连阶梯(把 `insufficient_user_quota` 这类码排除在 `isFatalProviderRejection` 之外),今天不做。- 卡点原地:**2.2c**、**3.5**、**3.6**、**4.2** / **4.3**、**5.6** / **5.10**。++## 第七十九轮:切 Project 不再显示、也不再询问上一个 Project 的 Agent(2026-10-18,条目 5.49)++### 开工自检与选活理由++- 同步:开工时 `git status --short` 干净,`main` 停在 `21ed7923`,`git fetch origin && git merge --ff-only+ origin/main` = Already up to date(没切分支、没碰 `legacy/main`、没推 upstream)。+- 待办里最靠前的未勾选条目仍是 **2.2c**(剩下的活全在桌面壳一侧与既有部署单元里,本轮纪律不许碰 desktop),+ 其后 **3.5**(要拍板取哪个桌面壳)、**3.6**(模型 key)、**4.1–4.3**(明令不动)、**5.6** / **5.10**+ (要拍板 / 要新依赖)同样不可动;上一轮把 7.2 勾掉了,桌上只剩 `#1165`。+- 上游按 URL 复核:`0eafa6dc` → `ace1bca2` 之后只多了一笔 **`7e08d23f`(`#1152`,56 文件 / +2580+ −734,「一台机器的 Agent 属于那台机器」)**,`git apply -3 --check` 要改的 `api-session-settings.tsx`、+ `create-agent-dialog.tsx`、`mcp-server-dialog.tsx`、`workbenches-tab.tsx`、`plugin-card.tsx`、+ `plugin-mcp.tsx` 六个文件本树都没有(属 #1153 / #1133 那一整套前置),**不是一轮的量**。+- 所以做 **`#1165`(`61cd00bb`)**:上一轮末尾点名「唯一还值得单独立一轮」的那条,是一条用户看得见的真+ 缺陷(切 Project 后看到上一个 Project 的 Agent、并向新 Project 询问它 → `agent_not_found`+ 「该 Agent 已不存在。」),只碰 `packages/web`,不引入新依赖、不碰桌面壳 / 包名 / 流水线。++### 改了什么(17 个跟踪文件 + 一对 changelog,约 +560 −120)++- **新增两条规则文件**:`packages/web/src/lib/project-scope.ts`(`Scoped<T>` / `scoped` / `scopedValue`+ / `scopeKey` / `isCurrentProject` / `ofProject`)与 `packages/web/src/lib/use-opened-in-project.ts`+ (页面记住自己被打开时的 Project,切换后离开,并在跳转落地前一个提交里什么都不渲染、什么都不问)。+- `state/project.tsx`:Agent 列表改为 `Scoped<AgentSummary[]>`,每次 `reloadAgents` 记一个询问序号,只应用+ **最新一次且 Project 仍当前**的应答;`reloadProjects` 发现当前 Project 消失时按切换重置(同一个 set);+ 上下文只发布当前 Project 的列表(`projectView`),空列表用一个稳定常量。+- `state/sessions.tsx`:`reload` / `loadMoreFor` 除 `gen` 外再核对 Project;`insert` 拒绝不属于当前+ Project 的行;Provider 通过 `sessionsListFor` 只发布当前 Project 的列表(切换的那一个提交里为空且+ loading);机器 Agent 的 JSON 也打上 Project 标。+- `features/chat/session-project.ts`:`resolveRoutedSession` 与 `heldRouteSession` 多一个 `projectId`,+ 列表行、查询到的行与被保留的行都只在其所属 Project 下使用;`chat-page.tsx` 同步传入。+- `features/agents/agent-settings-page.tsx`:配置与错误都按 `scopeKey(projectId, agentId)` 打标,+ `useLeaveOnProjectSwitch(projectId, "/agents")` 在切换时离开;`save` 写回打标后的配置。+- `features/usage/usage-page.tsx`:`?agentId=` 深链接与手选筛选都带上 Project,切换后按新 Project 不加+ 筛选读取;每次读取记序号,只应用最新的那份。+- `features/benchmark/benchmark-detail-page.tsx`:切换时离开到 `/benchmark`,切换后不再读该 id。+- `features/chat/draft-view.tsx`:只有候选列表确认了该 `agentId` 才读它的配置 / 技能(缓存里可能是别的+ Project 的 id),依赖改为 `resolvedAgentId`。+- `features/chat/use-memory-listing.ts`:列表按 `scopeKey(projectId, agentId)` 打标,别的 Project 的+ 同名 `default_agent` 不再顶替。+- `state/company.tsx`:`reloadOrgSessions` 记住最新一次读的 Project,迟到的旧 Project 应答不再替换整张图。+- `features/agents/agents-page.tsx`:机器 Agent 列表按 Project 打标;`components/layout/sidebar.tsx`:+ 按 Project 的折叠 / 固定 / 排序 / Workspace 改为在**看见切换的那次渲染**里换(effect 晚一个提交)。+- **本树手写解决的三处**:①上游那一版导入的 `workbench-tabs`、`machine-models`、`agent-employment`、+ `create-agent-dialog` 本树都没有 —— 只取 Project 打标需要的部分,缺件导入剔除;②本树的+ `useMemoryListing` 与 `getAgentConfig` / `getAgentSkills` 还没有 `machineId` 参数(那是上游+ `#1153` / `#1155` 的产物)—— 只保留 Project 打标;③`agent-settings-page` 的 `save` 保持+ `Promise<void>`(本树各页签的 `SaveFn` 如此),只把写回改成打标后的配置。+- **有意未取**:上游新写的页面级单测 `packages/web/test/project-switch.test.ts`(要本树没有的+ `helpers/dom.ts`、`helpers/admin-settings.ts`、`helpers/agent-app.ts`、`helpers/event-source.ts` 的+ `stubEventSource`)、重写后的 `e2e/project-switch.spec.mjs`(同上,且依赖两 Project 的新夹具)与+ CI 里那条浏览器作业(流水线属 4.x)。改为本树自己的用例:新增+ `packages/web/test/project-scope.test.ts`(11 条纯逻辑用例),`session-project.test.ts` 补「切到另一个+ Project 后,查询到的行与列表里的行都不是路由对话」,`route-session-hold.test.ts` 补「Project 变了就释放+ 保留的行」。+- 一对 changelog:`changelog/unreleased/2026-10-18-project-switch-isolation{,.zh}.md`(日期改到本轮、+ 去掉上游 PR 行、写明移植来源;CI 那一条不写,因为本树没取)。++### 验证++- 六包 `typecheck`:**`EXIT=0`**(web / core / server / ui / cli / hmr;`gen:ifaces` 报+ `src/ifaces.json unchanged`,192 接口 / 587 类型 —— 本笔不动服务契约)。+- `npx oxlint`:**0 警告 0 错误**(2212 文件);改动文件 `prettier --check` 干净。+- 逐包 test:全部 `EXIT=0`、**0 失败** —— web **260 文件 / 3202 通过 / 2 跳过**(比上一轮 +1 文件 / +15+ 用例)· core **1399** / 6 跳过 · ui **1043**(129 文件)· cli **561**(38 文件)· server+ **201 文件 / 2946 通过 / 4 跳过**(hmr 无测试文件)。+- **真服务 + 真浏览器整套 e2e**:重建 core / server / web 产物后,一次性数据根+ `/root/adelie-fork-data/r79-full2`、`localhost:8983` 起真服务(`ADELIE_SEED_ADMIN_PASSWORD`),自带+ `mock-llm.mjs` 起在 `8981`,`npx playwright test -c e2e/playwright.config.mjs` →+ **`77 passed (5.9m)`、0 failed**(上一轮同一套 77 条)。中途在复用的数据根上跑过一次,唯一红的是+ `project-switch.spec.mjs` 的建 Project 步骤返回 409(夹具不幂等,不是产品问题);再重跑时+ `llm-errors` / `malformed` 两条红,是 `mock-llm.mjs` 的全局计数器(`transientTurns` /+ `malformedTurns`)已被前一次跑耗尽 —— 重启 mock 后整套全绿。+- **反证(同一个探针,改前 / 改后两态)**:临时把 `state/project.tsx` 的守卫改成恒真、`projectView` 忽略+ 范围标签,重建 web 产物;用户 A 有 `default_agent` + `Alpha A`、Project B 只有 `default_agent`,A 的+ Agent 列表用 Playwright 路由压住 3 秒,页面停在 `/agents` 时切到 B —— **改前**:B 的智能体页出现+ **`Alpha A`**(`alphaUnderB: 1`,页面文本里两张卡);**改后**(恢复守卫重建):同一操作 **0**,页面只有+ General Agent。两态 console 各 **0 error**,唯一 4xx 是非管理员预期的 `GET …/machines` 403。截图+ `r79/agents-under-b.png`(改后)与探针 `r79/probe.mjs` 都在 scratchpad。+- 端口只用 8980 / 8981 / 8982 / 8983(跑完都已停),3003 / 3004 / 4000 / 7364 / 7369 一个没碰;数据只落在+ `/root/adelie-fork-data/r79-{e2e-a,full,full2}`,一个字节没往 `~/.penguin` / `~/.adelie` 里写。+- 没有切版本号、没发 npm、没发安装包、没发发布汇总。++### 下一轮从这里接++- **待办里已没有可做的一轮内条目**:2.2c(桌面壳 / 部署单元)、3.5(拍板)、3.6(模型 key)、+ 4.1–4.3(明令不动)、5.6 / 5.10(拍板 / 新依赖)原地不动;本轮把 `#1165` 收了。+- 上游新尖端 **`7e08d23f`(`#1152`)** 要本树没有的六个文件(#1153 的 Machines 页 / #1133 的 Workbench+ 那一整套)—— 要落它得先把那两套搬进来,属多轮的量;先按 URL 拉一次,看有没有新的小件。+- 卡点原地:**2.2c**、**3.5**、**3.6**、**4.2** / **4.3**、**5.6** / **5.10**。diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 37afa8cd..4e5aed9a 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -598,8 +598,23 @@ export function Sidebar({/** Group header being dragged (its key) and the current group drop hint (target group + which edge). */const [dragGroup, setDragGroup] = useState<string | null>(null);const [groupDropHint, setGroupDropHint] = useState<{ key: string; after: boolean } | null>(null);- // Project resolved on first load / switched: swap in that Project's persisted collapse/pin sets.- useEffect(() => {+ /** Expanded folders (background / archived; collapsed by default), keyed by folderKey — each folder has its own open state. */+ const [openFolders, setOpenFolders] = useState<ReadonlySet<string>>(new Set());+ /** "More" rows with a fetch in flight, keyed `${category}\0${groupKey}` — the row disables and reads "loading" so a page that lands entirely in other groups still visibly did something. */+ const [pendingLoads, setPendingLoads] = useState<ReadonlySet<string>>(new Set());+ /** Per-group display cap for active rows (keyed by group key; absent = SIDEBAR_PAGE_SIZE). "More" raises it a page at a time. */+ const [groupCaps, setGroupCaps] = useState<ReadonlyMap<string, number>>(new Map());+ /** The same display cap per folder (keyed by folderKey; absent = SIDEBAR_PAGE_SIZE), so an expanded folder reveals a page at a time instead of everything a fetch returned. */+ const [folderCaps, setFolderCaps] = useState<ReadonlyMap<string, number>>(new Map());+ /** Which PAGE of groups renders (#139: dozens of Agents/Workspaces made the list too tall to scan), 0-based; reset per Project and on a mode switch, and clamped at render to the pages that still exist. */+ const [groupPage, setGroupPage] = useState(0);+ // Project resolved on first load / switched: swap in that Project's persisted collapse/pin+ // sets, row and group orders and registered Workspaces — in the render that sees the switch+ // (React re-renders before committing), not in an effect: an effect runs a commit late, and+ // that commit would draw the new Project's list with the previous Project's groups.+ const [setsFor, setSetsFor] = useState(currentProjectId);+ if (setsFor !== currentProjectId) {+ setSetsFor(currentProjectId);setCollapsedGroups(loadGroupSet(collapseStoreKey));setPinnedGroups(loadGroupSet(pinStoreKey));setExpandedFolderOnlyGroups(loadGroupSet(folderOnlyStoreKey));@@ -611,18 +626,7 @@ export function Sidebar({// The other Project's groups are gone, and so is any meaning their reveal state had.setGroupCaps(new Map());setFolderCaps(new Map());- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [collapseStoreKey, pinStoreKey, folderOnlyStoreKey, currentProjectId]);- /** Expanded folders (background / archived; collapsed by default), keyed by folderKey — each folder has its own open state. */- const [openFolders, setOpenFolders] = useState<ReadonlySet<string>>(new Set());- /** "More" rows with a fetch in flight, keyed `${category}\0${groupKey}` — the row disables and reads "loading" so a page that lands entirely in other groups still visibly did something. */- const [pendingLoads, setPendingLoads] = useState<ReadonlySet<string>>(new Set());- /** Per-group display cap for active rows (keyed by group key; absent = SIDEBAR_PAGE_SIZE). "More" raises it a page at a time. */- const [groupCaps, setGroupCaps] = useState<ReadonlyMap<string, number>>(new Map());- /** The same display cap per folder (keyed by folderKey; absent = SIDEBAR_PAGE_SIZE), so an expanded folder reveals a page at a time instead of everything a fetch returned. */- const [folderCaps, setFolderCaps] = useState<ReadonlyMap<string, number>>(new Map());- /** Which PAGE of groups renders (#139: dozens of Agents/Workspaces made the list too tall to scan), 0-based; reset per Project and on a mode switch, and clamped at render to the pages that still exist. */- const [groupPage, setGroupPage] = useState(0);+ }/** Session pending delete confirmation (null = none). */const [deletingSession, setDeletingSession] = useState<SessionInfo | null>(null);const [deletingBusy, setDeletingBusy] = useState(false);diff --git a/packages/web/src/features/agents/agent-settings-page.tsx b/packages/web/src/features/agents/agent-settings-page.tsxindex 3d2e0b91..d6f556a5 100644--- a/packages/web/src/features/agents/agent-settings-page.tsx+++ b/packages/web/src/features/agents/agent-settings-page.tsx@@ -56,6 +56,8 @@ import { ApiError } from "../../api/client";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { useDocumentTitle } from "../../lib/use-document-title";+import { scopeKey, scoped, scopedValue, type Scoped } from "../../lib/project-scope";+import { useLeaveOnProjectSwitch } from "../../lib/use-opened-in-project";import { useProject } from "../../state/project";import { useSaveConfirm } from "./save-confirm";import { SkillsTab } from "./skills-tab";@@ -147,10 +149,18 @@ export function AgentSettingsPage() {useDocumentTitle(S.agent.settings);const { currentProject, reloadAgents } = useProject();const projectId = currentProject?.projectId ?? null;+ // The route's Agent is one of the Project the page was opened in: a Project switch leaves for+ // the new Project's Agents, where every tab would otherwise answer "This agent no longer exists."+ const switchedAway = useLeaveOnProjectSwitch(projectId, "/agents");- const [data, setData] = useState<AgentConfigResponse | null>(null);- // ?tab= deep link (from the Agents page's stat icons): a valid key lands the page on that- // tab; missing/unknown values fall back to "overview", exactly the previous behavior.+ /** The config and its load failure, each tagged with the Agent it was read for. */+ const pageScope = scopeKey(projectId, agentId);+ const [dataRead, setDataRead] = useState<Scoped<AgentConfigResponse> | null>(null);+ const data = scopedValue(dataRead, pageScope);+ // The open tab is the `?tab=` value alone (the Agents page's stat icons deep-link with it;+ // missing or unknown values fall back to "overview"). A switch only writes the address, so+ // it is a navigation: while the open tab holds unsaved edits the app's leave guard asks+ // before it happens, and the tab on screen never runs ahead of the address it would leave.const [searchParams, setSearchParams] = useSearchParams();const [tab, setTab] = useState<TabKey>(() =>resolveTabKey(searchParams.get("tab"), TABS, "overview"),@@ -171,27 +181,31 @@ export function AgentSettingsPage() {[setSearchParams],);// Only the initial config load failure renders inline (the page can't show without it); saves/imports report via toast.- const [error, setError] = useState<string | null>(null);+ const [errorRead, setErrorRead] = useState<Scoped<string> | null>(null);+ const error = scopedValue(errorRead, pageScope);const load = useCallback((opts?: { keepStale?: boolean }) => {- if (!projectId || !agentId) return;+ const scope = scopeKey(projectId, agentId);+ if (!projectId || !agentId || scope === null) return;// keepStale refreshes in place: dropping data would skeleton the page, unmount the tab// tree and lose unsaved editor state. Identity changes and whole-state replacements- // (import / config reset) still clear, so no stale agent's config ever shows.- if (!opts?.keepStale) setData(null);- setError(null);+ // (import / config reset) still clear, so no stale agent's config ever shows — and an+ // answer is tagged with the Agent it was asked about, so a late one for the Agent just+ // left is never read as this one's.+ if (!opts?.keepStale) setDataRead(null);+ setErrorRead(null);api.getAgentConfig(projectId, agentId)- .then(setData)- .catch((e: unknown) => setError(apiErrorText(e)));+ .then((res) => setDataRead(scoped(scope, res)))+ .catch((e: unknown) => setErrorRead(scoped(scope, apiErrorText(e))));},[projectId, agentId],);useEffect(() => {- load();- }, [load]);+ if (!switchedAway) load();+ }, [load, switchedAway]);/** Memory-tab config writes (switch, placeholder insert, prompt save): refresh the page's config copy without unmounting the tabs. */const refreshConfig = useCallback(() => load({ keepStale: true }), [load]);@@ -226,10 +240,11 @@ export function AgentSettingsPage() {const save = useCallback(async (update: AgentConfigUpdateRequest) => {- if (!projectId || !agentId) return;+ const scope = scopeKey(projectId, agentId);+ if (!projectId || !agentId || scope === null) return;try {const res = await api.putAgentConfig(projectId, agentId, update);- setData(res);+ setDataRead(scoped(scope, res));// Compaction is the one section core re-reads at every compaction checkpoint, so a save// that changed nothing else lands on a running conversation right away; everything else// still waits for that conversation's next context. The test is "only compaction", not@@ -256,7 +271,9 @@ export function AgentSettingsPage() {[projectId, agentId, reloadAgents],);- if (!projectId) return null;+ // Switched away: nothing of the Agent renders, so no tab asks the new Project about it while+ // the navigation above takes the page to the Agents list.+ if (!projectId || switchedAway) return null;if (error && !data) {return <p className="p-6 text-sm text-red-600 dark:text-red-400">{error}</p>;}diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsxindex 60073e9e..49386502 100644--- a/packages/web/src/features/agents/agents-page.tsx+++ b/packages/web/src/features/agents/agents-page.tsx@@ -82,6 +82,7 @@ import { AiCreateButtons } from "../ai-create/ai-create-buttons";import { mergeAgents } from "../../lib/benchmark-merge";import type { AgentSource } from "../../lib/benchmark-merge";import { useSessions } from "../../state/sessions";+import { scoped, scopedValue, type Scoped } from "../../lib/project-scope";/** Built-in Agent shipped with every Project (default_agent only; the server also rejects deletion, so no delete entry point is shown here). */const BUILTIN_AGENT_IDS = new Set(["default_agent"]);@@ -139,6 +140,9 @@ function pluginPickItems(plugins: readonly PluginItem[]): PickableItem[] {return plugins.map((plugin) => ({ ...plugin, fallbackIcon: ICONS.puzzle }));}+/** No machine Agents read for the current Project (yet): one identity, so the merge memo stays put. */+const NO_MACHINE_AGENTS: AgentSource[] = [];+export function AgentsPage() {const navigate = useNavigate();useDocumentTitle(S.nav.agents);@@ -151,7 +155,8 @@ export function AgentsPage() {* built from this server alone does not have it at all.*/const { machineIds, machineLabels } = useSessions();- const [machineAgents, setMachineAgents] = useState<AgentSource[]>([]);+ /** The machines' own Agents, tagged with the Project they were listed for. */+ const [machineAgentsRead, setMachineAgents] = useState<Scoped<AgentSource[]> | null>(null);const machinesKey = [...machineIds].join(",");/** Header search, the Models page's shape: name, id and description, case-insensitive. */const [query, setQuery] = useState("");@@ -355,8 +360,10 @@ export function AgentsPage() {}};+ // Only the current Project's: the list is reset in the effect below, a commit after a switch.+ const machineAgents = scopedValue(machineAgentsRead, projectId ?? null) ?? NO_MACHINE_AGENTS;useEffect(() => {- setMachineAgents([]);+ setMachineAgents(null);if (!projectId || machinesKey === "") return;let cancelled = false;void Promise.allSettled(@@ -368,7 +375,12 @@ export function AgentsPage() {// A machine that cannot answer contributes no Agents, which is what not reading it// means; this server's own list still stands on its own.if (!cancelled) {- setMachineAgents(answers.flatMap((a) => (a.status === "fulfilled" ? [a.value] : [])));+ setMachineAgents(+ scoped(+ projectId,+ answers.flatMap((a) => (a.status === "fulfilled" ? [a.value] : [])),+ ),+ );}});return () => {diff --git a/packages/web/src/features/benchmark/benchmark-detail-page.tsx b/packages/web/src/features/benchmark/benchmark-detail-page.tsxindex c2e72ff1..b952b537 100644--- a/packages/web/src/features/benchmark/benchmark-detail-page.tsx+++ b/packages/web/src/features/benchmark/benchmark-detail-page.tsx@@ -13,6 +13,7 @@ import * as api from "../../api/endpoints";import type { MergedBenchmark } from "../../lib/benchmark-merge";import { nameOnMachine } from "../../lib/workspace-machines";import { useSessions } from "../../state/sessions";+import { useLeaveOnProjectSwitch } from "../../lib/use-opened-in-project";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { useDocumentTitle } from "../../lib/use-document-title";@@ -49,6 +50,9 @@ export function BenchmarkDetailPage() {const { machineIds, machineLabels } = useSessions();const projectId = currentProject?.projectId ?? null;const isOwner = currentProject?.role === "owner";+ // The route's Benchmark is one of the Project the page was opened in: a Project switch leaves+ // for the new Project's Benchmarks rather than asking that Project about this id.+ const switchedAway = useLeaveOnProjectSwitch(projectId, "/benchmark");const [benchmark, setBenchmark] = useState<MergedBenchmark | null>(null);const [error, setError] = useState<string | null>(null);@@ -63,7 +67,7 @@ export function BenchmarkDetailPage() {// it whole — merged over this server and the machines it holds — and picks its own out of it.const machinesKey = machineIds.join(",");useEffect(() => {- if (!projectId || benchmarkId === "") return;+ if (!projectId || benchmarkId === "" || switchedAway) return;let cancelled = false;setBenchmark(null);setError(null);@@ -81,12 +85,12 @@ export function BenchmarkDetailPage() {return () => {cancelled = true;};- }, [projectId, benchmarkId, machinesKey]);+ }, [projectId, benchmarkId, machinesKey, switchedAway]);// The Project's models, for the Use dialog's conversation-model picker; a failure just leaves// the picker at the Project default.useEffect(() => {- if (!projectId) return;+ if (!projectId || switchedAway) return;let cancelled = false;api.getModels(projectId)@@ -97,9 +101,11 @@ export function BenchmarkDetailPage() {return () => {cancelled = true;};- }, [projectId]);+ }, [projectId, switchedAway]);- if (!projectId) return null;+ // Switched away: nothing of the Benchmark renders (its cases would be asked of the new+ // Project) while the navigation above takes the page to the list.+ if (!projectId || switchedAway) return null;/** The ssh alias of a machine, or null for this server. An unlabelled machine falls back to its id. */const machineNameOf = (machineId: string | null): string | null =>diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex dd1df8b7..d8cc0276 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -136,6 +136,7 @@ import type { SwitchContextShape } from "./model-switch";import { hasConfiguredKey, promotedPricing, sameModelRef } from "../models/model-grouping";import { providerInfo } from "@adelie/core/model-catalog";import { useMemoryListing } from "./use-memory-listing";+import { scoped, scopedValue, type Scoped } from "../../lib/project-scope";import { deletedChangeKeys } from "./memory-nav";import { noteScheduleEvent } from "../schedules/schedule-store";import { DockPanel } from "../dock/dock-panel";@@ -335,7 +336,11 @@ export function ChatPage() {const [credentialGuide, setCredentialGuide] = useState(false);const [infoOpen, setInfoOpen] = useState(false);const [modeSaving, setModeSaving] = useState(false);- const [models, setModels] = useState<ModelsResponse | null>(null);+ /** This server's model configuration for the Project, tagged with the Project it was read for. */+ const [modelsRead, setModels] = useState<Scoped<ModelsResponse> | null>(null);+ // Only the current Project's: the read is reset in an effect, and the draft (remounted per+ // Project in the same commit) would otherwise resolve its model against the last Project's.+ const models = scopedValue(modelsRead, projectId);// Background processes the conversation started (the details popover list), refreshed by// the polling effect below; procBusy marks the rows whose Stop / Remove requests are in// flight (every exited row at once while "clear exited" runs).@@ -476,7 +481,12 @@ export function ChatPage() {* the open conversation. See resolveRoutedSession.*/const [fetchedSession, setFetchedSession] = useState<SessionInfo | null>(null);- const listed = draft ? null : resolveRoutedSession(routeSessionId, sessions, fetchedSession);+ // A Session this page deleted, or heard was deleted, is not shown from a stale lookup either:+ // its route probes, fails at once on the tombstone, and moves on.+ const listed =+ draft || (routeSessionId !== null && isSessionDeleted(routeSessionId))+ ? null+ : resolveRoutedSession(routeSessionId, sessions, fetchedSession, projectId);/*** The routed Session, held across a refetch that momentarily does not list it.*@@ -499,6 +509,7 @@ export function ChatPage() {listed,routeSessionId ?? null,probeKey !== null && probeFailedKey === probeKey,+ projectId,);const selected = draft ? null : heldSession.current;// The tabs beside a conversation are its OWN Agent's, asked of the server that Agent's@@ -1223,7 +1234,7 @@ export function ChatPage() {try {const res = await api.getModels(projectId);if (cancelled) return;- setModels(res);+ setModels(scoped(projectId, res));const { prefs } = await api.getPrefs();if (cancelled || prefs.credentialGuideSeen) return;const def = res.models.find((m) => sameModelRef(m, res.defaultModel));@@ -1257,7 +1268,7 @@ export function ChatPage() {api.getModels(projectId).then((res) => {- if (!cancelled) setModels(res);+ if (!cancelled) setModels(scoped(projectId, res));}).catch(() => undefined);};diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsxindex 6dd75ba3..f30675f0 100644--- a/packages/web/src/features/chat/draft-view.tsx+++ b/packages/web/src/features/chat/draft-view.tsx@@ -465,12 +465,20 @@ export function DraftView({// never written from here. Refetched whenever the draft's Agent changes; while loading// (or after a failed fetch) the picker stays disabled (null).const [agentThinkingLevel, setAgentThinkingLevel] = useState<string | null>(null);+ /**+ * The draft's Agent once the list on offer carries it. Nothing is asked about an id the cache+ * or the route named until then: a cached id may be one this Project does not have (deleted+ * since, or written while another Project's Agents were on screen), and the request would only+ * come back "This agent no longer exists."+ */+ const selectedAgent = agents.find((a) => a.agentId === agentId) ?? null;+ const resolvedAgentId = selectedAgent?.agentId ?? null;useEffect(() => {setAgentThinkingLevel(null);- if (!agentId) return;+ if (!resolvedAgentId) return;let cancelled = false;api- .getAgentConfig(projectId, agentId)+ .getAgentConfig(projectId, resolvedAgentId).then((res) => {if (!cancelled) setAgentThinkingLevel(res.config.model?.thinkingLevel ?? "");})@@ -478,7 +486,7 @@ export function DraftView({return () => {cancelled = true;};- }, [projectId, agentId]);+ }, [projectId, resolvedAgentId]);const thinkingLevel =agentThinkingLevel === null || chatDefaults === null? null@@ -514,10 +522,10 @@ export function DraftView({const [agentSkills, setAgentSkills] = useState<SkillMetadataItem[]>([]);useEffect(() => {setAgentSkills((prev) => (prev.length > 0 ? [] : prev));- if (!agentId) return;+ if (!resolvedAgentId) return;let cancelled = false;api- .getAgentSkills(projectId, agentId)+ .getAgentSkills(projectId, resolvedAgentId).then((res) => {if (!cancelled) setAgentSkills(res.skills);})@@ -525,7 +533,7 @@ export function DraftView({return () => {cancelled = true;};- }, [projectId, agentId]);+ }, [projectId, resolvedAgentId]);// —— Auto-cache ——// Options (Agent / Workspace / approval mode / Model) are discrete clicks: written@@ -827,8 +835,6 @@ export function DraftView({*/const [shortcutsOpen, setShortcutsOpen] = useState(false);- const selectedAgent = agents.find((a) => a.agentId === agentId) ?? null;-// Capability info for the currently selected model (vision/context window) switches instantly with the selection (matched by paired reference).const modelInfo = models?.models.find((m) => sameModelRef(m, modelRef));const contextWindow = modelInfo?.contextWindow;diff --git a/packages/web/src/features/chat/session-project.ts b/packages/web/src/features/chat/session-project.tsindex 94e6ff39..051aa295 100644--- a/packages/web/src/features/chat/session-project.ts+++ b/packages/web/src/features/chat/session-project.ts@@ -1,4 +1,5 @@import type { SessionInfo } from "@adelie/server/api";+import { ofProject } from "../../lib/project-scope";/*** The Session the route names: the loaded list's row when it holds one, otherwise the row a@@ -10,16 +11,23 @@ import type { SessionInfo } from "@adelie/server/api";* is exactly that row, and losing it again is what left the conversation behind the skeleton* for good. The list row still WINS where it exists: it is the one the status and title* events keep current.+ *+ * Either is the routed Session only under its own Project. The looked-up row outlives a Project+ * switch (the route does too), and showing it under the next Project renders that Project with+ * the conversation — and the Agent — of the one just left.*/export function resolveRoutedSession(sessionId: string | null,sessions: readonly SessionInfo[],fetched: SessionInfo | null,+ projectId: string | null,): SessionInfo | null {if (sessionId === null) return null;const row = sessions.find((s) => s.sessionId === sessionId);- if (row !== undefined) return row;- return fetched !== null && fetched.sessionId === sessionId ? fetched : null;+ if (row !== undefined) return ofProject(row, projectId) ? row : null;+ return fetched !== null && fetched.sessionId === sessionId && ofProject(fetched, projectId)+ ? fetched+ : null;}/** Return a probed Session only when it belongs to the Project currently shown by the UI. */@@ -43,17 +51,20 @@ export function sessionProbeKey(projectId: string, sessionId: string): string {* conversation for a tick. Taking that for "gone" is what paints the skeleton over a* conversation being read; holding the last answer through it is what this is for.*- * The hold is released the moment either thing that could make it a LIE happens: the route- * moved to another Session, or the direct lookup came back and said this one is not there.- * So a deleted Session still leaves the screen — one tick later than it used to.+ * The hold is released the moment anything that could make it a LIE happens: the route+ * moved to another Session, the direct lookup came back and said this one is not there, or the+ * Project changed — a Session is only ever held under its own Project. So a deleted Session+ * still leaves the screen — one tick later than it used to.*/export function heldRouteSession(held: SessionInfo | null,listed: SessionInfo | null,routeSessionId: string | null,probeSaysGone: boolean,+ projectId: string | null,): SessionInfo | null {if (listed !== null) return listed;- if (held === null || held.sessionId !== routeSessionId) return null;+ if (held === null || held.sessionId !== routeSessionId || !ofProject(held, projectId))+ return null;return probeSaysGone ? null : held;}diff --git a/packages/web/src/features/chat/use-memory-listing.ts b/packages/web/src/features/chat/use-memory-listing.tsindex a7fa0747..36601963 100644--- a/packages/web/src/features/chat/use-memory-listing.ts+++ b/packages/web/src/features/chat/use-memory-listing.ts@@ -13,6 +13,7 @@ import * as api from "../../api/endpoints";import { apiErrorText } from "../../lib/api-error";import type { MemoryChangeRow } from "../../lib/omni/memory-changes";import type { ScopeFiles } from "./memory-nav";+import { scopeKey } from "../../lib/project-scope";export function useMemoryListing(projectId: string | null,@@ -20,6 +21,12 @@ export function useMemoryListing(wanted: boolean,changes: readonly MemoryChangeRow[],): { scopes: ScopeFiles[] | null; error: string | null } {+ /**+ * The Agent a listing is about: its id in its Project. The Project is part of it — every+ * Project has a `default_agent`, and one Project's memory shown under another's is that+ * other Agent's memory, delete marks and all.+ */+ const agentKey = scopeKey(projectId, agentId);const [state, setState] = useState<{forAgent: string | null;scopes: ScopeFiles[] | null;@@ -38,18 +45,18 @@ export function useMemoryListing(files: (await api.getMemoryFiles(projectId, agentId, info.scopeKey)).files,})),);- if (!cancelled) setState({ forAgent: agentId, scopes, error: null });+ if (!cancelled) setState({ forAgent: agentKey, scopes, error: null });} catch (err) {- if (!cancelled) setState({ forAgent: agentId, scopes: null, error: apiErrorText(err) });+ if (!cancelled) setState({ forAgent: agentKey, scopes: null, error: apiErrorText(err) });}})();return () => {cancelled = true;};- }, [wanted, projectId, agentId, changes]);+ }, [wanted, projectId, agentId, agentKey, changes]);// A listing loaded for another Agent is not this Agent's memory — report it as not loaded// rather than briefly showing (and delete-marking against) the wrong tree.- if (state.forAgent !== agentId) return { scopes: null, error: null };+ if (state.forAgent !== agentKey) return { scopes: null, error: null };return { scopes: state.scopes, error: state.error };}diff --git a/packages/web/src/features/usage/usage-page.tsx b/packages/web/src/features/usage/usage-page.tsxindex 106abf6b..959c624e 100644--- a/packages/web/src/features/usage/usage-page.tsx+++ b/packages/web/src/features/usage/usage-page.tsx@@ -25,7 +25,7 @@* of them is what keeps an entity's history from sliding onto the wrong* intervals. Each chart marks the skipped intervals on its own axis.*/-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useSearchParams } from "react-router";import type { ModelRefDto, UsageBucket, UsageResponse } from "@adelie/server/api";import { Input, PageFrame, PageHeader, Select, Skeleton, TodoNotice } from "@adelie/ui";@@ -38,6 +38,8 @@ import { dismissTodo } from "../../lib/todo-dismissals";import { refreshProjectTodos } from "../../lib/use-project-todos";import { formatMoney, humanizeTokens } from "../../lib/format";import { catalogEntryFor } from "@adelie/core/model-catalog";+import { scoped, scopedValue, type Scoped } from "../../lib/project-scope";+import { useOpenedInProject } from "../../lib/use-opened-in-project";import { useProject } from "../../state/project";import { useTheme } from "../../state/theme";import { TrendChart } from "./trend-chart";@@ -141,6 +143,16 @@ interface LoadedRange {toTs?: string;}+/** The `?agentId=` deep link as a filter of the Project the page was opened in; none without either. */+function linkedAgentFilter(+ agentId: string | null,+ projectId: string | null,+): Scoped<string> | null {+ return agentId === null || agentId === "" || projectId === null+ ? null+ : scoped(projectId, agentId);+}+export function UsagePage() {useDocumentTitle(S.usage.title);const { currency } = useTheme();@@ -157,14 +169,28 @@ export function UsagePage() {// / date filters likewise don't enter the URL — the effect never overrides a manual selection when the parameter is unchanged).const [searchParams] = useSearchParams();const paramAgentId = searchParams.get("agentId");- const [agentFilter, setAgentFilter] = useState<string>(paramAgentId ?? "");+ // The filter names an Agent of the Project it was chosen in — the deep link's belongs to the+ // Project the page was opened in — and is read only under that Project (lib/project-scope.ts):+ // after a Project switch the page is unfiltered, rather than asking the new Project about an+ // Agent of the old one.+ const openedIn = useOpenedInProject(projectId);+ const [agentFilterRead, setAgentFilterRead] = useState<Scoped<string> | null>(() =>+ linkedAgentFilter(paramAgentId, openedIn),+ );+ // The deep link is applied again when it changes, and once the Project it belongs to is known+ // — in the render that sees the change, so no read goes out with the filter it replaces.+ const [linkSeen, setLinkSeen] = useState({ paramAgentId, openedIn });+ if (linkSeen.paramAgentId !== paramAgentId || linkSeen.openedIn !== openedIn) {+ setLinkSeen({ paramAgentId, openedIn });+ setAgentFilterRead(linkedAgentFilter(paramAgentId, openedIn));+ }+ const agentFilter = scopedValue(agentFilterRead, projectId) ?? "";+ const setAgentFilter = (agentId: string) =>+ setAgentFilterRead(agentId === "" || projectId === null ? null : scoped(projectId, agentId));// Model filtering is a **paired reference** (the same model_id can coexist// under multiple providers); the dropdown's option value uses the// candidate's index rather than a concatenated string — the reference is always passed as a pair, never concatenated into an id.const [modelFilter, setModelFilter] = useState<ModelRefDto | null>(null);- useEffect(() => {- setAgentFilter(paramAgentId ?? "");- }, [paramAgentId]);// Date range: a trailing window (last hour / last 24 hours), a calendar// preset (7/30/90 days), or a custom from/to pair — plus the time-series// precision. A range change keeps the precision when the new preset still@@ -177,7 +203,9 @@ export function UsagePage() {setFrom(nextFrom);setTo(nextTo);};- const [data, setData] = useState<UsageResponse | null>(null);+ /** The dashboard's answer, tagged with the Project it was read for. */+ const [dataRead, setData] = useState<Scoped<UsageResponse> | null>(null);+ const data = scopedValue(dataRead, projectId);/*** The range the dashboard actually READ, which is not always the one the picker holds. A* trailing preset computes its window at load time and deliberately leaves `from`/`to` on@@ -193,8 +221,11 @@ export function UsagePage() {// extra) while the marks live inside the cards, lifted to this level.const [tokenBucket, setTokenBucket] = useState<TokenLegendKey | null>(null);+ /** Dashboard reads so far: only the newest one's answer is applied. */+ const asked = useRef(0);const load = useCallback(async () => {if (!projectId) return;+ const ask = ++asked.current;// The notice must acknowledge the errors fetched for this visit, not the timestamp// cached when the app started; otherwise those errors return as unread after a reload.refreshProjectTodos(projectId);@@ -214,10 +245,12 @@ export function UsagePage() {...(agentFilter ? { agentId: agentFilter } : {}),...(modelFilter ? { provider: modelFilter.provider, modelId: modelFilter.modelId } : {}),});- setData(res);+ // A late answer — for the Project just left, or for filters changed since — is dropped.+ if (ask !== asked.current) return;+ setData(scoped(projectId, res));setLoaded({ preset, ...range });} catch (e) {- setError(apiErrorText(e));+ if (ask === asked.current) setError(apiErrorText(e));}}, [projectId, preset, from, to, agentFilter, modelFilter?.provider, modelFilter?.modelId]);diff --git a/packages/web/src/lib/project-scope.ts b/packages/web/src/lib/project-scope.tsnew file mode 100644index 00000000..d59805be--- /dev/null+++ b/packages/web/src/lib/project-scope.ts@@ -0,0 +1,64 @@+/**+ * Project-scoped state, and the one rule every surface that holds it follows.+ *+ * The Web App shows one Project at a time, and the user can switch while answers are still in+ * flight — on a slow machine, while the previous Project's lists are still loading. Anything read+ * for a Project (its Agents, its Sessions, an Agent's config) is true of that Project only. So:+ *+ * - **Every Project-scoped answer carries the Project it was asked for**, and is applied only+ * while that Project is still the current one (`isCurrentProject`). A late answer for A that+ * lands after the switch to B is dropped; it must not overwrite what B already shows.+ * - **Held state is tagged with the Project it was read for** (`Scoped`), and read through+ * `scopedValue`, which hands it out only for that Project. A provider or page that resets its+ * state in an effect lags `useProject()` by one commit — the descendants' effects run first —+ * and in that commit an untagged value would pair B with A's Agents, A's rows, A's config.+ * - **A row that names its own Project** (`SessionInfo.projectId`) is used only under that+ * Project (`ofProject`).+ *+ * The tag can be finer than the Project: an Agent's config or listing is scoped to the Agent+ * within the Project (and the machine holding it), keyed with `scopeKey`.+ */++/** A value and the scope it was read for — a Project, or an Agent within one (`scopeKey`). */+export interface Scoped<T> {+ readonly scope: string;+ readonly value: T;+}++/** Tags `value` with the scope it was read for. */+export function scoped<T>(scope: string, value: T): Scoped<T> {+ return { scope, value };+}++/** `held`'s value when it was read for `scope`; null for any other scope, or none. */+export function scopedValue<T>(held: Scoped<T> | null, scope: string | null): T | null {+ return held !== null && scope !== null && held.scope === scope ? held.value : null;+}++/**+ * The scope key of a Project, or of one Agent in it — on a machine, when given (an Agent id+ * names a different Agent on each server). Null while the Project or the named Agent is unknown.+ */+export function scopeKey(+ projectId: string | null,+ agentId?: string | null,+ machineId?: string | null,+): string | null {+ if (projectId === null) return null;+ if (agentId === undefined) return projectId;+ if (agentId === null) return null;+ return JSON.stringify([projectId, agentId, machineId ?? null]);+}++/** Whether an answer asked for `askedFor` may still be applied: that Project is still current. */+export function isCurrentProject(askedFor: string | null, current: string | null): boolean {+ return askedFor !== null && askedFor === current;+}++/** Whether a row that names its own Project belongs under `projectId`. */+export function ofProject(+ row: { readonly projectId: string } | null | undefined,+ projectId: string | null,+): boolean {+ return row != null && projectId !== null && row.projectId === projectId;+}diff --git a/packages/web/src/lib/use-opened-in-project.ts b/packages/web/src/lib/use-opened-in-project.tsnew file mode 100644index 00000000..2d8029da--- /dev/null+++ b/packages/web/src/lib/use-opened-in-project.ts@@ -0,0 +1,29 @@+/**+ * Pages whose address names something of one Project — an Agent (`/agents/:agentId`), a+ * Benchmark (`/benchmark/:benchmarkId`), an Agent filter (`/usage?agentId=`) — belong to the+ * Project they were opened in (lib/project-scope.ts). Asked under another Project, the same id+ * names another thing or nothing at all.+ */+import { useEffect, useRef } from "react";+import { useNavigate } from "react-router";++/** The first Project this mounted page was shown under; null until the Project is known. */+export function useOpenedInProject(projectId: string | null): string | null {+ const openedIn = useRef<string | null>(null);+ if (openedIn.current === null) openedIn.current = projectId;+ return openedIn.current;+}++/**+ * Leaves for `to` — the new Project's list — once the current Project is no longer the one the+ * page was opened in. Returns whether it has switched away, so the page renders nothing, and+ * asks nothing, in the commit before the navigation lands.+ */+export function useLeaveOnProjectSwitch(projectId: string | null, to: string): boolean {+ const navigate = useNavigate();+ const switchedAway = projectId !== useOpenedInProject(projectId);+ useEffect(() => {+ if (switchedAway) navigate(to, { replace: true });+ }, [switchedAway, navigate, to]);+ return switchedAway;+}diff --git a/packages/web/src/state/company.tsx b/packages/web/src/state/company.tsxindex d9d1b22c..0055cbaa 100644--- a/packages/web/src/state/company.tsx+++ b/packages/web/src/state/company.tsx@@ -62,6 +62,7 @@ import { createStore } from "zustand/vanilla";import { toastAttention } from "@adelie/ui";import * as api from "../api/endpoints";import { apiErrorText } from "../lib/api-error";+import { isCurrentProject } from "../lib/project-scope";import { S } from "../lib/strings";import { markBetaNoticeShown, shouldShowBetaNotice } from "../features/company/company-beta";import { channelBadgeCounts } from "../features/company/channel-list";@@ -276,6 +277,11 @@ function settleWorkMode(state: CompanyStoreState): void {* the first render already knows whether company mode may be entered.*/export function createCompanyStore(options: { serverEnabled?: boolean } = {}) {+ /**+ * The Project the newest organization-sessions read is for. The Provider asks on every+ * Project switch, so this is the current Project; an answer for any other is dropped.+ */+ let orgSessionsFor: string | null = null;return createStore<CompanyStoreState>((set, get) => ({serverEnabled: options.serverEnabled ?? false,personalEnabled: true,@@ -493,6 +499,7 @@ export function createCompanyStore(options: { serverEnabled?: boolean } = {}) {},reloadOrgSessions: async (projectId) => {+ orgSessionsFor = projectId;const orgs = get().organizations.filter((o) => o.projectId === projectId);const entries = await Promise.all(orgs.map(async (o) => {@@ -506,6 +513,9 @@ export function createCompanyStore(options: { serverEnabled?: boolean } = {}) {}}),);+ // The map is replaced whole: an answer for the Project just left, landing after the+ // current one's, would take the current organizations' desks and tickets off screen.+ if (!isCurrentProject(projectId, orgSessionsFor)) return;const next = new Map<string, OrgSessionsResponse>();for (const entry of entries) if (entry !== null) next.set(entry[0], entry[1]);set({ orgSessions: next });diff --git a/packages/web/src/state/project.tsx b/packages/web/src/state/project.tsxindex 28f672fb..48c09e33 100644--- a/packages/web/src/state/project.tsx+++ b/packages/web/src/state/project.tsx@@ -8,6 +8,10 @@* State lives in a zustand vanilla store (one instance per Provider mount, so an unmount* still resets everything); the Provider is a thin lifecycle component that triggers the* initial fetches and republishes the store's state through the same context value as before.+ *+ * The Agent list follows lib/project-scope.ts: it is held tagged with the Project it was listed+ * for, an answer is applied only while that Project is still current (a late list of the+ * Project just left is dropped), and the context publishes only the current Project's list.*/import { createContext, useContext, useEffect, useMemo, useState } from "react";import type { ReactNode } from "react";@@ -15,6 +19,7 @@ import type { AgentSummary, ProjectSummary } from "@adelie/server/api";import { useStore } from "zustand/react";import { createStore } from "zustand/vanilla";import * as api from "../api/endpoints";+import { isCurrentProject, scoped, scopedValue, type Scoped } from "../lib/project-scope";const PROJECT_KEY = "penguin.lastProjectId";const agentKey = (projectId: string) => `penguin.lastAgentId.${projectId}`;@@ -54,13 +59,14 @@ export function agentDisplayName(a: AgentSummary): string {return a.name ?? a.agentId;}-/** Store state: the context value's raw ingredients (currentProject/currentAgent are derived in the Provider) plus the mutation functions. */+/** Store state: the context value's raw ingredients (currentProject/agents/currentAgent are derived by projectView) plus the mutation functions. */interface ProjectStoreState {projects: ProjectSummary[];projectsLoading: boolean;currentProjectId: string | null;- agents: AgentSummary[];+ /** The last Agent list applied, tagged with the Project it was listed for; null before any. */+ agents: Scoped<AgentSummary[]> | null;agentsLoading: boolean;currentAgentId: string | null;@@ -70,13 +76,23 @@ interface ProjectStoreState {reloadAgents: () => Promise<void>;}+/**+ * What moving to another Project resets, in the same update that moves it: the current Agent+ * and the Agent list are the previous Project's, and nothing may read them as the new one's.+ */+function enteredProject(projectId: string | null): Partial<ProjectStoreState> {+ return { currentProjectId: projectId, currentAgentId: null, agents: null, agentsLoading: true };+}+function createProjectStore() {+ /** Agent-list asks so far: only the newest one's answer is applied (see reloadAgents). */+ let agentsAsked = 0;return createStore<ProjectStoreState>((set, get) => ({projects: [],projectsLoading: true,currentProjectId: null,- agents: [],+ agents: null,agentsLoading: true,currentAgentId: null,@@ -86,9 +102,12 @@ function createProjectStore() {const res = await api.listProjects();const wanted = get().currentProjectId ?? localStorage.getItem(PROJECT_KEY);const found = res.projects.find((p) => p.projectId === wanted);+ const next = (found ?? res.projects[0])?.projectId ?? null;+ // The current Project gone from the list (deleted, access lost) moves the app to another+ // one: a switch like any other, so it resets what a switch resets, in the same update.set({projects: res.projects,- currentProjectId: (found ?? res.projects[0])?.projectId ?? null,+ ...(next === get().currentProjectId ? {} : enteredProject(next)),});} finally {set({ projectsLoading: false });@@ -106,26 +125,33 @@ function createProjectStore() {// Clear the Agent list in sync: avoids a transient render with "new projectId + old// Project's agents" that would make downstream consumers (Sessions) fetch with the// wrong Agent set (which could create spurious Sessions under the new Project).- set({- currentProjectId: projectId,- currentAgentId: null,- agents: [],- agentsLoading: true,- });+ set(enteredProject(projectId));// Sync server-side prefs (best-effort; failure doesn't affect the local experience).void api.putPrefs({ lastProjectId: projectId }).catch(() => undefined);},reloadAgents: async () => {- const currentProjectId = get().currentProjectId;- if (!currentProjectId) return;+ const projectId = get().currentProjectId;+ if (!projectId) return;+ const ask = ++agentsAsked;+ // The answer is applied only while it is the newest ask and its Project is still the+ // current one. A list of the Project just left that answers after the switch — slow+ // network, slow machine, a reload fired by the turn that just ended there — would+ // otherwise land as the new Project's Agents, and every page would then pair the new+ // Project with Agents it does not have.+ const applies = () =>+ ask === agentsAsked && isCurrentProject(projectId, get().currentProjectId);set({ agentsLoading: true });try {- const res = await api.listAgents(currentProjectId);- const wanted = get().currentAgentId ?? localStorage.getItem(agentKey(currentProjectId));- set({ agents: res.agents, currentAgentId: agentOf(res.agents, wanted)?.agentId ?? null });+ const res = await api.listAgents(projectId);+ if (!applies()) return;+ const wanted = get().currentAgentId ?? localStorage.getItem(agentKey(projectId));+ set({+ agents: scoped(projectId, res.agents),+ currentAgentId: agentOf(res.agents, wanted)?.agentId ?? null,+ });} finally {- set({ agentsLoading: false });+ if (applies()) set({ agentsLoading: false });}},@@ -156,6 +182,26 @@ export function agentOf();}+/** Published while no Agent list of the current Project has been applied: one identity, so effects keyed on it stay put. */+const NO_AGENTS: AgentSummary[] = [];++/**+ * What the context publishes from the store: the current Project, its Agents and the current+ * Agent. The Agent list is handed out only when it was listed for the current Project — never+ * another Project's, whichever write left it there — and the current Agent is one of it.+ */+function projectView(+ state: Pick<ProjectStoreState, "projects" | "currentProjectId" | "agents" | "currentAgentId">,+): {+ currentProject: ProjectSummary | null;+ agents: AgentSummary[];+ currentAgent: AgentSummary | null;+} {+ const currentProject = state.projects.find((p) => p.projectId === state.currentProjectId) ?? null;+ const agents = scopedValue(state.agents, state.currentProjectId) ?? NO_AGENTS;+ return { currentProject, agents, currentAgent: agentOf(agents, state.currentAgentId) };+}+export function ProjectProvider({ children }: { children: ReactNode }) {const [store] = useState(createProjectStore);const state = useStore(store);@@ -166,21 +212,18 @@ export function ProjectProvider({ children }: { children: ReactNode }) {const { currentProjectId } = state;useEffect(() => {- store.setState({ agents: [] });void store.getState().reloadAgents();}, [store, currentProjectId]);const value = useMemo<ProjectContextValue>(() => {- const currentProject =- state.projects.find((p) => p.projectId === state.currentProjectId) ?? null;- const currentAgent = agentOf(state.agents, state.currentAgentId);+ const { currentProject, agents, currentAgent } = projectView(state);return {projects: state.projects,projectsLoading: state.projectsLoading,currentProject,setCurrentProjectId: state.setCurrentProjectId,reloadProjects: state.reloadProjects,- agents: state.agents,+ agents,agentsLoading: state.agentsLoading,currentAgent,setCurrentAgentId: state.setCurrentAgentId,diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsxindex a054bd2d..0903c2f4 100644--- a/packages/web/src/state/sessions.tsx+++ b/packages/web/src/state/sessions.tsx@@ -102,6 +102,13 @@ import {} from "../lib/session-grouping";import type { ActivityKey, StreamPosition } from "../lib/session-grouping";import { noteScheduleEvent } from "../features/schedules/schedule-store";+import {+ isCurrentProject,+ ofProject,+ scoped,+ scopedValue,+ type Scoped,+} from "../lib/project-scope";import { useProject } from "./project";interface SessionsContextValue {@@ -576,6 +583,10 @@ export function createSessionsStore() {* it — a possible one-off drift self-heals on the next reload.*/const insert = (session: SessionInfo) => {+ // Only this Project's rows: a row handed in for a conversation of the Project just left+ // (a lookup that settled after the switch, a notification clicked later) is not this+ // list's, and held here it would put that Project's Agent under this one.+ if (!ofProject(session, get().projectId)) return;const existed = get().sessions.some((s) => s.sessionId === session.sessionId);// Per SOURCE and stream: the row belongs to the machine it lives on, and the whole// stream (scope "") is the one the totals were fetched against.@@ -710,7 +721,10 @@ export function createSessionsStore() {}),)).flat();- if (g !== gen) return;+ // Superseded, or asked for a Project the list has since left: the Provider's context+ // sync moves `projectId` before the next Agent set exists, and no reload runs to+ // supersede this one until it does — so the Project is compared, not only `gen`.+ if (g !== gen || !isCurrentProject(projectId, get().projectId)) return;// Agents this server did not answer about. Per Agent, not per server: a damaged// index or a 500 on ONE Agent is a different event from this server being// unreadable, and reading the first as the second is what leaves the page on a@@ -1021,7 +1035,8 @@ export function createSessionsStore() {}),)).flat();- if (g !== gen) return; // Project switch / reload raced this page: drop it.+ // Project switch / reload raced this page: drop it.+ if (g !== gen || !isCurrentProject(projectId, get().projectId)) return;const ok = results.filter((r) => r !== null);const prev = get().sessions;const seen = new Set(prev.map((s) => s.sessionId));@@ -1423,6 +1438,39 @@ export function applyUserEvent(*/export const OFFLINE_RECHECK_MS = 30_000;+/** The list's rows, pages and totals — everything in the store that is read for one Project. */+type ListedState = Pick<+ SessionsStoreState,+ | "sessions"+ | "pageState"+ | "countsByAgent"+ | "workspaceCountsByAgent"+ | "workspaceLatestByAgent"+ | "loading"+>;++/** What the list holds for a Project it has not been read for yet: nothing, and still loading. */+const NOTHING_LISTED: ListedState = {+ sessions: [],+ pageState: new Map(),+ countsByAgent: new Map(),+ workspaceCountsByAgent: new Map(),+ workspaceLatestByAgent: new Map(),+ loading: true,+};++/**+ * The store's list as `projectId` may read it: the store's own when it holds that Project's,+ * else nothing and loading. The Provider publishes through this, so no consumer ever reads one+ * Project's rows — or the Agents they name — under another (see SessionsProvider).+ */+function sessionsListFor(+ state: ListedState & Pick<SessionsStoreState, "projectId">,+ projectId: string | null,+): ListedState {+ return isCurrentProject(projectId, state.projectId) ? state : NOTHING_LISTED;+}+export function SessionsProvider({ children }: { children: ReactNode }) {const { currentProject, agents } = useProject();const projectId = currentProject?.projectId ?? null;@@ -1457,14 +1505,14 @@ export function SessionsProvider({ children }: { children: ReactNode }) {* What the list is FOR: a Session started on a machine's own Agent is listed by nobody* unless that machine is asked about that Agent (see `agentIdsByMachine` in the store).*/- const [machineAgentIdsJson, setMachineAgentIdsJson] = useState("{}");+ const [machineAgents, setMachineAgents] = useState<Scoped<string> | null>(null);const [machinesEpoch, setMachinesEpoch] = useState(0);useEffect(() => {if (projectId === null) {setMachineIdsKey("");setOfflineMachineIdsKey("");setMachineLabelsJson("[]");- setMachineAgentIdsJson("{}");+ setMachineAgents(null);return;}let cancelled = false;@@ -1514,8 +1562,11 @@ export function SessionsProvider({ children }: { children: ReactNode }) {}),);if (cancelled) return;- setMachineAgentIdsJson(- JSON.stringify(Object.fromEntries(answers.filter((entry) => entry !== null))),+ setMachineAgents(+ scoped(+ projectId,+ JSON.stringify(Object.fromEntries(answers.filter((entry) => entry !== null))),+ ),);} catch {// No machine list (not an admin, or the call failed): the list is this server's alone.@@ -1531,6 +1582,9 @@ export function SessionsProvider({ children }: { children: ReactNode }) {if (timer !== null) clearTimeout(timer);};}, [projectId, machinesEpoch]);+ // The machines' Agents of THIS Project only: until the answer for it is in, none — the+ // previous Project's would ask its machines about Agents this Project does not have.+ const machineAgentIdsJson = scopedValue(machineAgents, projectId) ?? "{}";/*** The Project and its Agent set: what the list is OF. A change here invalidates every row@@ -1614,7 +1668,13 @@ export function SessionsProvider({ children }: { children: ReactNode }) {return () => conn.close();}, [store]);- const { pageState, countsByAgent, machineIds } = state;+ // The store is told about a Project switch in the effect above, one commit after useProject()+ // reports it — and in that commit every descendant's effects run before this Provider's. So+ // the list is published only for the Project it was read for: under any other it is empty and+ // loading, never the previous Project's rows (their Agents paired with the new Project).+ const listed = sessionsListFor(state, projectId);+ const { pageState, countsByAgent } = listed;+ const { machineIds } = state;// One more stream per connected machine: a Session there changes state on that machine's// server, and this server never hears of it. Keyed on the held set, so a machine that@@ -1699,7 +1759,7 @@ export function SessionsProvider({ children }: { children: ReactNode }) {// pure waste.const byAgent = useMemo(() => {const map = new Map<string, SessionInfo[]>();- for (const s of state.sessions) {+ for (const s of listed.sessions) {const list = map.get(s.agentId);if (list) list.push(s);else map.set(s.agentId, [s]);@@ -1708,7 +1768,7 @@ export function SessionsProvider({ children }: { children: ReactNode }) {// place): sort each Agent's list in activity order, the key the server pages by.for (const list of map.values()) list.sort(mostRecentFirst);return map;- }, [state.sessions]);+ }, [listed.sessions]);const machineLabels = useMemo<ReadonlyMap<string, string>>(() => {const entries = JSON.parse(machineLabelsJson) as [string | null, string][];@@ -1719,18 +1779,18 @@ export function SessionsProvider({ children }: { children: ReactNode }) {const value = useMemo<SessionsContextValue>(() => {return {- sessions: state.sessions,+ sessions: listed.sessions,byAgent,- countsByAgent: state.countsByAgent,- workspaceCountsByAgent: state.workspaceCountsByAgent,- workspaceLatestByAgent: state.workspaceLatestByAgent,+ countsByAgent: listed.countsByAgent,+ workspaceCountsByAgent: listed.workspaceCountsByAgent,+ workspaceLatestByAgent: listed.workspaceLatestByAgent,liveStatuses: state.liveStatuses,machineLabels,machineIds: state.machineIds,isLoadedFor,hasMoreFor,activityWatermarkFor,- loading: state.loading,+ loading: listed.loading,machinesUnreachable: state.offlineMachineIds.length > 0,offlineMachineIds: state.offlineMachineIds,reload: state.reload,@@ -1742,7 +1802,16 @@ export function SessionsProvider({ children }: { children: ReactNode }) {setStatus: state.setStatus,setTitle: state.setTitle,};- }, [state, byAgent, machineLabels, isLoadedFor, hasMoreFor, activityWatermarkFor, isDeleted]);+ }, [+ state,+ listed,+ byAgent,+ machineLabels,+ isLoadedFor,+ hasMoreFor,+ activityWatermarkFor,+ isDeleted,+ ]);return <SessionsContext.Provider value={value}>{children}</SessionsContext.Provider>;}diff --git a/packages/web/test/project-scope.test.ts b/packages/web/test/project-scope.test.tsnew file mode 100644index 00000000..a4d7f326--- /dev/null+++ b/packages/web/test/project-scope.test.ts@@ -0,0 +1,83 @@+/**+ * lib/project-scope.ts unit tests: the one rule every surface holding Project-scoped state+ * follows (a tag on what was read, a check before an answer is applied).+ *+ * - A held value is handed out only for the scope it was read for; any other scope reads null.+ * - A Project's scope key is the Project; an Agent's adds the Agent (and the machine, when one+ * is named), so the same Agent id in two Projects — or on two servers — is two scopes.+ * - An answer asked for a Project other than the current one is never applied, nor one asked+ * for no Project at all.+ * - A row that names its own Project belongs only under that Project.+ */+import { describe, expect, it } from "vitest";+import {+ isCurrentProject,+ ofProject,+ scopeKey,+ scoped,+ scopedValue,+} from "../src/lib/project-scope";++describe("scoped / scopedValue", () => {+ it("hands the value out for the scope it was read for", () => {+ expect(scopedValue(scoped("p1", ["alpha"]), "p1")).toEqual(["alpha"]);+ });++ it("hands out nothing for another scope, or before anything was read", () => {+ expect(scopedValue(scoped("p1", ["alpha"]), "p2")).toBeNull();+ expect(scopedValue(scoped("p1", ["alpha"]), null)).toBeNull();+ expect(scopedValue(null, "p1")).toBeNull();+ });++ it("keeps a value that is itself falsy", () => {+ expect(scopedValue(scoped("p1", 0), "p1")).toBe(0);+ expect(scopedValue(scoped("p1", ""), "p1")).toBe("");+ });+});++describe("scopeKey", () => {+ it("is the Project alone when no Agent is named", () => {+ expect(scopeKey("p1")).toBe("p1");+ expect(scopeKey("p1", undefined)).toBe("p1");+ });++ it("names the Agent within the Project", () => {+ expect(scopeKey("p1", "default_agent")).toBe(scopeKey("p1", "default_agent"));+ expect(scopeKey("p1", "default_agent")).not.toBe(scopeKey("p2", "default_agent"));+ expect(scopeKey("p1", "default_agent")).not.toBe(scopeKey("p1", "alpha"));+ });++ it("separates the same Agent id on two servers", () => {+ expect(scopeKey("p1", "default_agent", "gpu-box")).not.toBe(+ scopeKey("p1", "default_agent", "lab-box"),+ );+ expect(scopeKey("p1", "default_agent", "gpu-box")).not.toBe(scopeKey("p1", "default_agent"));+ });++ it("has no key without a Project, or with an Agent explicitly unset", () => {+ expect(scopeKey(null, "default_agent")).toBeNull();+ expect(scopeKey("p1", null)).toBeNull();+ });+});++describe("isCurrentProject", () => {+ it("applies an answer only for the Project still current", () => {+ expect(isCurrentProject("p1", "p1")).toBe(true);+ expect(isCurrentProject("p1", "p2")).toBe(false);+ expect(isCurrentProject("p1", null)).toBe(false);+ expect(isCurrentProject(null, null)).toBe(false);+ });+});++describe("ofProject", () => {+ it("keeps a row under its own Project only", () => {+ expect(ofProject({ projectId: "p1" }, "p1")).toBe(true);+ expect(ofProject({ projectId: "p1" }, "p2")).toBe(false);+ expect(ofProject({ projectId: "p1" }, null)).toBe(false);+ });++ it("has nothing to place for a missing row", () => {+ expect(ofProject(null, "p1")).toBe(false);+ expect(ofProject(undefined, "p1")).toBe(false);+ });+});diff --git a/packages/web/test/route-session-hold.test.ts b/packages/web/test/route-session-hold.test.tsindex c1b2ed79..45814585 100644--- a/packages/web/test/route-session-hold.test.ts+++ b/packages/web/test/route-session-hold.test.ts@@ -2,34 +2,38 @@* The chat page keeps showing the routed Session through a refetch that momentarily stops* listing it (features/chat/session-project.ts, heldRouteSession). The list is rebuilt* wholesale by every reload, so "not in the list" is two facts wearing one face — gone, or- * one tick old — and only the direct lookup failing, or the route moving on, may release the- * hold.+ * one tick old — and only the direct lookup failing, the route moving on, or the Project+ * changing may release the hold.*/import { describe, expect, it } from "vitest";import type { SessionInfo } from "@adelie/server/api";import { heldRouteSession } from "../src/features/chat/session-project";-const row = (sessionId: string) => ({ sessionId }) as SessionInfo;+const row = (sessionId: string) => ({ sessionId, projectId: "p1" }) as SessionInfo;describe("heldRouteSession", () => {it("the listed row always wins", () => {- expect(heldRouteSession(row("old"), row("s1"), "s1", false)).toEqual(row("s1"));+ expect(heldRouteSession(row("old"), row("s1"), "s1", false, "p1")).toEqual(row("s1"));});it("holds the previous answer while the list momentarily does not name the route", () => {- expect(heldRouteSession(row("s1"), null, "s1", false)).toEqual(row("s1"));+ expect(heldRouteSession(row("s1"), null, "s1", false, "p1")).toEqual(row("s1"));});it("lets go when the route moved to another Session", () => {- expect(heldRouteSession(row("s1"), null, "s2", false)).toBeNull();- expect(heldRouteSession(row("s1"), null, null, false)).toBeNull();+ expect(heldRouteSession(row("s1"), null, "s2", false, "p1")).toBeNull();+ expect(heldRouteSession(row("s1"), null, null, false, "p1")).toBeNull();});it("lets go when the direct lookup says the Session is gone", () => {- expect(heldRouteSession(row("s1"), null, "s1", true)).toBeNull();+ expect(heldRouteSession(row("s1"), null, "s1", true, "p1")).toBeNull();+ });++ it("lets go when the Project changed: a Session is never held under another Project", () => {+ expect(heldRouteSession(row("s1"), null, "s1", false, "p2")).toBeNull();});it("has nothing to hold on a first render", () => {- expect(heldRouteSession(null, null, "s1", false)).toBeNull();+ expect(heldRouteSession(null, null, "s1", false, "p1")).toBeNull();});});diff --git a/packages/web/test/session-project.test.ts b/packages/web/test/session-project.test.tsindex 06b358f1..2cd2cfd7 100644--- a/packages/web/test/session-project.test.ts+++ b/packages/web/test/session-project.test.ts@@ -2,6 +2,9 @@* session-project.ts unit tests: the Project isolation of a deep-linked Session, the probe* key that scopes a failed lookup to its Project, and how the chat page settles which Session* the route names when the loaded list does not hold it.+ *+ * - a Session of another Project is never the routed one, listed or looked up, so a Project+ * switch never shows the previous Project's conversation.*/import { describe, expect, it } from "vitest";import type { SessionInfo } from "@adelie/server/api";@@ -49,23 +52,30 @@ describe("resolveRoutedSession", () => {const other: SessionInfo = { ...SESSION, sessionId: "session-b" };it("takes the list's row when it holds one", () => {- expect(resolveRoutedSession("session-a", [other, SESSION], null)).toBe(SESSION);+ expect(resolveRoutedSession("session-a", [other, SESSION], null, "project-a")).toBe(SESSION);});it("prefers the list's row over the fetched one — the list is the row events keep current", () => {const stale: SessionInfo = { ...SESSION, status: "running" };- expect(resolveRoutedSession("session-a", [SESSION], stale)).toBe(SESSION);+ expect(resolveRoutedSession("session-a", [SESSION], stale, "project-a")).toBe(SESSION);});it("falls back to the fetched row, which is what survives a list reload dropping it", () => {// An organization's desk opened from the org chart: never in the development list, and// dropped from the store again by the next reload.- expect(resolveRoutedSession("session-a", [], SESSION)).toBe(SESSION);- expect(resolveRoutedSession("session-a", [other], SESSION)).toBe(SESSION);+ expect(resolveRoutedSession("session-a", [], SESSION, "project-a")).toBe(SESSION);+ expect(resolveRoutedSession("session-a", [other], SESSION, "project-a")).toBe(SESSION);});it("ignores a fetched row for another id, and answers nothing without a route", () => {- expect(resolveRoutedSession("session-a", [], other)).toBeNull();- expect(resolveRoutedSession(null, [SESSION], SESSION)).toBeNull();+ expect(resolveRoutedSession("session-a", [], other, "project-a")).toBeNull();+ expect(resolveRoutedSession(null, [SESSION], SESSION, "project-a")).toBeNull();+ });++ it("after a switch to another Project, neither the looked-up row nor a listed one is the routed Session", () => {+ // The route and the lookup's copy outlive the switch; shown under project-b they would+ // render that Project with project-a's conversation and Agent.+ expect(resolveRoutedSession("session-a", [], SESSION, "project-b")).toBeNull();+ expect(resolveRoutedSession("session-a", [SESSION], SESSION, "project-b")).toBeNull();});});