Compare commits

..

2 Commits

33 changed files with 96 additions and 444 deletions
+3 -3
View File
@@ -1,4 +1,4 @@
# Next 服务端访问 Foundry 的源站;本地代理从这里发起后端 HTTP 请求,不是浏览器页面地址。 # Next 服务端访问 Bedrock 的源站;本地代理从这里发起后端 HTTP 请求,不是浏览器页面地址。
FOUNDRY_API_ORIGIN=https://api.foundry.entroia.com BEDROCK_API_ORIGIN=https://api.foundry.entroia.com
# 公开的项目路由标识,可进入浏览器构建;不是密码、会话令牌或授权凭证。 # 公开的项目路由标识,可进入浏览器构建;不是密码、会话令牌或授权凭证。
NEXT_PUBLIC_FOUNDRY_PROJECT=endoleap NEXT_PUBLIC_BEDROCK_PROJECT=endoleap
+2 -2
View File
@@ -11,5 +11,5 @@ node_modules/
*.tsbuildinfo *.tsbuildinfo
# macOS Finder 的目录元数据。 # macOS Finder 的目录元数据。
.DS_Store .DS_Store
# 本地研究与历史草案保留在 research-docs;docs 为纳入版本管理的开发教程。 # 仓库根 docs 是本地研究/草案目录,当前约定不跟踪其中内容。
/research-docs/ /docs/
+13 -14
View File
@@ -1,7 +1,5 @@
# 啡跃 Endoleap # 啡跃 Endoleap
开发者入门:[从一次画布操作理解项目](docs/README.md)。教程从页面打开、编辑和渲染讲到同步、恢复及功能扩展,无需先读历史设计草案。
本地 Next.js App Router + TypeScript + Tailwind CSS + shadcn/ui 项目。首页采用留白、黑色主按钮、衬线标题与线稿画布预览;账户页保留原有布局。工作台使用合并后的单侧栏。 本地 Next.js App Router + TypeScript + Tailwind CSS + shadcn/ui 项目。首页采用留白、黑色主按钮、衬线标题与线稿画布预览;账户页保留原有布局。工作台使用合并后的单侧栏。
项目目录:`/Users/zzyang/endoleap`。 项目目录:`/Users/zzyang/endoleap`。
@@ -31,18 +29,19 @@ npm run dev
- `src/app/dashboard/dashboard.tsx`:侧栏收起/展开、页面搜索、新建图谱与底部账户弹出框。 - `src/app/dashboard/dashboard.tsx`:侧栏收起/展开、页面搜索、新建图谱与底部账户弹出框。
- `src/app/dashboard/[workspace]/[board]/page.tsx`:按 workspace 和图谱 ID 打开页面,重新读取后端资料。 - `src/app/dashboard/[workspace]/[board]/page.tsx`:按 workspace 和图谱 ID 打开页面,重新读取后端资料。
- `src/components/ui/icon-button.tsx`:Lucide 图标按钮,图标为 16×16px,上下 4px、左右 6px 内边距,总尺寸为 28×24px。 - `src/components/ui/icon-button.tsx`:Lucide 图标按钮,图标为 16×16px,上下 4px、左右 6px 内边距,总尺寸为 28×24px。
- `src/app/api/**/route.ts`:Foundry 代理与 OAuth 跳转,使用 App Router Route Handlers。 - `src/app/api/**/route.ts`:Bedrock 代理与 OAuth 跳转,使用 App Router Route Handlers。
## 配置 ## 配置
复制 .env.example 为 .env.local,按实际部署填写: 复制 .env.example 为 .env.local,按实际部署填写:
- FOUNDRY_API_ORIGIN:仅供 Next 服务端请求后端,默认 https://api.foundry.entroia.com。 - `BEDROCK_API_ORIGIN`:仅供 Next 服务端请求后端,默认 https://api.foundry.entroia.com。
- NEXT_PUBLIC_FOUNDRY_PROJECT:项目标识,默认 endoleap。 - `NEXT_PUBLIC_BEDROCK_PROJECT`:项目标识,默认 endoleap。
- 同源代理使用 `/api/bedrock/…`。部署时同步更新环境变量。
Slack Client Secret、Signing Secret、Verification Token、用户令牌与 app token 均不需要放入此前端。浏览器调用同源 Next API,由服务端转发到 Foundry。Foundry 会话保存在 HttpOnly / SameSite=Lax Cookie,生产 HTTPS 反向代理需传 X-Forwarded-Proto=https。不要将原始会话写入客户端存储。 Slack Client Secret、Signing Secret、Verification Token、用户令牌与 app token 均不需要放入此前端。浏览器调用同源 Next API,由服务端转发到 Bedrock。Bedrock 会话保存在 HttpOnly / SameSite=Lax Cookie,生产 HTTPS 反向代理需传 X-Forwarded-Proto=https。不要将原始会话写入客户端存储。
Google / Slack 的提供方回调仍是 Foundry 后端地址;后端的项目回调映射必须指向本前端 /auth/callback。协议、主机名、端口必须与启动第三方登录时一致,否则 sessionStorage 中的 verifier 无法恢复。正式账号授权、邮件验证与 OAuth 全流程尚未完成真人验收;HTTP 302 跳转成功不能代表登录成功。 Google / Slack 的提供方回调仍是 Bedrock 后端地址;后端的项目回调映射必须指向本前端 /auth/callback。协议、主机名、端口必须与启动第三方登录时一致,否则 sessionStorage 中的 verifier 无法恢复。正式账号授权、邮件验证与 OAuth 全流程尚未完成真人验收;HTTP 302 跳转成功不能代表登录成功。
## 当前功能与范围 ## 当前功能与范围
@@ -50,9 +49,9 @@ Google / Slack 的提供方回调仍是 Foundry 后端地址;后端的项目
- 邮箱注册 / 登录 / 邮件验证兑换,Google 和 Slack 的 PKCE 登录入口及回调处理。 - 邮箱注册 / 登录 / 邮件验证兑换,Google 和 Slack 的 PKCE 登录入口及回调处理。
- 真实用户资料、空间列表与创建、画布列表与创建。资料和空间并行读取;首次创建画布时自动建立个人空间。 - 真实用户资料、空间列表与创建、画布列表与创建。资料和空间并行读取;首次创建画布时自动建立个人空间。
- 单侧栏第一行提供完全收起/恢复与新建页面,第二行为当前空间页面列表搜索。画布列表包含可展开的父子画布目录,搜索保留祖先路径,直接打开子图时自动展开所在目录。侧栏使用 Motion for React 14.9.1 实现 240ms 开关动画,尊重系统减少动态效果偏好,收起后保留左上角快捷浮框。 - 单侧栏第一行提供完全收起/恢复与新建页面,第二行为当前空间页面列表搜索。画布列表包含可展开的父子画布目录,搜索保留祖先路径,直接打开子图时自动展开所在目录。侧栏使用 Motion for React 14.9.1 实现 240ms 开关动画,尊重系统减少动态效果偏好,收起后保留左上角快捷浮框。
- 账户菜单分为工作空间概览、账户设置、用户资料与空间切换、新建工作空间、退出登录;账户设置和新建空间均接入 Foundry。菜单文字和行距参考 Notion 收紧,工作空间分组标题保留浅灰色。 - 账户菜单分为工作空间概览、账户设置、用户资料与空间切换、新建工作空间、退出登录;账户设置和新建空间均接入 Bedrock。菜单文字和行距参考 Notion 收紧,工作空间分组标题保留浅灰色。
- 底部按钮、账户菜单和设置面板使用 Foundry `profile.avatar_url` 提供的 Google 头像;无头像或图片加载失败时显示姓名首字。 - 底部按钮、账户菜单和设置面板使用 Bedrock `profile.avatar_url` 提供的 Google 头像;无头像或图片加载失败时显示姓名首字。
- 新建页面使用 Foundry Core 的 `POST /workspaces/{workspace}/materials`,提交 `kind: board`、默认名称“未命名图谱”和内容版本;由后端生成 ID。没有空间时先创建“个人空间”,成功后跳转到图谱的独立地址。 - 新建页面使用 Bedrock 的 `POST /workspaces/{workspace}/materials`,提交 `kind: board`、默认名称“未命名图谱”和内容版本;由后端生成 ID。没有空间时先创建“个人空间”,成功后跳转到图谱的独立地址。
- 本地演示提供示例图谱、搜索、新建和浏览器保存,支持图谱独立地址与刷新。 - 本地演示提供示例图谱、搜索、新建和浏览器保存,支持图谱独立地址与刷新。
- 图谱页面使用 React Flow 12.12.1,支持空白处平移、节点拖动、连线、多选、缩放和文本编辑。文字、脚本、图片节点和创作模板可从底部悬浮工具栏插入。 - 图谱页面使用 React Flow 12.12.1,支持空白处平移、节点拖动、连线、多选、缩放和文本编辑。文字、脚本、图片节点和创作模板可从底部悬浮工具栏插入。
- 右上角悬浮框提供撤销、重做、缩放、恢复 100%、适应画布和 JSON 导出;底部支持 JSON 导入及操作帮助。 - 右上角悬浮框提供撤销、重做、缩放、恢复 100%、适应画布和 JSON 导出;底部支持 JSON 导入及操作帮助。
@@ -118,7 +117,7 @@ CANVAS_UI_TOOLS=/path/to/isolated-tools node tests/canvas-ui-check.mjs
DOM 工具仅需在临时目录安装 esbuild/jsdom,见测试文件开头;不启动浏览器。生产构建与 `tests/api-smoke.mjs` 使用隔离副本和临时本地服务,避免影响现有开发服务器。实际结果及限制见 VALIDATION.md。 DOM 工具仅需在临时目录安装 esbuild/jsdom,见测试文件开头;不启动浏览器。生产构建与 `tests/api-smoke.mjs` 使用隔离副本和临时本地服务,避免影响现有开发服务器。实际结果及限制见 VALIDATION.md。
Headless Canvas API 的完整方案保留在本地忽略的 `research-docs/HEADLESS_CANVAS_API_DRAFT.md`。当前工作分支已接入纯 core/runtime、ledger/queue、IndexedDB 恢复、渐进导入/深复制、canonical Foundry 协议和私有 ESM 包预览;使用方式见 `headless/README.md`,尚未发布 npm registry,也不代表完整产品验收或后端部署完成。 Headless Canvas API 的完整方案保留在本地忽略的 `docs/HEADLESS_CANVAS_API_DRAFT.md`。当前工作分支已接入纯 core/runtime、ledger/queue、IndexedDB 恢复、渐进导入/深复制、canonical Foundry 协议和私有 ESM 包预览;使用方式见 `headless/README.md`,尚未发布 npm registry,也不代表完整产品验收或后端部署完成。
Workspace AssetDepot 支持重新授权后的跨项目采用、持久绑定与共享字节。浏览器数据库 v4 将已确认上传的项目文件转换为共享字节指针,保留原 File MIME 和逻辑读取接口;绑定使用恢复格式13。共享回收要求所有项目的持久引用清单完整且与 Root 同步;关闭项目仍受保护。源文件转换、字节、引用清单和 Root 在同一个事务中保存,未确认上传继续保留原 Blob。 Workspace AssetDepot 支持重新授权后的跨项目采用、持久绑定与共享字节。浏览器数据库 v4 将已确认上传的项目文件转换为共享字节指针,保留原 File MIME 和逻辑读取接口;绑定使用恢复格式13。共享回收要求所有项目的持久引用清单完整且与 Root 同步;关闭项目仍受保护。源文件转换、字节、引用清单和 Root 在同一个事务中保存,未确认上传继续保留原 Blob。
@@ -126,12 +125,12 @@ Workspace AssetDepot 支持重新授权后的跨项目采用、持久绑定与
## 会话期限 ## 会话期限
会话为可撤销的随机令牌。30 天闲置续期、90 天绝对期限由 Core 控制,代理按剩余期限更新 HttpOnly Cookie;既有过期会话不恢复。详细本地说明为 `research-docs/SESSION_LIFETIME.md`。 会话为可撤销的随机令牌。30 天闲置续期、90 天绝对期限由 Core 控制,代理按剩余期限更新 HttpOnly Cookie;既有过期会话不恢复。详细本地说明为 `docs/SESSION_LIFETIME.md`。
## 图片附件与加载 ## 图片附件与加载
真实画布新上传的图片存入 Foundry 附件 API,快照只保存原始附件引用,避免 Base64 随每次打开和保存传输。原图保留;画布按需读取单一最长边 1024px 的预览,放大后可读取原图。预览权限与原图一致,Core 的配套预览功能已随 PR #15 合并并部署(b2ae48e);小图或 GIF 可能直接返回原始文件。 真实画布新上传的图片存入 Bedrock 附件 API,快照只保存原始附件引用,避免 Base64 随每次打开和保存传输。原图保留;画布按需读取单一最长边 1024px 的预览,放大后可读取原图。预览权限与原图一致,Core 的配套预览功能已随 PR #15 合并并部署(b2ae48e);小图或 GIF 可能直接返回原始文件。
指定测试画布已完成一次性旧图迁移,原图、节点与连线的哈希核对一致;临时迁移入口及执行逻辑已移除。打开页面不会自动迁移或 PATCH。只改变视角保存在本机;真实内容修改才自动保存到服务器。 指定测试画布已完成一次性旧图迁移,原图、节点与连线的哈希核对一致;临时迁移入口及执行逻辑已移除。打开页面不会自动迁移或 PATCH。只改变视角保存在本机;真实内容修改才自动保存到服务器。
@@ -213,4 +212,4 @@ Core `subgraphs.member_positions` 能力启用时,最终落点(源画布局
`tests/headless/fixtures/foundry-model-operation-v2.json` 是服务适配器单测的完整请求样例。协议 2 的 `request_id` 标识冻结请求,`expected_versions` 是参与 canvas 的已确认版本,`operations[].id` 是逻辑操作 ID。样例把第一代元素 `a` 的 `data.title` 从 `a` 改为 `renamed`;`beforePresent`/`afterPresent` 区分字段缺失与有值。字段旁注与断言在 `tests/headless/service.test.mjs`,静态样例不代表真实服务已执行。 `tests/headless/fixtures/foundry-model-operation-v2.json` 是服务适配器单测的完整请求样例。协议 2 的 `request_id` 标识冻结请求,`expected_versions` 是参与 canvas 的已确认版本,`operations[].id` 是逻辑操作 ID。样例把第一代元素 `a` 的 `data.title` 从 `a` 改为 `renamed`;`beforePresent`/`afterPresent` 区分字段缺失与有值。字段旁注与断言在 `tests/headless/service.test.mjs`,静态样例不代表真实服务已执行。
`.gitignore` 排除依赖、Next/headless 产物、环境变量、增量缓存和系统文件;仅放行 `.env.example` 作为模板。根 `/research-docs/` 作为本地研究目录忽略;`docs/` 保存纳入版本管理的开发教程。忽略规则只影响未跟踪文件,不会把已经跟踪的文件自动移出 Git。`.env.example` 的公开项目标识与服务端源站说明写在模板内;实际凭据不应写进示例或公开构建变量。 `.gitignore` 排除依赖、Next/headless 产物、环境变量、增量缓存和系统文件;仅放行 `.env.example` 作为模板。根 `/docs/` 当前作为本地研究目录忽略。忽略规则只影响未跟踪文件,不会把已经跟踪的文件自动移出 Git。`.env.example` 的公开项目标识与服务端源站说明写在模板内;实际凭据不应写进示例或公开构建变量。
+2 -2
View File
@@ -23,7 +23,7 @@
- 按用户约定未访问项目浏览器,未进行视觉布局、真实拖动手感与真实登录会话的浏览器验收。 - 按用户约定未访问项目浏览器,未进行视觉布局、真实拖动手感与真实登录会话的浏览器验收。
- 子图关系备份不能作为普通单图快照导入其他画布;导出包含完整 owner 文档集合,避免仅备份父图或重复保存投影。 - 子图关系备份不能作为普通单图快照导入其他画布;导出包含完整 owner 文档集合,避免仅备份父图或重复保存投影。
- 网络未知结果保留请求并暂停编辑;普通版本冲突保留本地草稿,不强推覆盖。 - 网络未知结果保留请求并暂停编辑;普通版本冲突保留本地草稿,不强推覆盖。
- Headless 库尚未创建,提取方案已改写在本地忽略的 research-docs/HEADLESS_CANVAS_API_DRAFT.md;已替代的分区/元素/后端需求文档已清理。会话策略文档仍保留。 - Headless 库尚未创建,提取方案已改写在本地忽略的 docs/HEADLESS_CANVAS_API_DRAFT.md;已替代的分区/元素/后端需求文档已清理。会话策略文档仍保留。
- 原有 next-env.d.ts、pnpm-lock.yaml 和 pnpm-workspace.yaml 不属于本次交付,保留未提交。 - 原有 next-env.d.ts、pnpm-lock.yaml 和 pnpm-workspace.yaml 不属于本次交付,保留未提交。
@@ -80,7 +80,7 @@
## Headless 方案与应用提示依赖 ## Headless 方案与应用提示依赖
本地忽略的 `research-docs/HEADLESS_CANVAS_API_DRAFT.md` 已重写为方案:同步 command/working document 与独立 runtime、operation ledger、ACK 基线分离;提供 component/feature 组合、API A/B/C、八个 viewport slot、实例 mode、混合选择、文件恢复、幂等与撤销设计。仅为待选择方案,没有提取或发布 npm 包,也没有实现 IndexedDB/outbox。特别区分普通 CAS 快照 PATCH 与有 Idempotency-Key 的事务,避免把重试后的 412 错判为原请求零写入。 本地忽略的 `docs/HEADLESS_CANVAS_API_DRAFT.md` 已重写为方案:同步 command/working document 与独立 runtime、operation ledger、ACK 基线分离;提供 component/feature 组合、API A/B/C、八个 viewport slot、实例 mode、混合选择、文件恢复、幂等与撤销设计。仅为待选择方案,没有提取或发布 npm 包,也没有实现 IndexedDB/outbox。特别区分普通 CAS 快照 PATCH 与有 Idempotency-Key 的事务,避免把重试后的 412 错判为原请求零写入。
实际安装 Sonner 2.0.8、Radix Tooltip 1.4.1,并同步 `package-lock.json`。根布局挂应用 provider,固定通知 ID 避免重复;图标按钮保留实际 button/ref 与原尺寸。通用错误/归属完成使用应用通知,原保存冲突、失败上传和重试入口保留。 实际安装 Sonner 2.0.8、Radix Tooltip 1.4.1,并同步 `package-lock.json`。根布局挂应用 provider,固定通知 ID 避免重复;图标按钮保留实际 button/ref 与原尺寸。通用错误/归属完成使用应用通知,原保存冲突、失败上传和重试入口保留。
-50
View File
@@ -1,50 +0,0 @@
# 1. 建立项目模型
[教程目录](README.md) · 下一章:[打开画布](02-open.md)
## 先把产品拆成两条链
Endoleap 是带账户与工作空间的图谱编辑应用。Next.js App Router 负责页面与同源 API;React 负责界面;React Flow 负责画布呈现与交互接入。用户操作最终改变的是 headless 文档模型。
第一条链是“找到我要打开什么”:路由参数 → 账户与 board 元数据 → canonical 项目模型 → engine → 视图。第二条链是“改变它”:界面动作 → editor 命令 → 原子发布 → 界面订阅更新,同时由 runtime 推动持久化与网络同步。
区分这两条链很重要:页面加载状态属于第一条链;某次修改是否被服务器确认属于第二条链。画布显示出来,不代表此前所有写入都已完成。
## 一份事实,几种用途
`Document` 是项目规范化数据,主要有 `projectId`、`canvases`、`elements`、`tombstones`。元素通过 `ownerCanvasId` 归属某个 canvas,节点保存 geometry,连线保存端点与路径。组件私有字段放在 `data` 中。
这里的 board 是路由和工作空间目录中的材料信息;canvas 是文档里的业务结构;ProjectEngine 管理项目的 canonical ID 空间及已加载 canvas。三者有关联,但不能把一次路由切换理解成新建一份独立文档。
| 对象 | 保存什么 | 为什么单独存在 |
| --- | --- | --- |
| Registry | 组件 schema、版本、能力与行为 | 数据与显示实现可以分离,未知类型也能被保留 |
| Editor | 文档提交、历史、查询与命令入口 | 所有编辑遵守同一校验和发布规则 |
| ProjectEngine | Editor 与同步、资源、加载、恢复的协调 | 编辑事实与运行任务需要一致推进 |
| WorkspaceRuntime | 按项目复用 engine,共享工作区资源 | 切换视图不丢失项目任务 |
| RuntimeHost | 按账户/工作区装配与身份隔离 | 旧账户的异步结果不能冒充新账户结果 |
| ViewSession | 选择、焦点、视口、工具和临时手势 | 两个视图能看同一文档而各有交互状态 |
运行时包含关系为 Host → WorkspaceRuntime → ProjectEngine → ViewSession。业务树则是 CanvasRecord 的 parent 关系。DOM 嵌套既不是这两种树的替代品,也不能决定元素 owner。
## 四层代码的职责
`canvas-core` 解释数据、能力、命令、事务、历史与几何规则;`canvas-runtime` 增加调度、存储、恢复、资源和异步作业;`canvas-service` 把运行时端口转换为 Foundry 协议;`canvas-bindings` 把模型与会话投影成可呈现、可订阅、可命中的数据。应用组件负责装配这些能力,并实现具体界面。
因此“改节点的产品规则”通常从 core 查起;“请求丢失后怎么办”去 runtime;“协议字段怎么编码”去 service;“模型正确但画面错误”去 bindings 和组件。
## 身份为什么不只是一个 ID
一个元素的目标由 `id + incarnation` 组成。删除后撤销可以恢复同一个 ID,但恢复实例拥有新的 incarnation。旧输入框或异步回调捕获的 target 不能因此获得修改新实例的权力。账户也有自己的代次保护 `authEpoch`;它保护账户生命周期,不是元素 incarnation。
## 跟踪任务
打开 [types.ts](../src/lib/canvas-core/types.ts),找到 `Document`、`ElementRecord` 和 `Target`,为案例节点画出字段归属。然后查看 [canvas-runtime-host.tsx](../src/components/workspace/canvas-runtime-host.tsx) 的 `CanvasRuntimeHost`,标出 Registry、浏览器端口和 Foundry adapters 在哪里注入。
只要能指出“标题在元素 data 中,选择在 ViewSession 中,服务端确认版本在 runtime 中”,本章就已达标。
## 自检
**关闭一个画布页面,是否应该删除文档并停止全部上传?**
不应该。页面借用 engine,卸载时归还视图;项目和持久任务由工作区运行时管理。真正关闭项目还需要可靠保存等收尾,浏览器卸载回调也不保证一定完成落盘。
-51
View File
@@ -1,51 +0,0 @@
# 2. 打开一张画布
[上一章](01-system.md) · [目录](README.md) · [下一章](03-edit.md)
## 从地址开始
当用户进入 `/dashboard/{workspace}/{board}`,App Router 的 [page.tsx](../src/app/dashboard/[workspace]/[board]/page.tsx) 等待路径参数,再把它们交给 `GraphPage`。这一层没有直接读取模型。
根 [layout.tsx](../src/app/layout.tsx) 已安装 `CanvasRuntimeHost`;dashboard 布局另提供侧栏和活动 board 信息。这意味着画布页面可以复用应用宿主,而不是每次进入路由都自行创建存储和同步器。
## 从路径引用找到真实身份
[GraphPage](../src/components/workspace/graph-page.tsx) 调用 [loadCanvasEntry](../src/lib/canvas-entry.ts)。入口并行请求 board 元数据与 profile,确认材料类型是 board、路径引用匹配、有 workspace ID 和账户 ID,然后才读取模型。
路径里的字符串可能是引用或 slug;持久化作用域需要已解析的真实身份。`workspaceId`、`accountId` 与项目根 ID 在后续参与端口装配、存储隔离与请求校验。
## 为什么先查 canonical
入口优先读取 canonical 模型。模型 `ready` 后采用 headless engine;明确允许旧模式的情形才进入 snapshot 链路。权限失败不能简单当成“新接口不存在”,进而偷偷回退旧读写器。
原因是同一项目一旦采用新模型,旧 snapshot writer 可能无法表达新的数据与操作语义。让它继续写会引入覆盖风险。因此新旧分流是数据完整性边界,不只是选哪个 React 组件。
真实迁移需要显式操作。入口给出的迁移信息说明资格,并不等于可以立即拿这份旧读取结果发迁移写入;执行前还需收拢旧 writer 并刷新源版本。
## 模型如何成为 engine
GraphPage 通过 Host 绑定账户,从对应 WorkspaceRuntime 打开项目。WorkspaceRuntime 按 `document.projectId` 复用打开句柄,避免同一项目重复创建 engine、重复竞争本地 leader。
完整读取到来时可能是首次打开,也可能要与已有 engine 协调。`open()` 返回已有 engine,并不保证新传入文档一定覆盖了它:运行时还会检查版本、加载状态和来源 token,保护已存在的本地编辑。
随后 GraphPage 将 engine 交给 `HeadlessGraphCanvas`。旧模式则交给 `GraphCanvas`。这个分叉解释了为何仓库同时存在两组画布组件。
## 大模型为什么能先显示一部分
模型读取可以报告前缀预览。GraphPage 在当前 board 已进入前缀时显示预览,有元素后可建立 partial engine;后续前缀在同一加载上下文里继续被采用,完整读取最终收尾。
前缀不是完整项目。加载状态会限制不安全操作;较新的协议允许在证据和持久屏障满足时执行部分操作,不能概括为“未加载完全部只读”或“显示出来便全部可编辑”。完整结果也必须等前缀采用链结束,不能覆盖其间发生的编辑。
导航取消、路由匹配、账户代次和 source token 分别解决不同问题:停止旧读取、避免旧画布闪现、隔离换号结果、识别同次模型来源。一个 `isLoading` 布尔值无法替代它们。
## 跟踪任务
在 GraphPage 中依次定位 `loadCanvasEntry`、`onPreview`、`openPartial`、`workspace(...).open` 和返回 JSX。写出以下五个状态的显示结果:尚无模型、只读预览、partial engine、完整 engine、legacy snapshot。
再读 [entry.test.mjs](../tests/headless/entry.test.mjs) 的前两个测试,确认已采用项目不读取旧快照,以及权限失败不会变成兼容回退。
## 自检
**用户快速从画布 A 切到 B,A 的慢响应回来后该怎么办?**
它不能把 A 显示到 B 的路由,也不能越过账户身份围栏。页面清理取消本次读取并撤销显示资格;已拥有的 partial 项目可能继续后台补全,不能为了清页面直接关闭共享 engine。
-59
View File
@@ -1,59 +0,0 @@
# 3. 一次编辑如何成立
[上一章](02-open.md) · [目录](README.md) · [下一章](04-view.md)
## 把“改标题”翻译成命令
假设当前节点有有效 target,支持对应编辑能力。标题从“想法”改为“行动”的核心接口形态是:
```ts
engine.editor.dispatch({
type: 'element.data',
target, // 当前元素的 { id, incarnation }
patch: { title: '行动' },
});
```
这只是已取得 engine 后的命令示意。真实界面还要处理焦点、编辑租约、目标是否仍有效等问题。不要绕过命令直接修改 snapshot 中的 Map 或元素对象;它们是受保护的发布结果。
## 从命令到候选文档
[editor.ts](../src/lib/canvas-core/editor.ts) 的 `dispatch` 是同步 `transaction` 的便捷封装。事务内部先在候选文档上规划命令,得到 changes。规划会解析目标、检查宿主 policy、组件能力和字段规则;提交前还会对候选文档做整体校验。
Registry 在这里负责解释“这个组件允许什么”。一个元素存在,不等于它支持任意命令。未来版本和未知组件可以保留原始数据,但不能借此调用未安装的行为。
Change 描述实际发生的变化,OperationIntent 描述需要同步的逻辑意图,HistoryEntry 则组织用户可撤销的工作单元。它们有关联,却不是同一个对象。
## 为什么两个命令可以一起成功或一起失败
例如一个 counter 节点同时移动位置并把 count 改为负数。第一条命令可以在候选文档中成立,第二条违反 schema。事务最终拒绝时,候选文档被丢弃,原文档、历史、操作记录和通知均不应留下第一条命令的结果。
完整例子在 [consumer.mjs](../headless/consumer.mjs):找到标有“非法事务”的部分,再与后面的合法事务比较。合法的移动与计数更新被组织成一个历史单元。
事务回调必须同步。异步读取和资源准备先在事务外完成,再带着仍需重新验证的目标进入事务。`await` 期间世界可能变化,不能持有一个可在稍后继续写的事务草稿。
## 发布边界里还有 runtime
事务成功后进入 `publish`,构造历史与操作等候选状态。engine 创建 Editor 时注入 `reduceRuntime`,将新操作合入 ledger,并整合相关资源任务;`prepareRuntime` 再检查所有权、加载和资源保留等规则。
这些准备在最终 state 赋值之前完成,因此“文档已改但待同步操作没有入账”不应成为一次成功提交的状态。准备钩子不做网络 I/O;如果它们偷偷产生外部写入,丢弃候选根也无法撤销外部副作用。
订阅者随后观察已发布状态,更新页面或调度后续工作。监听器发生异常不能把已经提交的文档倒回去。
## 撤销为什么不是恢复整个旧快照
撤销根据历史变化与当前状态执行校验,再发布补偿意图。它必须保留期间到来的有效服务端资源确认等运行事实。如果只是把整个状态替换成编辑前的快照,这些事实会丢失。
同字段冲突时撤销可能拒绝,并保持历史栈不动。删除后撤销恢复元素会产生新的 incarnation,因此此前捕获的 target 继续失效。一次无实际变化的提交可以返回 applied,但不产生新的 operation;applied 不代表必然发生写入。
## 跟踪任务
先跟踪 `dispatch → transaction → plan → publish`,再到 [engine.ts](../src/lib/canvas-runtime/engine.ts) 找 `createEditor` 的 `reduceRuntime` 和 `prepareRuntime`。标出候选状态在哪里变成发布状态。
在 [core.test.mjs](../tests/headless/core.test.mjs) 阅读标题含 `rejected second command`、`same-field conflict`、`async transactions` 的测试。分别写出它们保护的事实。
## 自检
**`dispatch()` 返回 applied,是否意味着服务器已保存?**
不是。它说明本地命令已成功处理;还需区分有无实际变化、本地可靠持久化是否完成,以及操作是否收到并协调了服务器回执。下一章看页面为什么能先响应,第 5 章再看后续可靠性。
-43
View File
@@ -1,43 +0,0 @@
# 4. 拖动节点与画面更新
[上一章](03-edit.md) · [目录](README.md) · [下一章](05-sync.md)
## 文档坐标不是屏幕坐标
节点 geometry 属于 owner canvas 的局部空间。嵌套 canvas 带来祖先变换,视口又有平移与缩放。一个鼠标位置必须经过相应转换,才能成为正确的文档几何。
因此问题“拖完为什么跳动”至少可能来自三处:坐标转换不一致、临时预览与提交几何不一致、旧目标回调迟到。直接调整 React Flow 节点数组,可能暂时改变画面,却没有修复业务文档。
## 手势先预览,结束才提交
拖动开始时,sessions 为有效 target 建立手势;移动过程更新临时几何,投影读取有效几何来显示位置;结束时才把最终结果提交到 Editor。取消时释放预览,恢复基于已提交文档的显示。
这样连续 pointermove 无需每次都生成历史和网络写入。一段有效拖动可成为一个历史单元。取消只处理自己的手势,不能把这段时间并行发生的资源 ACK 或其他有效状态也撤销。
当前约束下,一个项目同时最多一个写几何的手势。视图 detach 或目标失效会取消对应手势;组件里的编辑租约还保护旧事件处理器,避免它在新的交互开始后提交旧目标。
## 从事实到可画的数据
[HeadlessGraphCanvas](../src/components/canvas/headless-graph-canvas.tsx) 同时消费 engine 根和 sessions。场景投影结合文档、当前视图、Registry、renderer 目录及查询,得到 React Flow 使用的节点、边和相关呈现数据。
投影是派生结果。元素的 owner、业务 data 和历史仍以模型为准;选择与临时预览来自会话。投影缓存与索引是为了减少重复工作,不应成为另一份可以独立编辑的业务文档。
[canvas-renderers.tsx](../src/components/canvas/canvas-renderers.tsx) 把 renderer 描述映射到具体 React 组件。Registry 回答“数据是什么、允许做什么”,renderer 回答“怎样显示”。只添加一个 React 节点组件,不足以完成可编辑的新类型。
## 更新如何到达 React
Editor 提交订阅先推进场景索引,再通知显示。代码对用户字段修改、undo/redo 等采用及时通知,避免受控输入落后;批量创建和后台变化允许合并到呈现帧。sessions 也有自己的通知节奏。
注意两种时间:文档已经提交的时间,与 React 执行下一次呈现的时间。逐帧合并通知不会把真实提交推迟到下一帧,也不能据此认为同帧发生的业务操作被合成一次事务。
## 跟踪任务
在主画布组件定位 `sceneCache`、Editor 的 `subscribe`、`createSessionFrameSource`、`sceneCache.project`,再找 `beginTransform`。画出“pointer → sessions → 投影 → React Flow”和“提交 → Editor → 投影更新”两条路径。
然后阅读 [consumer.mjs](../headless/consumer.mjs) 的手势取消断言:有效几何变了,但取消后文档坐标不变,请求数也不增加。它在没有 DOM 的情况下展示了业务规则。
## 自检
**视口缩放是否应改写每个节点的 geometry?**
不应该。视口是视图状态,模型坐标保持其业务空间含义。需要坐标转换的是输入、投影和命中过程。混淆两者会让嵌套和多视图行为难以保持一致。
-59
View File
@@ -1,59 +0,0 @@
# 5. 本地保存、网络同步与恢复
[上一章](04-view.md) · [目录](README.md) · [下一章](06-development.md)
## 三种“成功”
用户改完标题,页面立即显示“行动”。此时只知道本地发布成功。之后还需要可靠保存恢复材料,再推动网络请求,最后解释服务器结果。
| 阶段 | 已知事实 | 尚不能推断 |
| --- | --- | --- |
| 本地发布 | 当前内存文档及关联状态已更新 | 浏览器崩溃后可恢复 |
| 本地持久化 | 对应恢复材料已被存储端口确认 | 服务端已经采用修改 |
| 服务器结果协调完成 | 回执已被解释并纳入本地状态 | 其他尚未完成操作也已同步 |
## ledger 为什么与文档一起推进
ledger 记录逻辑操作、依赖和请求事实。scheduler 根据这些事实判断谁能发送,处理冻结请求、占用、重试和状态查询。它不会通过比较 React 组件状态来猜测需要保存什么。
[engine.ts](../src/lib/canvas-runtime/engine.ts) 将本地提交转换为 ledger 更新,然后把 ledger 读取、状态更新、可靠保存和具体请求执行注入 [scheduler.ts](../src/lib/canvas-runtime/scheduler.ts)。这把“决定发送什么”和“具体怎么访问 Foundry”分开。
请求冻结后,重试必须保持原请求身份与内容。发送之前要可靠保存相关请求身份和前置状态,否则进程在服务端执行后崩溃,重启时可能无法知道自己已经发过什么。
## 请求走到哪里
浏览器服务适配器通过同源 transport 访问 Next 的 [Foundry route handler](../src/app/api/foundry/[...path]/route.ts),由服务端代理请求上游。浏览器持 HttpOnly 会话 Cookie;代理在服务端转换上游认证,并限制路径、请求头、大小和超时。
[canvas-service/foundry.ts](../src/lib/canvas-service/foundry.ts) 处理 canonical 模型、操作协议与回执语义。代理负责传输边界,不能替代领域 schema 校验。冻结写入保留原字节,避免在中转时重编码而破坏请求身份。
认证到期续期由后端会话合同和 [session-cookie.ts](../src/lib/session-cookie.ts) 等代理逻辑协作完成。前端不能单靠延长浏览器 Cookie 来复活服务器已失效的会话。
## 请求发出后断网,为什么不能直接重做
假设服务器已执行“想法 → 行动”,响应在途中丢失。客户端看到的网络错误不证明操作未执行。若立刻生成新请求,复制、创建等操作可能重复发生。
因此 runtime 保留原冻结请求与不确定状态,沿原身份查询或重试。`accepted` 也不等于最终应用并协调完成。具体状态需要服务协议解释,不能把 HTTP 成功统一变成“保存完成”。
## ACK 如何避免盖掉后续编辑
客户端收到第一次标题修改的确认时,用户可能已继续输入。runtime 维护 acknowledged 基线与当前 working 文档,根据回执推进已确认状态,再协调尚未解决的本地操作。不能把服务端返回的文档直接覆盖到界面上,否则后一次编辑会丢失。
[reconcile.ts](../src/lib/canvas-runtime/reconcile.ts) 提供相关协调与重放逻辑。若服务端已应用,但本地无法安全协调,engine 保留回执和冲突材料,阻塞相关流程并报告恢复需求;它不会把失败候选中的一半状态当成成功发布。
## 刷新后如何接续
浏览器 storage 适配器使用 IndexedDB 等能力保存恢复记录,并配合 leader 所有权控制本地写入。重新打开项目先解释恢复材料,再处理未解决请求。恢复需要的不只是最终 Document,还包括历史、ledger、已确认基线及相关资源和版本证据。
[storage-port.ts](../src/lib/canvas-runtime/storage-port.ts) 定义端口合同;[storage.ts](../src/lib/canvas-runtime/storage.ts) 实现浏览器侧存储;[recovery.ts](../src/lib/canvas-runtime/recovery.ts) 负责恢复编解码。内存示例能证明合同接线,但不能证明跨进程崩溃持久性。
## 跟踪任务
在 engine 中找到 `createScheduler`,标出 `persistThrough`、执行请求与协调结果的连接。到 [engine.test.mjs](../tests/headless/engine.test.mjs)、[durability.test.mjs](../tests/headless/durability.test.mjs)、[crash-windows.test.mjs](../tests/headless/crash-windows.test.mjs) 中,分别找普通编辑、发送持久屏障、崩溃窗口相关断言。
用自己的话写出“本地提交 → 恢复材料可靠保存 → 请求发送 → 结果解释 → ACK/working 协调”。这是职责时序;具体 I/O 可以批处理或重入调度,不能把这句话当作每次都只发生一次的函数调用栈。
## 自检
**为什么刷新后不只重新 GET 服务端模型?**
因为尚未确认的本地编辑、结果未知的请求和可恢复任务可能只存在本地。直接丢掉恢复记录会丢失用户工作,也可能让已执行的操作再次执行。
-52
View File
@@ -1,52 +0,0 @@
# 6. 用模型指导开发与排查
[上一章](05-sync.md) · [目录](README.md)
## 练习:为 counter 增加“加一”按钮
先在纸上设计,再动源码。目标不是把按钮画出来,而是让它遵守事务、历史、同步和目标生命周期规则。
1. 模型:counter 的 `count` 是 JSON data,Registry 校验它的合法范围。`consumer.mjs` 已有完整自定义组件示例,可以先理解其定义。
2. 行为:按钮在最新状态下读取有效 target 和 count,通过受支持的命令提交 `element.data`。默认用户编辑进入历史与同步流程,不另写一套 fetch 保存。
3. 显示:在 renderer 目录中登记与组件 ID、版本和结构匹配的 React renderer;由应用宿主组合模型定义与 renderer 定义。
4. 生命周期:点击时重新确认目标,避免使用删除前捕获的 incarnation;组件卸载只清自己的事件和视图租约。
5. 验证:检查加一后文档值、undo/redo、非法数据拒绝及旧 target 拒绝;如果改动触及协议,再验证请求与回执。不要只测试按钮文字变了。
这里不提供一段未经项目接线验证的“可直接运行插件”。练习的产物是一份变更设计和检查方案。扩展入口可从 [CanvasRuntimeHost](../src/components/workspace/canvas-runtime-host.tsx) 的 `extensions` 与 [createReactRenderers](../src/lib/canvas-bindings/react-renderers.ts) 跟踪。
## 同一症状,从哪层排查
| 症状 | 第一处证据 | 接下来问什么 |
| --- | --- | --- |
| 一直正在打开 | GraphPage 的 error、入口结果 | 引用、身份、新旧分流还是模型加载失败? |
| 点击后无变化 | 命令 Result | 被 policy、能力、schema 还是旧 target 拒绝? |
| 文档正确但显示错误 | scene projection 与 renderer 输入 | 会话、坐标、缓存失效还是渲染映射错误? |
| 页面已改但刷新丢失 | 本地持久化结果、恢复记录 | 修改是否真正可靠落盘,作用域是否正确? |
| 操作迟迟未同步 | ledger、scheduler 门禁 | 依赖、身份、加载、持久屏障还是不确定请求阻塞? |
| 撤销失败 | History 与冲突结果 | 当前字段是否已变化,目标代次是否仍有效? |
| 上传完成但节点不对 | resource 记录与文档引用 | 上传事实、附件采用和节点编辑是否分别协调? |
先确认事实在哪层首次偏离,再修对应边界。比如命令已明确 rejected,就先解释拒绝码;此时刷新 renderer 通常不能解决问题。
## 如何选择测试
core 测试关注规则和原子性;runtime 测试关注操作、存储与恢复;service 测试关注协议;bindings 测试关注投影、订阅与命中;浏览器与页面集成测试才覆盖真实适配器、焦点和事件。
同一条测试通过有明确边界:内存 storage 不能证明 IndexedDB 崩溃安全;模拟 transport 不能证明线上 Foundry 正确;源码加载通过也不能证明编译包 exports、Worker URL 正确。
执行前检查 `package.json` 和对应脚本。`build:headless` 会生成产物;`test:headless:package` 包含构建打包;页面、proxy、浏览器集成也需检查是否隐式编译或启动服务。需要构建的步骤使用用户确认的远程 runner。本教程编写只做文档和引用检查,没有重跑这些产品测试。
## 完成整套教程的检查
尝试不用看答案,讲解这段场景:用户打开项目,改标题,开始拖动;服务器返回上次编辑的 ACK;用户取消拖动,然后刷新。
合格的解释至少包含:
- 入口解析真实身份并选择新旧模型;WorkspaceRuntime 取得或复用 engine。
- 标题命令在候选根上验证,文档、历史和待同步事实一起发布。
- 拖动是会话预览,取消不会回退已提交标题,也不会抹掉服务器 ACK。
- 界面从文档、会话与 renderer 派生显示,不单独拥有业务真相。
- 发送前有可靠保存要求;ACK 需要与后续本地状态协调。
- 刷新解释本地恢复材料,不盲目覆盖为服务端最新模型;未解决请求沿原身份接续。
能讲清这段过程,就已具备定位大部分编辑链路问题的基础。接下来按实际开发目标深入资源、导入或渐进加载,而无需先通读整个仓库。
-34
View File
@@ -1,34 +0,0 @@
# 从一次画布操作理解 Endoleap
这套教程带你回答一个完整问题:用户打开图谱、修改节点、拖动节点,再刷新页面时,Endoleap 如何让页面、内存文档、本地恢复记录和服务端保持一致?
面向能阅读 TypeScript 和 React、但还不熟悉本项目的开发者。无需先阅读历史设计文档。章节中的源码链接用于定位讲解对象;先理解过程,再按任务跟踪函数,无需逐文件通读。
## 学习路线与完成标准
| 顺序 | 章节 | 读完应能解释 |
| --- | --- | --- |
| 1 | [建立项目模型](01-system.md) | 页面、文档、engine、视图分别保存什么 |
| 2 | [打开一张画布](02-open.md) | URL 如何变成可编辑画布,以及为何有新旧入口 |
| 3 | [完成一次编辑](03-edit.md) | 命令如何原子更新文档、历史与待同步操作 |
| 4 | [拖动与画面更新](04-view.md) | 手势预览、正式提交、投影与 React Flow 的关系 |
| 5 | [保存、同步与恢复](05-sync.md) | 本地成功与服务器确认的区别,以及失败如何收尾 |
| 6 | [开发与排查实践](06-development.md) | 新功能放在哪层,应补哪类验证,故障从哪里查 |
建议分三轮:第一轮读 1–3 章建立正常编辑链路;第二轮读 4–5 章掌握交互与可靠性;第三轮完成第 6 章的设计练习。每章末尾都有自检和答案,达到完成标准再进入下一章。
贯穿案例使用一个已有节点:标题为“想法”,用户将它改为“行动”,再拖动位置。案例中的短代码是接口示意,假定你已取得当前 engine 和有效 target;它不是直接粘贴就能独立运行的脚本。独立宿主的完整装配例子在 [consumer.mjs](../headless/consumer.mjs)。
## 阅读基线与边界
本教程依据主线提交 `960a3ff` 的源码编写。讲解重点是 canonical/headless 链路;旧 snapshot 编辑器仍为未升级项目及演示等路径提供兼容。教程会指出分流位置,不假定所有画布已迁移。
仓库包含 Next.js 前端、浏览器运行时和 Foundry 客户端适配器;Foundry 后端不在本仓库。这里可以解释请求如何生成和处理回执,不能由前端源码推断线上部署状态、权限配置或后端数据库实现。
`research-docs/` 保留原有本地研究、规格和历史验收资料,并继续被 Git 忽略。它们是本教程的写作来源,读者不需要拥有这些文件。本文不将历史验收数字当作当前分支已重新通过的检查结果。
## 如何使用源码和测试
每章的“跟踪任务”只要求查看少数符号,并写出你自己的时序。测试的价值是展示输入、边界和可观察结果,不必先运行整个项目。
本教程不要求启动开发服务器或构建。项目约定将编译、构建、打包及隐式触发这些动作的验证交给已确认的远程 runner;需要实际执行时先确认 runner。不要因 README 列出了 `npm run dev` 就默认在本机启动。
+2 -2
View File
@@ -6,7 +6,7 @@
前端产品实现基线为 `15ee917`,此前包含 `b05058a` 的迁移数据校验修复;真实服务 consumer 固定为 `dcbbdad25de7c3b1d6bee317df6074da2c0642eb`。后续 `d3eef78` 和本次修改增加测试与交付文档,不修改产品实现。后端为 `506f778ac33d47fbd6f38412995a10218d59fe0a`。 前端产品实现基线为 `15ee917`,此前包含 `b05058a` 的迁移数据校验修复;真实服务 consumer 固定为 `dcbbdad25de7c3b1d6bee317df6074da2c0642eb`。后续 `d3eef78` 和本次修改增加测试与交付文档,不修改产品实现。后端为 `506f778ac33d47fbd6f38412995a10218d59fe0a`。
后端现有 ces-control CI [#1186](https://gitea.entroia.com/Zayden-Jung/foundry-core/actions/runs/1186) 与 [#1187](https://gitea.entroia.com/Zayden-Jung/foundry-core/actions/runs/1187) 的七个阶段全部成功,包括实际认证 HTTP、PostgreSQL、资源与 RunPort consumer。两次报告全部功能标志为 true,生成执行次数均为 3。轮询次数随调度变化,不能用总 HTTP 次数代替“不重复受理”的独立断言。详见 [SERVICE_ACCEPTANCE.md](SERVICE_ACCEPTANCE.md)。 后端现有 ces-control CI [#1186](https://gitea.entroia.com/Zayden-Jung/Bedrock/actions/runs/1186) 与 [#1187](https://gitea.entroia.com/Zayden-Jung/Bedrock/actions/runs/1187) 的七个阶段全部成功,包括实际认证 HTTP、PostgreSQL、资源与 RunPort consumer。两次报告全部功能标志为 true,生成执行次数均为 3。轮询次数随调度变化,不能用总 HTTP 次数代替“不重复受理”的独立断言。详见 [SERVICE_ACCEPTANCE.md](SERVICE_ACCEPTANCE.md)。
下面命令从 Endoleap 源码仓库根目录执行。Node 测试通过不自动替代浏览器或真实后端证据。用户允许本地前端编译与测试;后端编译、容器和数据库验收只在既有远程 CI 执行。 下面命令从 Endoleap 源码仓库根目录执行。Node 测试通过不自动替代浏览器或真实后端证据。用户允许本地前端编译与测试;后端编译、容器和数据库验收只在既有远程 CI 执行。
@@ -99,4 +99,4 @@ A/B 维护 immutable Registry、规范化文档、命令/事务、history 双
## 最终交付状态(2026-11-11) ## 最终交付状态(2026-11-11)
T01–T36矩阵、当前前端回归、远程服务验收及独立SDK消费检查完成,原七步实现/验收交付完成。前端验收提交 `14f7475` 已推送 `codex/headless-canvas-v1`;后续只有交付状态记录更新。前后端相对最新main的merge-tree演算无冲突;后端506f778状态检查success。Foundry [PR #19](https://gitea.entroia.com/Zayden-Jung/foundry-core/pulls/19)已由Draft转为可评审,API返回draft=false、mergeable=true,等待用户手动合并。前端遵循当前不新建PR的项目约定保留工作分支。两仓库均未由bot合并main或部署。 T01–T36矩阵、当前前端回归、远程服务验收及独立SDK消费检查完成,原七步实现/验收交付完成。前端验收提交 `14f7475` 已推送 `codex/headless-canvas-v1`;后续只有交付状态记录更新。前后端相对最新main的merge-tree演算无冲突;后端506f778状态检查success。Foundry [PR #19](https://gitea.entroia.com/Zayden-Jung/Bedrock/pulls/19)已由Draft转为可评审,API返回draft=false、mergeable=true,等待用户手动合并。前端遵循当前不新建PR的项目约定保留工作分支。两仓库均未由bot合并main或部署。
+1 -1
View File
@@ -1224,7 +1224,7 @@ not evidence for response-loss recovery. Its remote worker fixture replaces
only generation output, not authenticated HTTP, PostgreSQL or service receipts. only generation output, not authenticated HTTP, PostgreSQL or service receipts.
`createFoundryAssets` accepts a host `displayURL(id)` callback. Its default is `createFoundryAssets` accepts a host `displayURL(id)` callback. Its default is
Endoleap's same-origin `/api/foundry/...` preview route; a Node or other host must Endoleap's same-origin `/api/bedrock/...` preview route; a Node or other host must
provide its own reachable preview route and arrange authentication there. This provide its own reachable preview route and arrange authentication there. This
does not change `sourceURL`, canonical asset identity or the authority scope. does not change `sourceURL`, canonical asset identity or the authority scope.
Use `assets.authority.read` for original bytes and digest verification: a display Use `assets.authority.read` for original bytes and digest verification: a display
+5 -5
View File
@@ -11,19 +11,19 @@ production deployment are separate, pending steps.
- Current verified Endoleap service consumer: `dcbbdad25de7c3b1d6bee317df6074da2c0642eb` - Current verified Endoleap service consumer: `dcbbdad25de7c3b1d6bee317df6074da2c0642eb`
(product implementation `15ee917`; receipt diagnostics added by `dcbbdad`). (product implementation `15ee917`; receipt diagnostics added by `dcbbdad`).
- Current Foundry: `506f778ac33d47fbd6f38412995a10218d59fe0a`. - Current Foundry: `506f778ac33d47fbd6f38412995a10218d59fe0a`.
- [Foundry CI #1186](https://gitea.entroia.com/Zayden-Jung/foundry-core/actions/runs/1186): - [Foundry CI #1186](https://gitea.entroia.com/Zayden-Jung/Bedrock/actions/runs/1186):
job 1283 completed successfully, all seven steps successful. All prior flags job 1283 completed successfully, all seven steps successful. All prior flags
and `dissolveCanvas`, `dissolveLostAckRecovered`, `dissolveUndoRedo` are true; and `dissolveCanvas`, `dissolveLostAckRecovered`, `dissolveUndoRedo` are true;
`aiExecutionCount: 3`, 84 transport calls. The new canonical-frame rotation `aiExecutionCount: 3`, 84 transport calls. The new canonical-frame rotation
test also passed. Same-commit PR CI #1187/job 1284 subsequently passed all seven test also passed. Same-commit PR CI #1187/job 1284 subsequently passed all seven
steps, with the same flags/execution count and 83 transport calls. steps, with the same flags/execution count and 83 transport calls.
- [Foundry CI #1182](https://gitea.entroia.com/Zayden-Jung/foundry-core/actions/runs/1182): - [Foundry CI #1182](https://gitea.entroia.com/Zayden-Jung/Bedrock/actions/runs/1182):
job 1279 completed successfully, all seven steps successful, pinned to the job 1279 completed successfully, all seven steps successful, pinned to the
browser delivery baseline `24c4592`, Foundry `5db2bf3`. Its report has all document/resource/AI and browser delivery baseline `24c4592`, Foundry `5db2bf3`. Its report has all document/resource/AI and
migration flags true, `aiExecutionCount: 3`, and 75 transport calls. migration flags true, `aiExecutionCount: 3`, and 75 transport calls.
Same-commit PR CI #1183/job 1280 subsequently passed all seven steps too. Same-commit PR CI #1183/job 1280 subsequently passed all seven steps too.
- [Foundry CI #1180](https://gitea.entroia.com/Zayden-Jung/foundry-core/actions/runs/1180) - [Foundry CI #1180](https://gitea.entroia.com/Zayden-Jung/Bedrock/actions/runs/1180)
and [PR CI #1181](https://gitea.entroia.com/Zayden-Jung/foundry-core/actions/runs/1181): and [PR CI #1181](https://gitea.entroia.com/Zayden-Jung/Bedrock/actions/runs/1181):
completed successfully for consumer `26da326` and Foundry `3268c57`; completed successfully for consumer `26da326` and Foundry `3268c57`;
jobs 1277/1278, all seven steps successful. The original service scope audit jobs 1277/1278, all seven steps successful. The original service scope audit
also passed CI #1178 and #1179. also passed CI #1178 and #1179.
@@ -167,6 +167,6 @@ compatibility, identity mapping, source-version/permission/run admission barrier
and rollback after writes have begun. Migration/delivery now has the separate and rollback after writes have begun. Migration/delivery now has the separate
browser/package evidence above; the final requirement matrix now has its separate per-row audit. A green browser/package evidence above; the final requirement matrix now has its separate per-row audit. A green
feature-branch run does not merge or deploy feature-branch run does not merge or deploy
either repository. [Foundry PR #19](https://gitea.entroia.com/Zayden-Jung/foundry-core/pulls/19) either repository. [Foundry PR #19](https://gitea.entroia.com/Zayden-Jung/Bedrock/pulls/19)
is open, ready for review (`draft: false`, `mergeable: true`, checked 2026-11-11), is open, ready for review (`draft: false`, `mergeable: true`, checked 2026-11-11),
and waits for the user to merge manually. and waits for the user to merge manually.
@@ -91,8 +91,8 @@ async function handler(
} }
const bodyReceived = performance.now(); const bodyReceived = performance.now();
// 上游地址来自服务端环境,客户端path白名单不会让调用者自己指定任意目标源站。 // 上游地址来自服务端环境,客户端path白名单不会让调用者自己指定任意目标源站。
const origin = process.env.FOUNDRY_API_ORIGIN || "https://api.foundry.entroia.com"; const origin = process.env.BEDROCK_API_ORIGIN || "https://api.foundry.entroia.com";
const project = process.env.NEXT_PUBLIC_FOUNDRY_PROJECT || "endoleap"; const project = process.env.NEXT_PUBLIC_BEDROCK_PROJECT || "endoleap";
// multipart沿用浏览器Content-Type和boundary,其余发JSON;不透传浏览器任意请求头。 // multipart沿用浏览器Content-Type和boundary,其余发JSON;不透传浏览器任意请求头。
const headers: Record<string, string> = { "Content-Type": asset ? (req.headers.get("content-type") || "application/octet-stream") : "application/json" }; const headers: Record<string, string> = { "Content-Type": asset ? (req.headers.get("content-type") || "application/octet-stream") : "application/json" };
if (canvas) headers.Accept = "application/vnd.foundry.canvas+json;version=2"; if (canvas) headers.Accept = "application/vnd.foundry.canvas+json;version=2";
+2 -2
View File
@@ -21,8 +21,8 @@ export async function GET(
) )
return NextResponse.json({ error: "invalid_request" }, { status: 400 }); return NextResponse.json({ error: "invalid_request" }, { status: 400 });
// 上游源站/项目由宿主环境装配,不让查询参数决定任意OAuth重定向目标。 // 上游源站/项目由宿主环境装配,不让查询参数决定任意OAuth重定向目标。
const origin = process.env.FOUNDRY_API_ORIGIN || "https://api.foundry.entroia.com"; const origin = process.env.BEDROCK_API_ORIGIN || "https://api.foundry.entroia.com";
const project = process.env.NEXT_PUBLIC_FOUNDRY_PROJECT || "endoleap"; const project = process.env.NEXT_PUBLIC_BEDROCK_PROJECT || "endoleap";
return NextResponse.redirect( return NextResponse.redirect(
origin + "/projects/" + encodeURIComponent(project) + "/auth/" + provider + "?challenge=" + challenge, origin + "/projects/" + encodeURIComponent(project) + "/auth/" + provider + "?challenge=" + challenge,
{ status: 302, headers: { "Cache-Control": "no-store" } }, { status: 302, headers: { "Cache-Control": "no-store" } },
+2 -2
View File
@@ -11,8 +11,8 @@ export default async function Home() {
const session = (await cookies()).get("foundry_session")?.value; const session = (await cookies()).get("foundry_session")?.value;
let authenticated = false; let authenticated = false;
if (session) { if (session) {
const origin = process.env.FOUNDRY_API_ORIGIN || "https://api.foundry.entroia.com"; const origin = process.env.BEDROCK_API_ORIGIN || "https://api.foundry.entroia.com";
const project = process.env.NEXT_PUBLIC_FOUNDRY_PROJECT || "endoleap"; const project = process.env.NEXT_PUBLIC_BEDROCK_PROJECT || "endoleap";
try { try {
const response = await fetch(`${origin}/projects/${encodeURIComponent(project)}/profile`, { const response = await fetch(`${origin}/projects/${encodeURIComponent(project)}/profile`, {
headers: { Authorization: `Bearer ${session}` }, headers: { Authorization: `Bearer ${session}` },
@@ -81,7 +81,7 @@ export function HeadlessResourcePicker({engine,workspaceId,canvasId,position,clo
return <Dialog open onOpenChange={open=>{if(!open)dismiss();}}><DialogContent data-canvas-ui-view={viewId} aria-describedby={descriptionId}> return <Dialog open onOpenChange={open=>{if(!open)dismiss();}}><DialogContent data-canvas-ui-view={viewId} aria-describedby={descriptionId}>
<DialogHeader><DialogTitle>从其它画布添加图片</DialogTitle><DialogDescription id={descriptionId}>选择同一工作区已打开画布中的图片,无需再次上传。</DialogDescription></DialogHeader> <DialogHeader><DialogTitle>从其它画布添加图片</DialogTitle><DialogDescription id={descriptionId}>选择同一工作区已打开画布中的图片,无需再次上传。</DialogDescription></DialogHeader>
{loading?<p role="status">正在查找图片…</p>:items.length===0?<p>暂无可复用的图片。先打开有已上传图片的画布,再回到这里。</p>:<div className="grid max-h-80 grid-cols-2 gap-3 overflow-y-auto">{items.map(item=><button key={item.id} type="button" aria-label={`添加图片:${item.title}`} disabled={!!busy} onClick={()=>void insert(item)} className="flex min-w-0 flex-col items-center gap-2 rounded-lg border border-border p-3 text-sm hover:bg-muted disabled:opacity-50"> {loading?<p role="status">正在查找图片…</p>:items.length===0?<p>暂无可复用的图片。先打开有已上传图片的画布,再回到这里。</p>:<div className="grid max-h-80 grid-cols-2 gap-3 overflow-y-auto">{items.map(item=><button key={item.id} type="button" aria-label={`添加图片:${item.title}`} disabled={!!busy} onClick={()=>void insert(item)} className="flex min-w-0 flex-col items-center gap-2 rounded-lg border border-border p-3 text-sm hover:bg-muted disabled:opacity-50">
<span className="flex h-20 w-full items-center justify-center overflow-hidden rounded bg-muted"><Preview src={`/api/foundry/workspaces/${encodeURIComponent(workspaceId)}/assets/${encodeURIComponent(item.id)}?variant=preview`}/></span><span className="w-full truncate">{item.title}</span>{busy===item.id&&<span role="status">正在添加…</span>} <span className="flex h-20 w-full items-center justify-center overflow-hidden rounded bg-muted"><Preview src={`/api/bedrock/workspaces/${encodeURIComponent(workspaceId)}/assets/${encodeURIComponent(item.id)}?variant=preview`}/></span><span className="w-full truncate">{item.title}</span>{busy===item.id&&<span role="status">正在添加…</span>}
</button>)}</div>} </button>)}</div>}
{error&&<p role="alert">{error}</p>} {error&&<p role="alert">{error}</p>}
</DialogContent></Dialog>; </DialogContent></Dialog>;
@@ -43,7 +43,7 @@ export default function LoadingGraphCanvas({preview,canvasId,registry,renderers,
// 每条边端点都追加描述,不按 handleId 去重;PreparingNode 使用临时索引 key,仅供预览定位。 // 每条边端点都追加描述,不按 handleId 去重;PreparingNode 使用临时索引 key,仅供预览定位。
const handles=new Map<string,{id?:string;type:'source'|'target'}[]>();for(const edge of value.edges)for(const type of ['source','target'] as const){const id=edge[type],rows=handles.get(id)??[];rows.push({type,id:edge[type==='source'?'sourceHandle':'targetHandle']??undefined});handles.set(id,rows);} const handles=new Map<string,{id?:string;type:'source'|'target'}[]>();for(const edge of value.edges)for(const type of ['source','target'] as const){const id=edge[type],rows=handles.get(id)??[];rows.push({type,id:edge[type==='source'?'sourceHandle':'targetHandle']??undefined});handles.set(id,rows);}
// 节点禁用拖动/选择/焦点/连接及指针,边禁用选择/焦点;已知组件声明assetId资源字段才设置预览URL。 // 节点禁用拖动/选择/焦点/连接及指针,边禁用选择/焦点;已知组件声明assetId资源字段才设置预览URL。
return{nodes:value.nodes.map(node=>({...node,draggable:false,selectable:false,focusable:false,connectable:false,style:{...node.style,pointerEvents:'none' as const},data:{...node.data,__previewHandles:handles.get(node.id)??[],...(registry.resolve(preview.document.elements.get(node.id)!)==='known'&&typeof node.data.assetId==='string'&&registry.components.get(preview.document.elements.get(node.id)!.componentId)?.resourceFields?.includes('assetId')?{src:`/api/foundry/workspaces/${encodeURIComponent(workspaceId)}/assets/${encodeURIComponent(node.data.assetId)}?variant=preview`}:{})}})),edges:value.edges.map(edge=>({...edge,selectable:false,focusable:false}))}; return{nodes:value.nodes.map(node=>({...node,draggable:false,selectable:false,focusable:false,connectable:false,style:{...node.style,pointerEvents:'none' as const},data:{...node.data,__previewHandles:handles.get(node.id)??[],...(registry.resolve(preview.document.elements.get(node.id)!)==='known'&&typeof node.data.assetId==='string'&&registry.components.get(preview.document.elements.get(node.id)!.componentId)?.resourceFields?.includes('assetId')?{src:`/api/bedrock/workspaces/${encodeURIComponent(workspaceId)}/assets/${encodeURIComponent(node.data.assetId)}?variant=preview`}:{})}})),edges:value.edges.map(edge=>({...edge,selectable:false,focusable:false}))};
},[preview.document,canvasId,workspaceId,registry,catalog]); },[preview.document,canvasId,workspaceId,registry,catalog]);
// 普通rendererId优先使用专用preview,否则节点PreparingNode、边UnsupportedEdge;节点再套inert隔离内部控件。 // 普通rendererId优先使用专用preview,否则节点PreparingNode、边UnsupportedEdge;节点再套inert隔离内部控件。
const nodeTypes=useMemo<NodeTypes>(()=>{const result:NodeTypes={};for(const [id,Renderer]of Object.entries({...Object.fromEntries(Object.keys(renderers.nodeTypes).map(id=>[id,renderers.previewNodeTypes[id]??PreparingNode])),unsupported:UnsupportedNode}))result[id]=props=><div inert style={{width:'100%',height:'100%'}}><Renderer {...props}/></div>;return result;},[renderers]),edgeTypes=useMemo(()=>({...Object.fromEntries(Object.keys(renderers.edgeTypes).map(id=>[id,renderers.previewEdgeTypes[id]??UnsupportedEdge])),unsupported:UnsupportedEdge}),[renderers]); const nodeTypes=useMemo<NodeTypes>(()=>{const result:NodeTypes={};for(const [id,Renderer]of Object.entries({...Object.fromEntries(Object.keys(renderers.nodeTypes).map(id=>[id,renderers.previewNodeTypes[id]??PreparingNode])),unsupported:UnsupportedNode}))result[id]=props=><div inert style={{width:'100%',height:'100%'}}><Renderer {...props}/></div>;return result;},[renderers]),edgeTypes=useMemo(()=>({...Object.fromEntries(Object.keys(renderers.edgeTypes).map(id=>[id,renderers.previewEdgeTypes[id]??UnsupportedEdge])),unsupported:UnsupportedEdge}),[renderers]);
@@ -36,7 +36,7 @@ export function CanvasRuntimeHost({ children,extensions=[] }: { children: ReactN
/** 一项目一组协议适配器;summary策略只压缩已协调回执,不改变网络请求或原始操作身份。 */ /** 一项目一组协议适配器;summary策略只压缩已协调回执,不改变网络请求或原始操作身份。 */
adapters(rootId, current) { adapters(rootId, current) {
const transport = createFoundryTransport({ accountId, isCurrentIdentity: current }); const transport = createFoundryTransport({ accountId, isCurrentIdentity: current });
return { runs: createFoundryRuns({ workspaceId, rootId, registry, transport }), persistence: createFoundryPersistence({ workspaceId, rootId, registry, transport, resolvedReceiptPolicy:'summary' }), assets: createFoundryAssets({ workspaceId, transport, project: process.env.NEXT_PUBLIC_FOUNDRY_PROJECT || "endoleap", origin: process.env.NEXT_PUBLIC_FOUNDRY_API_ORIGIN }) }; return { runs: createFoundryRuns({ workspaceId, rootId, registry, transport }), persistence: createFoundryPersistence({ workspaceId, rootId, registry, transport, resolvedReceiptPolicy:'summary' }), assets: createFoundryAssets({ workspaceId, transport, project: process.env.NEXT_PUBLIC_BEDROCK_PROJECT || "endoleap", origin: process.env.NEXT_PUBLIC_BEDROCK_API_ORIGIN }) };
}, },
// 同工作区错误用稳定通知id更新,不创建另一份任务状态;错误恢复仍须runtime明确操作。 // 同工作区错误用稳定通知id更新,不创建另一份任务状态;错误恢复仍须runtime明确操作。
onError: error => notify({ id: `canvas-runtime:${accountId}:${workspaceId}`, title: "画布同步需要处理", description: errorText(error), level: "error" }), onError: error => notify({ id: `canvas-runtime:${accountId}:${workspaceId}`, title: "画布同步需要处理", description: errorText(error), level: "error" }),
+2 -2
View File
@@ -28,7 +28,7 @@ export async function api<T>(
options: RequestInit = {}, options: RequestInit = {},
): Promise<T> { ): Promise<T> {
// fetch 本身拒绝(网络失败/发出前取消)时原异常直接传播;下面的 ApiError 包装只覆盖响应读取与 HTTP 错误。 // fetch 本身拒绝(网络失败/发出前取消)时原异常直接传播;下面的 ApiError 包装只覆盖响应读取与 HTTP 错误。
const res = await fetch("/api/foundry/" + path, { const res = await fetch("/api/bedrock/" + path, {
...options, ...options,
// FormData让浏览器生成boundary,其它请求默认JSON;这里只展开 headers 的自有可枚举字段。 // FormData让浏览器生成boundary,其它请求默认JSON;这里只展开 headers 的自有可枚举字段。
// 普通对象可覆盖同名默认字段;Headers 实例/二元组数组不会在这里被规范化成对象键值。 // 普通对象可覆盖同名默认字段;Headers 实例/二元组数组不会在这里被规范化成对象键值。
@@ -55,7 +55,7 @@ export async function api<T>(
return body as T; return body as T;
} }
/** 公开项目标识,来自构建时NEXT_PUBLIC配置;不是密码或用户账户身份。 */ /** 公开项目标识,来自构建时NEXT_PUBLIC配置;不是密码或用户账户身份。 */
export const PROJECT = process.env.NEXT_PUBLIC_FOUNDRY_PROJECT || "endoleap"; export const PROJECT = process.env.NEXT_PUBLIC_BEDROCK_PROJECT || "endoleap";
/** 创建PKCE verifier和SHA-256 challenge:verifier留在当前标签页sessionStorage, /** 创建PKCE verifier和SHA-256 challenge:verifier留在当前标签页sessionStorage,
* 只把challenge带到同源OAuth入口,后续交换流程负责取回verifier。此处不直接取得令牌。 */ * 只把challenge带到同源OAuth入口,后续交换流程负责取回verifier。此处不直接取得令牌。 */
export async function startOAuth(provider: "google" | "slack") { export async function startOAuth(provider: "google" | "slack") {
+1 -1
View File
@@ -25,7 +25,7 @@ export async function uploadCanvasImage(request: Request, workspace: string, fil
if (!asset || typeof asset.url !== "string") throw new Error("invalid_asset_response"); if (!asset || typeof asset.url !== "string") throw new Error("invalid_asset_response");
let url: URL; let url: URL;
try { url = new URL(asset.url); } catch { throw new Error("invalid_asset_response"); } try { url = new URL(asset.url); } catch { throw new Error("invalid_asset_response"); }
if (!/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/i.test(asset.id) || url.origin !== "https://api.foundry.entroia.com" || url.pathname !== `/projects/${process.env.NEXT_PUBLIC_FOUNDRY_PROJECT || "endoleap"}/workspaces/${workspace}/assets/${asset.id}` || url.search || !Number.isFinite(asset.width) || asset.width < 1 || !Number.isFinite(asset.height) || asset.height < 1) throw new Error("invalid_asset_response"); if (!/^[a-f\d]{8}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{4}-[a-f\d]{12}$/i.test(asset.id) || url.origin !== "https://api.foundry.entroia.com" || url.pathname !== `/projects/${process.env.NEXT_PUBLIC_BEDROCK_PROJECT || "endoleap"}/workspaces/${workspace}/assets/${asset.id}` || url.search || !Number.isFinite(asset.width) || asset.width < 1 || !Number.isFinite(asset.height) || asset.height < 1) throw new Error("invalid_asset_response");
// bytes/mime_type 未在此逐项核验,URL hash/用户名密码也未另设拒绝条件;不能视为新版资源权威证明。 // bytes/mime_type 未在此逐项核验,URL hash/用户名密码也未另设拒绝条件;不能视为新版资源权威证明。
return asset; return asset;
} }
+1 -1
View File
@@ -88,7 +88,7 @@ export function createFoundryAssets(options: { workspaceId: Id; transport: Servi
* resolve 返回冻结元数据,read 返回原字节响应;不在此重新哈希/解码,权限身份与字节预算还依赖 transport 合同。 */ * resolve 返回冻结元数据,read 返回原字节响应;不在此重新哈希/解码,权限身份与字节预算还依赖 transport 合同。 */
const authority=Object.freeze({scope:`${origin.origin}/projects/${encodeURIComponent(options.project??'endoleap')}/${path}`,async resolve(id:Id,signal:AbortSignal){if(!uuid.test(id))throw fault('invalid_resource_id');const response=await options.transport({method:'GET',path:`${path}/metadata/${encodeURIComponent(id)}`,signal}),raw=object(response.body);if(response.status!==200)throw fault(typeof raw.error==='string'?raw.error:'asset_authorization_failed');if(raw.metadata_version!==1)throw fault('asset_metadata_interpreter_unavailable');const value={version:1 as const,authority:authority.scope,digest:raw.sha256 as string,asset:raw.asset as StoredAsset};validateSharedAsset(value);if(value.asset.id!==id||value.asset.url!==sourceURL(id))throw fault('asset_authorization_mismatch');return freeze(value);},async read(id:Id,signal:AbortSignal){if(!uuid.test(id))throw fault('invalid_resource_id');const response=await options.transport({method:'GET',path:`${path}/${encodeURIComponent(id)}`,signal,responseFormat:'asset-bytes-v1'});if(response.status!==200||!response.bytes)throw fault('asset_bytes_unavailable');return response.bytes;}}); const authority=Object.freeze({scope:`${origin.origin}/projects/${encodeURIComponent(options.project??'endoleap')}/${path}`,async resolve(id:Id,signal:AbortSignal){if(!uuid.test(id))throw fault('invalid_resource_id');const response=await options.transport({method:'GET',path:`${path}/metadata/${encodeURIComponent(id)}`,signal}),raw=object(response.body);if(response.status!==200)throw fault(typeof raw.error==='string'?raw.error:'asset_authorization_failed');if(raw.metadata_version!==1)throw fault('asset_metadata_interpreter_unavailable');const value={version:1 as const,authority:authority.scope,digest:raw.sha256 as string,asset:raw.asset as StoredAsset};validateSharedAsset(value);if(value.asset.id!==id||value.asset.url!==sourceURL(id))throw fault('asset_authorization_mismatch');return freeze(value);},async read(id:Id,signal:AbortSignal){if(!uuid.test(id))throw fault('invalid_resource_id');const response=await options.transport({method:'GET',path:`${path}/${encodeURIComponent(id)}`,signal,responseFormat:'asset-bytes-v1'});if(response.status!==200||!response.bytes)throw fault('asset_bytes_unavailable');return response.bytes;}});
// 默认显示地址走同源预览代理;upload/query只委托统一执行器,不复制另一套任务状态。 // 默认显示地址走同源预览代理;upload/query只委托统一执行器,不复制另一套任务状态。
return Object.freeze({ authority, sourceURL, displayURL: options.displayURL ?? ((id: Id) => `/api/foundry/${path}/${encodeURIComponent(id)}?variant=preview`), accept, return Object.freeze({ authority, sourceURL, displayURL: options.displayURL ?? ((id: Id) => `/api/bedrock/${path}/${encodeURIComponent(id)}?variant=preview`), accept,
upload: (request: FrozenRequest, bytes: Blob, signal: AbortSignal) => execute(request, bytes, signal), upload: (request: FrozenRequest, bytes: Blob, signal: AbortSignal) => execute(request, bytes, signal),
query: (request: FrozenRequest, signal: AbortSignal) => execute(request, undefined, signal), query: (request: FrozenRequest, signal: AbortSignal) => execute(request, undefined, signal),
}); });
+1 -1
View File
@@ -47,7 +47,7 @@ export function createFoundryTransport(options: { accountId: Id; isCurrentIdenti
if (!options.isCurrentIdentity()) throw fault('identity_changed'); if (!options.isCurrentIdentity()) throw fault('identity_changed');
if (input.expectedVersion !== undefined && (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)) throw fault('invalid_server_version'); if (input.expectedVersion !== undefined && (!Number.isSafeInteger(input.expectedVersion) || input.expectedVersion < 1)) throw fault('invalid_server_version');
// 禁止缓存和重定向,按表示设置 Accept;FormData 的 boundary 交给浏览器,不能强写 JSON Content-Type。 // 禁止缓存和重定向,按表示设置 Accept;FormData 的 boundary 交给浏览器,不能强写 JSON Content-Type。
const response = await requestFetch(`${options.basePath ?? '/api/foundry/'}${input.path}`, { method: input.method, body: input.body, signal: input.signal, credentials: 'same-origin', cache: 'no-store', redirect: 'error', headers: { const response = await requestFetch(`${options.basePath ?? '/api/bedrock/'}${input.path}`, { method: input.method, body: input.body, signal: input.signal, credentials: 'same-origin', cache: 'no-store', redirect: 'error', headers: {
Accept: input.responseFormat==='canvas-v2'?'application/vnd.foundry.canvas+json;version=2':input.responseFormat==='model-stream-v1'?modelStreamType:input.responseFormat==='asset-bytes-v1'?'image/*':'application/json', ...(input.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }), ...(input.resourceId ? { 'X-Resource-Id': input.resourceId } : {}), 'X-Expected-Account': options.accountId, ...(input.requestId ? { 'Idempotency-Key': input.requestId } : {}), ...(input.expectedVersion !== undefined ? { 'If-Match': `"${input.expectedVersion}"` } : {}), Accept: input.responseFormat==='canvas-v2'?'application/vnd.foundry.canvas+json;version=2':input.responseFormat==='model-stream-v1'?modelStreamType:input.responseFormat==='asset-bytes-v1'?'image/*':'application/json', ...(input.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }), ...(input.resourceId ? { 'X-Resource-Id': input.resourceId } : {}), 'X-Expected-Account': options.accountId, ...(input.requestId ? { 'Idempotency-Key': input.requestId } : {}), ...(input.expectedVersion !== undefined ? { 'If-Match': `"${input.expectedVersion}"` } : {}),
} }); } });
if (!options.isCurrentIdentity()) { await response.body?.cancel(); throw fault('identity_changed'); } if (!options.isCurrentIdentity()) { await response.body?.cancel(); throw fault('identity_changed'); }
+2 -2
View File
@@ -101,9 +101,9 @@ export function decodeNodeExtensions(data: Record<string, unknown>, schema: numb
* 内联、demo或其它地址原样返回,不把任意HTTPS资源都伪装成受管资源。 */ * 内联、demo或其它地址原样返回,不把任意HTTPS资源都伪装成受管资源。 */
export function managedImageSource(src?: string, preview = false) { export function managedImageSource(src?: string, preview = false) {
if (!src) return src; if (!src) return src;
// 此兼容路径固定项目名 endoleap,不读取 NEXT_PUBLIC_FOUNDRY_PROJECT;命中后舍弃原查询/片段。 // 此兼容路径固定项目名 endoleap,不读取 NEXT_PUBLIC_BEDROCK_PROJECT;命中后舍弃原查询/片段。
try { const url = new URL(src); const match = url.pathname.match(/^\/projects\/endoleap\/(workspaces\/[A-Za-z0-9_-]+\/assets\/[A-Za-z0-9_-]+)$/); try { const url = new URL(src); const match = url.pathname.match(/^\/projects\/endoleap\/(workspaces\/[A-Za-z0-9_-]+\/assets\/[A-Za-z0-9_-]+)$/);
if (url.origin === "https://api.foundry.entroia.com" && match) return "/api/foundry/" + match[1] + (preview ? "?variant=preview" : ""); if (url.origin === "https://api.foundry.entroia.com" && match) return "/api/bedrock/" + match[1] + (preview ? "?variant=preview" : "");
} catch { /* inline and demo images are already browser-readable */ } } catch { /* inline and demo images are already browser-readable */ }
return src; return src;
} }
+32 -32
View File
@@ -132,7 +132,7 @@ const app = spawn(
], ],
{ {
cwd: fileURLToPath(new URL("../", import.meta.url)), cwd: fileURLToPath(new URL("../", import.meta.url)),
env: { ...process.env, FOUNDRY_API_ORIGIN: "http://127.0.0.1:" + port }, env: { ...process.env, BEDROCK_API_ORIGIN: "http://127.0.0.1:" + port },
stdio: ["ignore", "pipe", "pipe"], stdio: ["ignore", "pipe", "pipe"],
}, },
); );
@@ -188,7 +188,7 @@ try {
} }
assert.equal((await fetch(host + "/missing-page")).status, 404); assert.equal((await fetch(host + "/missing-page")).status, 404);
// 登录代理必须去掉响应体 token,改设 HttpOnly/SameSite cookie,并报告上游计时。 // 登录代理必须去掉响应体 token,改设 HttpOnly/SameSite cookie,并报告上游计时。
const res = await fetch(host + "/api/foundry/auth/login", { const res = await fetch(host + "/api/bedrock/auth/login", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json", Origin: host }, headers: { "Content-Type": "application/json", Origin: host },
body: "{}", body: "{}",
@@ -207,7 +207,7 @@ try {
// 2500ms 的 Promise.race 只限制 fetch 返回响应头,后面的 reader.read 不在该 deadline 内,不能据此声称首块也受同一计时约束。 // 2500ms 的 Promise.race 只限制 fetch 返回响应头,后面的 reader.read 不在该 deadline 内,不能据此声称首块也受同一计时约束。
let streamTimer; let streamTimer;
try { try {
const streamed = await Promise.race([fetch(host + "/api/foundry/workspaces/space/materials/stream-board/canvas", { headers: { Cookie: session } }), new Promise((_, reject) => { streamTimer = setTimeout(() => reject(new Error("Snapshot proxy buffered the body")), 2500); })]); const streamed = await Promise.race([fetch(host + "/api/bedrock/workspaces/space/materials/stream-board/canvas", { headers: { Cookie: session } }), new Promise((_, reject) => { streamTimer = setTimeout(() => reject(new Error("Snapshot proxy buffered the body")), 2500); })]);
assert.equal(streamed.headers.get("etag"), '\"1\"'); assert.equal(streamed.headers.get("x-canvas-schema-version"), "2"); assert.equal(streamed.headers.get("etag"), '\"1\"'); assert.equal(streamed.headers.get("x-canvas-schema-version"), "2");
assert.match(streamed.headers.get("server-timing"), /upstream;dur=.*proxy_headers;dur=/); assert.match(streamed.headers.get("server-timing"), /upstream;dur=.*proxy_headers;dur=/);
assert.ok(streamed.headers.get("set-cookie")?.includes("HttpOnly")); assert.ok(streamed.headers.get("set-cookie")?.includes("HttpOnly"));
@@ -217,27 +217,27 @@ try {
assert.equal(JSON.parse(raw).document.schema_version, 2); assert.equal(JSON.parse(raw).document.schema_version, 2);
} finally { clearTimeout(streamTimer); releaseStream(); } } finally { clearTimeout(streamTimer); releaseStream(); }
// 子命令循环只检查头透传;随后检查资源 variant、目录分页与 AI 查询参数白名单。 // 子命令循环只检查头透传;随后检查资源 variant、目录分页与 AI 查询参数白名单。
const v2Base = host + "/api/foundry/workspaces/space/materials/foundry-generated-id/canvas"; const v2Base = host + "/api/bedrock/workspaces/space/materials/foundry-generated-id/canvas";
const idem = "11111111-1111-4111-8111-111111111111"; const idem = "11111111-1111-4111-8111-111111111111";
for (const path of ["connections", "subgraphs", "subgraphs/migrate", "subgraphs/frame-1/members", "subgraphs/frame-1/dissolve", "transactions/tx-1/undo", "ai/runs", "ai/runs/run-1/cancel", "ai/runs/run-1/apply"]) { for (const path of ["connections", "subgraphs", "subgraphs/migrate", "subgraphs/frame-1/members", "subgraphs/frame-1/dissolve", "transactions/tx-1/undo", "ai/runs", "ai/runs/run-1/cancel", "ai/runs/run-1/apply"]) {
const response = await fetch(v2Base + "/" + path, { method: "POST", headers: { Cookie: session, Origin: host, "Content-Type": "application/json", "Idempotency-Key": idem, "If-Match": '\"7\"' }, body: "{}" }); const response = await fetch(v2Base + "/" + path, { method: "POST", headers: { Cookie: session, Origin: host, "Content-Type": "application/json", "Idempotency-Key": idem, "If-Match": '\"7\"' }, body: "{}" });
assert.equal(response.status, 200, path); const echo = await response.json(); assert.equal(echo.key, idem); assert.equal(echo.version, '\"7\"'); assert.equal(echo.accept, "application/vnd.foundry.canvas+json;version=2"); assert.equal(response.status, 200, path); const echo = await response.json(); assert.equal(echo.key, idem); assert.equal(echo.version, '\"7\"'); assert.equal(echo.accept, "application/vnd.foundry.canvas+json;version=2");
} }
const preview = await fetch(host + "/api/foundry/workspaces/space/assets/image?variant=preview", { headers: { Cookie: session } });assert.equal(preview.status,200);assert.equal(preview.headers.get("x-asset-variant"),"preview");await preview.arrayBuffer(); const preview = await fetch(host + "/api/bedrock/workspaces/space/assets/image?variant=preview", { headers: { Cookie: session } });assert.equal(preview.status,200);assert.equal(preview.headers.get("x-asset-variant"),"preview");await preview.arrayBuffer();
const directoryResponse = await (await fetch(host + "/api/foundry/workspaces/space/materials?kind=board&sort=modified&include_subgraphs=true&limit=100&offset=100", { headers: { Cookie: session } })).json(); const directoryResponse = await (await fetch(host + "/api/bedrock/workspaces/space/materials?kind=board&sort=modified&include_subgraphs=true&limit=100&offset=100", { headers: { Cookie: session } })).json();
const directoryQuery = new URL(directoryResponse.url, "http://mock").searchParams; const directoryQuery = new URL(directoryResponse.url, "http://mock").searchParams;
assert.equal(directoryQuery.get("include_subgraphs"), "true"); assert.equal(directoryQuery.get("offset"), "100"); assert.equal(directoryQuery.get("include_subgraphs"), "true"); assert.equal(directoryQuery.get("offset"), "100");
const events = await (await fetch(v2Base + "/ai/runs/run-1?after_seq=12&limit=100&status=active&include_descendants=true&cursor=cursor&secret=drop", { headers: { Cookie: session } })).json(); const events = await (await fetch(v2Base + "/ai/runs/run-1?after_seq=12&limit=100&status=active&include_descendants=true&cursor=cursor&secret=drop", { headers: { Cookie: session } })).json();
const query = new URL(events.url, "http://mock").searchParams; assert.equal(query.get("after_seq"), "12"); assert.equal(query.get("include_descendants"), "true"); assert.equal(query.get("cursor"), "cursor"); assert.equal(query.get("secret"), null); const query = new URL(events.url, "http://mock").searchParams; assert.equal(query.get("after_seq"), "12"); assert.equal(query.get("include_descendants"), "true"); assert.equal(query.get("cursor"), "cursor"); assert.equal(query.get("secret"), null);
// 验证慢 body 完整读取和 trace 标识,再检查资源认证、MIME 拒绝、nosniff 与 multipart 转发。 // 验证慢 body 完整读取和 trace 标识,再检查资源认证、MIME 拒绝、nosniff 与 multipart 转发。
const slowSnapshot = await fetch(host + "/api/foundry/workspaces/space/materials/slow-body-board/canvas", { headers: { Cookie: session } }); const slowSnapshot = await fetch(host + "/api/bedrock/workspaces/space/materials/slow-body-board/canvas", { headers: { Cookie: session } });
assert.ok(slowSnapshot.headers.get("x-canvas-trace-id")); assert.equal((await slowSnapshot.json()).version, 210, "A valid body can finish after the old 15-second total deadline"); assert.ok(slowSnapshot.headers.get("x-canvas-trace-id")); assert.equal((await slowSnapshot.json()).version, 210, "A valid body can finish after the old 15-second total deadline");
const asset = await fetch(host + "/api/foundry/workspaces/space/assets/image-1", { headers: { Cookie: session } }); const asset = await fetch(host + "/api/bedrock/workspaces/space/assets/image-1", { headers: { Cookie: session } });
assert.equal(asset.status, 200); assert.equal(asset.headers.get("content-type"), "image/png"); assert.equal(asset.headers.get("x-content-type-options"), "nosniff"); assert.ok(asset.headers.get("set-cookie")?.includes("HttpOnly")); assert.equal((await asset.arrayBuffer()).byteLength, 8); assert.equal(asset.status, 200); assert.equal(asset.headers.get("content-type"), "image/png"); assert.equal(asset.headers.get("x-content-type-options"), "nosniff"); assert.ok(asset.headers.get("set-cookie")?.includes("HttpOnly")); assert.equal((await asset.arrayBuffer()).byteLength, 8);
assert.equal((await fetch(host + "/api/foundry/workspaces/space/assets/image-1")).status, 401); assert.equal((await fetch(host + "/api/bedrock/workspaces/space/assets/image-1")).status, 401);
assert.equal((await fetch(host + "/api/foundry/workspaces/space/assets/bad", { headers: { Cookie: session } })).status, 502); assert.equal((await fetch(host + "/api/bedrock/workspaces/space/assets/bad", { headers: { Cookie: session } })).status, 502);
const form = new FormData(); form.set("image", new Blob([new Uint8Array([137,80,78,71])], { type: "image/png" }), "test.png"); const form = new FormData(); form.set("image", new Blob([new Uint8Array([137,80,78,71])], { type: "image/png" }), "test.png");
const upload = await (await fetch(host + "/api/foundry/workspaces/space/assets", { method: "POST", headers: { Cookie: session, Origin: host, "Idempotency-Key": idem }, body: form })).json(); const upload = await (await fetch(host + "/api/bedrock/workspaces/space/assets", { method: "POST", headers: { Cookie: session, Origin: host, "Idempotency-Key": idem }, body: form })).json();
// 这里只核对 multipart Content-Type、image 字段标记及幂等键;未解析 multipart,也未逐字节比较上传文件内容。 // 这里只核对 multipart Content-Type、image 字段标记及幂等键;未解析 multipart,也未逐字节比较上传文件内容。
assert.match(upload.type, /^multipart\/form-data; boundary=/); assert.equal(upload.key, idem); assert.ok(upload.multipart); assert.match(upload.type, /^multipart\/form-data; boundary=/); assert.equal(upload.key, idem); assert.ok(upload.multipart);
// 有效会话首页重定向且不缓存私有结果;dashboard 初始 HTML 不应包含画布或 landing。 // 有效会话首页重定向且不缓存私有结果;dashboard 初始 HTML 不应包含画布或 landing。
@@ -264,29 +264,29 @@ try {
assert.equal( assert.equal(
( (
await fetch(host + "/api/foundry/profile", { await fetch(host + "/api/bedrock/profile", {
headers: { Cookie: session }, headers: { Cookie: session },
}) })
).status, ).status,
200, 200,
); );
assert.equal((await fetch(host + "/api/foundry/profile")).status, 401); assert.equal((await fetch(host + "/api/bedrock/profile")).status, 401);
// 续期只接受有效剩余秒数;非法上游值和无效会话不应产生新的 Set-Cookie。 // 续期只接受有效剩余秒数;非法上游值和无效会话不应产生新的 Set-Cookie。
mockSessionSeconds = "3600"; mockSessionSeconds = "3600";
const renewed = await fetch(host + "/api/foundry/profile", { headers: { Cookie: session } }); const renewed = await fetch(host + "/api/bedrock/profile", { headers: { Cookie: session } });
assert.equal(renewed.status, 200); assert.match(renewed.headers.get("set-cookie") || "", /Max-Age=3600/); assert.equal(renewed.status, 200); assert.match(renewed.headers.get("set-cookie") || "", /Max-Age=3600/);
assert.match(renewed.headers.get("set-cookie") || "", /HttpOnly/); assert.match(renewed.headers.get("set-cookie") || "", /HttpOnly/);
mockSessionSeconds = "garbage"; mockSessionSeconds = "garbage";
const malformedRenewal = await fetch(host + "/api/foundry/profile", { headers: { Cookie: session } }); const malformedRenewal = await fetch(host + "/api/bedrock/profile", { headers: { Cookie: session } });
assert.equal(malformedRenewal.headers.get("set-cookie"), null); assert.equal(malformedRenewal.headers.get("set-cookie"), null);
mockSessionSeconds = "2592000"; mockSessionSeconds = "2592000";
const expiredSession = await fetch(host + "/api/foundry/profile", { headers: { Cookie: "foundry_session=expired" } }); const expiredSession = await fetch(host + "/api/bedrock/profile", { headers: { Cookie: "foundry_session=expired" } });
assert.equal(expiredSession.status, 401); assert.equal(expiredSession.headers.get("set-cookie"), null); assert.equal(expiredSession.status, 401); assert.equal(expiredSession.headers.get("set-cookie"), null);
// 读取头像再修改公开资料,确认未涉及的头像字段保持。 // 读取头像再修改公开资料,确认未涉及的头像字段保持。
const profile = await (await fetch(host + "/api/foundry/profile", { headers: { Cookie: session } })).json(); const profile = await (await fetch(host + "/api/bedrock/profile", { headers: { Cookie: session } })).json();
assert.equal(profile.avatar_url, "https://lh3.googleusercontent.com/test-avatar=s96-c"); assert.equal(profile.avatar_url, "https://lh3.googleusercontent.com/test-avatar=s96-c");
const updated = await fetch(host + "/api/foundry/profile", { const updated = await fetch(host + "/api/bedrock/profile", {
method: "PATCH", method: "PATCH",
headers: { "Content-Type": "application/json", Cookie: session, Origin: host }, headers: { "Content-Type": "application/json", Cookie: session, Origin: host },
body: JSON.stringify({ username: "test", display_name: "Updated name" }), body: JSON.stringify({ username: "test", display_name: "Updated name" }),
@@ -297,7 +297,7 @@ try {
assert.equal(updatedProfile.avatar_url, profile.avatar_url); assert.equal(updatedProfile.avatar_url, profile.avatar_url);
// 经真实代理创建、读取和重命名内存图谱,检查服务分配身份、内容保留和元信息版本递增。 // 经真实代理创建、读取和重命名内存图谱,检查服务分配身份、内容保留和元信息版本递增。
const create = await fetch(host + "/api/foundry/workspaces/space/materials", { const create = await fetch(host + "/api/bedrock/workspaces/space/materials", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json", Cookie: session, Origin: host }, headers: { "Content-Type": "application/json", Cookie: session, Origin: host },
body: JSON.stringify({ kind: "board", title: "未命名图谱", content: { schema_version: 1 } }), body: JSON.stringify({ kind: "board", title: "未命名图谱", content: { schema_version: 1 } }),
@@ -305,18 +305,18 @@ try {
assert.equal(create.status, 201); assert.equal(create.status, 201);
const graph = await create.json(); const graph = await create.json();
assert.deepEqual(graph, { id: "foundry-generated-id", workspace_id: "space", kind: "board", version: 1 }); assert.deepEqual(graph, { id: "foundry-generated-id", workspace_id: "space", kind: "board", version: 1 });
const opened = await fetch(host + `/api/foundry/workspaces/${graph.workspace_id}/materials/${graph.id}`, { headers: { Cookie: session } }); const opened = await fetch(host + `/api/bedrock/workspaces/${graph.workspace_id}/materials/${graph.id}`, { headers: { Cookie: session } });
assert.equal(opened.status, 200); assert.equal(opened.status, 200);
const stored = await opened.json(); const stored = await opened.json();
assert.equal(stored.title, "未命名图谱"); assert.equal(stored.title, "未命名图谱");
assert.equal(stored.workspace_id, "space"); assert.equal(stored.workspace_id, "space");
assert.equal(stored.content.schema_version, 1); assert.equal(stored.content.schema_version, 1);
const rename = await fetch(host + `/api/foundry/workspaces/${graph.workspace_id}/materials/${graph.id}`, { const rename = await fetch(host + `/api/bedrock/workspaces/${graph.workspace_id}/materials/${graph.id}`, {
method: "PATCH", headers: { "Content-Type": "application/json", Cookie: session, Origin: host, "If-Match": '"1"' }, method: "PATCH", headers: { "Content-Type": "application/json", Cookie: session, Origin: host, "If-Match": '"1"' },
body: JSON.stringify({ title: "改名后的图谱", description: "", content: stored.content }), body: JSON.stringify({ title: "改名后的图谱", description: "", content: stored.content }),
}); });
assert.equal(rename.status, 204); assert.equal(rename.status, 204);
const renamed = await (await fetch(host + `/api/foundry/workspaces/${graph.workspace_id}/materials/${graph.id}`, { headers: { Cookie: session } })).json(); const renamed = await (await fetch(host + `/api/bedrock/workspaces/${graph.workspace_id}/materials/${graph.id}`, { headers: { Cookie: session } })).json();
assert.equal(renamed.title, "改名后的图谱"); assert.equal(renamed.title, "改名后的图谱");
assert.equal(renamed.version, 2); assert.equal(renamed.version, 2);
assert.deepEqual(renamed.content, stored.content); assert.deepEqual(renamed.content, stored.content);
@@ -324,14 +324,14 @@ try {
// workspace/board 各自使用 ID 或 slug 的四种组合都应定位同一图谱和独立画布版本。 // workspace/board 各自使用 ID 或 slug 的四种组合都应定位同一图谱和独立画布版本。
// 替身通过 canonical 字符串替换提供该映射;此处验证代理接受四种路径,不验证真实 Foundry 的 slug 解析实现。 // 替身通过 canonical 字符串替换提供该映射;此处验证代理接受四种路径,不验证真实 Foundry 的 slug 解析实现。
for (const workspace of ["space", "creative-space"]) for (const board of ["foundry-generated-id", "my-board"]) { for (const workspace of ["space", "creative-space"]) for (const board of ["foundry-generated-id", "my-board"]) {
const path = `/api/foundry/workspaces/${workspace}/materials/${board}`; const path = `/api/bedrock/workspaces/${workspace}/materials/${board}`;
const material = await (await fetch(host + path, { headers: { Cookie: session } })).json(); const material = await (await fetch(host + path, { headers: { Cookie: session } })).json();
assert.equal(material.id, "foundry-generated-id"); assert.equal(material.slug, "my-board"); assert.equal(material.id, "foundry-generated-id"); assert.equal(material.slug, "my-board");
const snapshot = await fetch(host + path + "/canvas", { headers: { Cookie: session } }); const snapshot = await fetch(host + path + "/canvas", { headers: { Cookie: session } });
assert.equal(snapshot.status, 200); assert.equal(snapshot.headers.get("etag"), '"1"'); assert.equal(snapshot.status, 200); assert.equal(snapshot.headers.get("etag"), '"1"');
assert.equal((await snapshot.json()).version, 1); assert.equal((await snapshot.json()).version, 1);
} }
const canvasPath = "/api/foundry/workspaces/creative-space/materials/my-board/canvas"; const canvasPath = "/api/bedrock/workspaces/creative-space/materials/my-board/canvas";
// 生成超过 1 MiB 的完整快照经代理保存/恢复,再用旧版本重发检查 412;不是增量或大文件性能测试。 // 生成超过 1 MiB 的完整快照经代理保存/恢复,再用旧版本重发检查 412;不是增量或大文件性能测试。
const largeDocument = { schema_version: 1, nodes: Array.from({ length: 15 }, (_, index) => ({ id: "text-" + index, type: "material", position: { x: index * 300, y: 100 }, width: 260, height: 200, data: { kind: "text", title: "保存测试", text: "x".repeat(90000), fontSize: 24, rotation: 30, textStyle: { bold: true, color: "#123456" } } })), edges: [], viewport: { x: 20, y: 40, zoom: 0.75 } }; const largeDocument = { schema_version: 1, nodes: Array.from({ length: 15 }, (_, index) => ({ id: "text-" + index, type: "material", position: { x: index * 300, y: 100 }, width: 260, height: 200, data: { kind: "text", title: "保存测试", text: "x".repeat(90000), fontSize: 24, rotation: 30, textStyle: { bold: true, color: "#123456" } } })), edges: [], viewport: { x: 20, y: 40, zoom: 0.75 } };
const savedCanvas = await fetch(host + canvasPath, { method: "PATCH", headers: { Cookie: session, Origin: host, "Content-Type": "application/json", "If-Match": '"1"' }, body: JSON.stringify({ document: largeDocument }) }); const savedCanvas = await fetch(host + canvasPath, { method: "PATCH", headers: { Cookie: session, Origin: host, "Content-Type": "application/json", "If-Match": '"1"' }, body: JSON.stringify({ document: largeDocument }) });
@@ -354,7 +354,7 @@ try {
assert.equal(restored.document.nodes[1].data.frameId, "frame-1"); assert.equal(restored.document.nodes[1].data.frameId, "frame-1");
} }
assert.equal((await fetch(host + canvasPath)).status, 401); assert.equal((await fetch(host + canvasPath)).status, 401);
assert.equal((await fetch(host + "/api/foundry/workspaces/space/search/my-board/canvas")).status, 404); assert.equal((await fetch(host + "/api/bedrock/workspaces/space/search/my-board/canvas")).status, 404);
// 超过画布 body 上限的请求必须返回 413,不能转成成功保存。 // 超过画布 body 上限的请求必须返回 413,不能转成成功保存。
const oversizedCanvas = await fetch(host + canvasPath, { method: "PATCH", headers: { Cookie: session, "Content-Type": "application/json" }, body: JSON.stringify({ document: "x".repeat(5 * 1024 * 1024) }) }); const oversizedCanvas = await fetch(host + canvasPath, { method: "PATCH", headers: { Cookie: session, "Content-Type": "application/json" }, body: JSON.stringify({ document: "x".repeat(5 * 1024 * 1024) }) });
assert.equal(oversizedCanvas.status, 413); assert.equal(oversizedCanvas.status, 413);
@@ -364,7 +364,7 @@ try {
for (const origin of ["https://example.com", "null"]) for (const origin of ["https://example.com", "null"])
assert.equal( assert.equal(
( (
await fetch(host + "/api/foundry/auth/login", { await fetch(host + "/api/bedrock/auth/login", {
method: "POST", method: "POST",
headers: { Origin: origin, "Content-Type": "application/json" }, headers: { Origin: origin, "Content-Type": "application/json" },
body: "{}", body: "{}",
@@ -372,27 +372,27 @@ try {
).status, ).status,
403, 403,
); );
assert.equal((await fetch(host + "/api/foundry/unlisted")).status, 404); assert.equal((await fetch(host + "/api/bedrock/unlisted")).status, 404);
assert.equal( assert.equal(
(await fetch(host + "/api/oauth/slack?challenge=bad")).status, (await fetch(host + "/api/oauth/slack?challenge=bad")).status,
400, 400,
); );
assert.equal(res.headers.get("cache-control"), "no-store"); assert.equal(res.headers.get("cache-control"), "no-store");
const secure = await fetch(host + "/api/foundry/auth/login", { const secure = await fetch(host + "/api/bedrock/auth/login", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json", "X-Forwarded-Proto": "https" }, headers: { "Content-Type": "application/json", "X-Forwarded-Proto": "https" },
body: "{}", body: "{}",
}); });
assert.match(secure.headers.get("set-cookie"), /; Secure/); assert.match(secure.headers.get("set-cookie"), /; Secure/);
for (const [body, status] of [["{", 400], [JSON.stringify({ text: "x".repeat(1024 * 1024) }), 413]]) { for (const [body, status] of [["{", 400], [JSON.stringify({ text: "x".repeat(1024 * 1024) }), 413]]) {
const invalid = await fetch(host + "/api/foundry/auth/login", { const invalid = await fetch(host + "/api/bedrock/auth/login", {
method: "POST", headers: { "Content-Type": "application/json" }, body, method: "POST", headers: { "Content-Type": "application/json" }, body,
}); });
assert.equal(invalid.status, status); assert.equal(invalid.status, status);
} }
assert.equal((await fetch(host + "/api/foundry/profile", { method: "PUT" })).status, 405); assert.equal((await fetch(host + "/api/bedrock/profile", { method: "PUT" })).status, 405);
// 查询保留 kind/limit 而删除未许可 secret;此处使用替身回显观察最终上游路径。 // 查询保留 kind/limit 而删除未许可 secret;此处使用替身回显观察最终上游路径。
const materials = await fetch(host + "/api/foundry/workspaces/space/materials?kind=board&limit=100&secret=drop", { const materials = await fetch(host + "/api/bedrock/workspaces/space/materials?kind=board&limit=100&secret=drop", {
method: "PATCH", headers: { "Content-Type": "application/json" }, body: "{}", method: "PATCH", headers: { "Content-Type": "application/json" }, body: "{}",
}); });
assert.deepEqual(await materials.json(), { assert.deepEqual(await materials.json(), {
@@ -405,7 +405,7 @@ try {
assert.equal(redirect.headers.get("location"), `http://127.0.0.1:${port}/projects/endoleap/auth/${provider}?challenge=${"a".repeat(43)}`); assert.equal(redirect.headers.get("location"), `http://127.0.0.1:${port}/projects/endoleap/auth/${provider}?challenge=${"a".repeat(43)}`);
} }
// 登出保持 204 空体并清除 cookie;下方 PASS 长文是摘要,实际覆盖以逐项断言为准。 // 登出保持 204 空体并清除 cookie;下方 PASS 长文是摘要,实际覆盖以逐项断言为准。
const logout = await fetch(host + "/api/foundry/auth/logout", { const logout = await fetch(host + "/api/bedrock/auth/logout", {
method: "POST", headers: { "Content-Type": "application/json", Cookie: session }, body: "{}", method: "POST", headers: { "Content-Type": "application/json", Cookie: session }, body: "{}",
}); });
assert.equal(logout.status, 204); assert.equal(logout.status, 204);
+1 -1
View File
@@ -35,6 +35,6 @@ test('uncertain upload retries the exact bytes with the same idempotency key',as
// 受管原始 URL 转同源认证代理,preview 仅加显示变体参数;普通外部图片地址保持原样。 // 受管原始 URL 转同源认证代理,preview 仅加显示变体参数;普通外部图片地址保持原样。
// 这里仅比对字符串,不请求代理,也不验证登录鉴权或预览图片内容。 // 这里仅比对字符串,不请求代理,也不验证登录鉴权或预览图片内容。
test('preview URLs are renderer-only and do not replace original managed references',()=>{ test('preview URLs are renderer-only and do not replace original managed references',()=>{
assert.equal(managedImageSource(asset.url),`/api/foundry/workspaces/w/assets/${id}`);assert.equal(managedImageSource(asset.url,true),`/api/foundry/workspaces/w/assets/${id}?variant=preview`); assert.equal(managedImageSource(asset.url),`/api/bedrock/workspaces/w/assets/${id}`);assert.equal(managedImageSource(asset.url,true),`/api/bedrock/workspaces/w/assets/${id}?variant=preview`);
assert.equal(managedImageSource('https://example.com/photo.png',true),'https://example.com/photo.png'); assert.equal(managedImageSource('https://example.com/photo.png',true),'https://example.com/photo.png');
}); });
+1 -1
View File
@@ -55,7 +55,7 @@ globalThis.ResizeObserver = window.ResizeObserver = class {
let apiMock = null; let apiMock = null;
const requests = []; const requests = [];
globalThis.fetch = async (url, options) => { globalThis.fetch = async (url, options) => {
if (apiMock && String(url).startsWith("/api/foundry/")) return apiMock(url, options); if (apiMock && String(url).startsWith("/api/bedrock/")) return apiMock(url, options);
requests.push(String(url)); requests.push(String(url));
assert.ok(String(url).startsWith("/canvas-icons/"), `Unexpected network request ${url}`); assert.ok(String(url).startsWith("/canvas-icons/"), `Unexpected network request ${url}`);
if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError"); if (options?.signal?.aborted) throw new DOMException("Aborted", "AbortError");
+1 -1
View File
@@ -168,7 +168,7 @@ export async function canvasV2Scenario({root,act,h,GraphCanvas,window,makeCanvas
assert.ok(document.querySelector('[aria-label="AI 模型"]').textContent.includes('测试图片模型'),'Sticky AI mode selects models for the newly selected image'); assert.ok(document.querySelector('[aria-label="AI 模型"]').textContent.includes('测试图片模型'),'Sticky AI mode selects models for the newly selected image');
assert.ok(!document.querySelector('[aria-label="AI 模型"]').textContent.includes('测试文本模型')); assert.ok(!document.querySelector('[aria-label="AI 模型"]').textContent.includes('测试文本模型'));
await event(document.querySelector('[aria-label="执行 AI"]'),'click'); await event(document.querySelector('[aria-label="执行 AI"]'),'click');
await waitUntil(()=>document.querySelector('.react-flow__node[data-id="image-target"] img')?.getAttribute('src')==='/api/foundry/workspaces/w/assets/generated-image?variant=preview','managed AI image result'); await waitUntil(()=>document.querySelector('.react-flow__node[data-id="image-target"] img')?.getAttribute('src')==='/api/bedrock/workspaces/w/assets/generated-image?variant=preview','managed AI image result');
const generated=records.get(parent).document.nodes.find(node=>node.id==='image-target');assert.equal(generated.width,image.width);assert.equal(generated.height,image.height);assert.equal(generated.data.title,'图片目标'); const generated=records.get(parent).document.nodes.find(node=>node.id==='image-target');assert.equal(generated.width,image.width);assert.equal(generated.height,image.height);assert.equal(generated.data.title,'图片目标');
await waitUntil(()=>document.querySelector('[aria-label="执行 AI"]'),'image run terminal UI'); await waitUntil(()=>document.querySelector('[aria-label="执行 AI"]'),'image run terminal UI');
await event(document.querySelector('[aria-label="执行 AI"]'),'click'); await event(document.querySelector('[aria-label="执行 AI"]'),'click');
+1 -1
View File
@@ -70,7 +70,7 @@ test('eight-direction resize is free by default in resize mode and Shift locks t
}); });
// 受管资产显示转认证同源代理,普通外部 URL 保留;这里只检查地址转换,不验证实际认证请求。 // 受管资产显示转认证同源代理,普通外部 URL 保留;这里只检查地址转换,不验证实际认证请求。
test('managed assets render through the authenticated same-origin proxy',()=>{ test('managed assets render through the authenticated same-origin proxy',()=>{
assert.equal(managedImageSource('https://api.foundry.entroia.com/projects/endoleap/workspaces/w/assets/a'),'/api/foundry/workspaces/w/assets/a');assert.equal(managedImageSource('https://example.com/a.png'),'https://example.com/a.png'); assert.equal(managedImageSource('https://api.foundry.entroia.com/projects/endoleap/workspaces/w/assets/a'),'/api/bedrock/workspaces/w/assets/a');assert.equal(managedImageSource('https://example.com/a.png'),'https://example.com/a.png');
}); });
// 连线持久 owner 是最低共同祖先,事务参与者恰为两条 owner 路径的并集;祖先本身不需要重复登记。 // 连线持久 owner 是最低共同祖先,事务参与者恰为两条 owner 路径的并集;祖先本身不需要重复登记。
+1 -1
View File
@@ -41,7 +41,7 @@ test('asset adapter preserves byte identity and headers and validates the scoped
test('a headless host supplies display URLs without changing canonical asset identity or authority',async()=>{ test('a headless host supplies display URLs without changing canonical asset identity or authority',async()=>{
const options={workspaceId:id(4),transport:async()=>{throw Error('display routing must not make a request');}}; const options={workspaceId:id(4),transport:async()=>{throw Error('display routing must not make a request');}};
const browser=createFoundryAssets(options),host=createFoundryAssets({...options,displayURL:asset=>`https://host.example/preview/${encodeURIComponent(asset)}`}); const browser=createFoundryAssets(options),host=createFoundryAssets({...options,displayURL:asset=>`https://host.example/preview/${encodeURIComponent(asset)}`});
assert.equal(browser.displayURL(id(1)),`/api/foundry/workspaces/${id(4)}/assets/${id(1)}?variant=preview`); assert.equal(browser.displayURL(id(1)),`/api/bedrock/workspaces/${id(4)}/assets/${id(1)}?variant=preview`);
assert.equal(host.displayURL(id(1)),`https://host.example/preview/${id(1)}`); assert.equal(host.displayURL(id(1)),`https://host.example/preview/${id(1)}`);
assert.equal(host.sourceURL(id(1)),browser.sourceURL(id(1)));assert.equal(host.authority.scope,browser.authority.scope); assert.equal(host.sourceURL(id(1)),browser.sourceURL(id(1)));assert.equal(host.authority.scope,browser.authority.scope);
}); });
+13 -12
View File
@@ -36,7 +36,7 @@ const reservation=createServer();await new Promise(resolve=>reservation.listen(0
let next,logs='',launchError; let next,logs='',launchError;
try{ try{
// 复制实际 route 及它依赖的响应/会话模块;临时页面仅满足 Next 项目结构,不替换被测 route。 // 复制实际 route 及它依赖的响应/会话模块;临时页面仅满足 Next 项目结构,不替换被测 route。
for(const filename of ['package.json','tsconfig.json','src/app/api/foundry/[...path]/route.ts','src/lib/canvas-response.ts','src/lib/session-cookie.ts']){ for(const filename of ['package.json','tsconfig.json','src/app/api/bedrock/[...path]/route.ts','src/lib/canvas-response.ts','src/lib/session-cookie.ts']){
const target=join(directory,filename);await mkdir(resolve(target,'..'),{recursive:true});await copyFile(join(source,filename),target); const target=join(directory,filename);await mkdir(resolve(target,'..'),{recursive:true});await copyFile(join(source,filename),target);
} }
// 复用当前依赖树而不重新安装,临时项目的源码和编译目录与主项目分开。 // 复用当前依赖树而不重新安装,临时项目的源码和编译目录与主项目分开。
@@ -44,58 +44,59 @@ try{
await writeFile(join(directory,'src/app/layout.tsx'),'export default function Layout({children}:{children:React.ReactNode}){return <html><body>{children}</body></html>}'); await writeFile(join(directory,'src/app/layout.tsx'),'export default function Layout({children}:{children:React.ReactNode}){return <html><body>{children}</body></html>}');
await writeFile(join(directory,'src/app/page.tsx'),'export default function Page(){return <main>Proxy verification fixture</main>}'); await writeFile(join(directory,'src/app/page.tsx'),'export default function Page(){return <main>Proxy verification fixture</main>}');
// 显式运行 webpack 开发服务器并指向本地上游,detached 便于 finally 按进程组清理。 // 显式运行 webpack 开发服务器并指向本地上游,detached 便于 finally 按进程组清理。
next=spawn(process.execPath,[join(source,'node_modules/next/dist/bin/next'),'dev','--webpack','--hostname','127.0.0.1','--port',String(port)],{cwd:directory,detached:true,env:{...process.env,NEXT_TELEMETRY_DISABLED:'1',FOUNDRY_API_ORIGIN:`http://127.0.0.1:${upstream.address().port}`,NEXT_PUBLIC_FOUNDRY_PROJECT:'fixture'},stdio:['ignore','pipe','pipe']}); next=spawn(process.execPath,[join(source,'node_modules/next/dist/bin/next'),'dev','--webpack','--hostname','127.0.0.1','--port',String(port)],{cwd:directory,detached:true,env:{...process.env,NEXT_TELEMETRY_DISABLED:'1',BEDROCK_API_ORIGIN:`http://127.0.0.1:${upstream.address().port}`,NEXT_PUBLIC_BEDROCK_PROJECT:'fixture'},stdio:['ignore','pipe','pipe']});
// 只保留最后 12000 字符日志;启动失败和退出必须被 readiness 循环识别。 // 只保留最后 12000 字符日志;启动失败和退出必须被 readiness 循环识别。
next.stdout.on('data',chunk=>{logs=(logs+chunk).slice(-12000)});next.stderr.on('data',chunk=>{logs=(logs+chunk).slice(-12000)});next.on('error',error=>{launchError=error}); next.stdout.on('data',chunk=>{logs=(logs+chunk).slice(-12000)});next.stderr.on('data',chunk=>{logs=(logs+chunk).slice(-12000)});next.on('error',error=>{launchError=error});
// 最多 90 次探测,单次请求超时 1.5 秒、失败间隔 250 毫秒;只有实际代理返回 200 才开始断言。 // 最多 90 次探测,单次请求超时 1.5 秒、失败间隔 250 毫秒;只有实际代理返回 200 才开始断言。
let ready=false; let ready=false;
for(let attempt=0;attempt<90;attempt++){ for(let attempt=0;attempt<90;attempt++){
if(launchError)throw launchError;if(next.exitCode!==null)throw new Error('Next exited during startup:\n'+logs); if(launchError)throw launchError;if(next.exitCode!==null)throw new Error('Next exited during startup:\n'+logs);
try{const response=await fetch(`http://127.0.0.1:${port}/api/foundry/profile`,{signal:AbortSignal.timeout(1500)});await response.text();if(response.status===200){ready=true;break}}catch{} try{const response=await fetch(`http://127.0.0.1:${port}/api/bedrock/profile`,{signal:AbortSignal.timeout(1500)});await response.text();if(response.status===200){ready=true;break}}catch{}
await pause(250); await pause(250);
} }
if(!ready)throw new Error('Next did not become ready:\n'+logs); if(!ready)throw new Error('Next did not become ready:\n'+logs);
assert.equal(received.at(-1)?.path,'/projects/fixture/profile');
// 规范文档操作路径使用固定 workspace/material,后续从它推导资产及 AI 路由。 // 规范文档操作路径使用固定 workspace/material,后续从它推导资产及 AI 路由。
const path='workspaces/10000000-0000-4000-8000-000000000003/materials/10000000-0000-4000-8000-000000000001/canvas/model/operations'; const path='workspaces/10000000-0000-4000-8000-000000000003/materials/10000000-0000-4000-8000-000000000001/canvas/model/operations';
// 1.1 MB 请求超过通用 1 MiB 上限但低于规范文档专用 5 MiB 上限,专门覆盖该路由的体积策略。 // 1.1 MB 请求超过通用 1 MiB 上限但低于规范文档专用 5 MiB 上限,专门覆盖该路由的体积策略。
const body=' {\n "protocol_version":2,"request_id":"'+key+'","fixture":"'+ 'x'.repeat(1100000)+'"\n} '; const body=' {\n "protocol_version":2,"request_id":"'+key+'","fixture":"'+ 'x'.repeat(1100000)+'"\n} ';
// 发送超过通用限制但低于文档专用限制的原始 body,核对上游状态码及终态回执字节不变。 // 发送超过通用限制但低于文档专用限制的原始 body,核对上游状态码及终态回执字节不变。
const response=await fetch(`http://127.0.0.1:${port}/api/foundry/${path}`,{method:'POST',body,headers:{'Content-Type':'application/json','Idempotency-Key':key,'X-Expected-Account':account,Cookie:'foundry_session=fixture-session',Origin:`http://127.0.0.1:${port}`},signal:AbortSignal.timeout(20000)}); const response=await fetch(`http://127.0.0.1:${port}/api/bedrock/${path}`,{method:'POST',body,headers:{'Content-Type':'application/json','Idempotency-Key':key,'X-Expected-Account':account,Cookie:'foundry_session=fixture-session',Origin:`http://127.0.0.1:${port}`},signal:AbortSignal.timeout(20000)});
assert.equal(response.status,409);assert.equal(await response.text(),responseBytes); assert.equal(response.status,409);assert.equal(await response.text(),responseBytes);
// 从上游记录检查 body、幂等键、预期账户,以及 session cookie 转成 Bearer 的实际结果。 // 从上游记录检查 body、幂等键、预期账户,以及 session cookie 转成 Bearer 的实际结果。
const request=received.find(item=>item.path.endsWith('/model/operations')); const request=received.find(item=>item.path.endsWith('/model/operations'));
assert.ok(request);assert.equal(request.body.toString(),body);assert.equal(request.headers['idempotency-key'],key);assert.equal(request.headers['x-expected-account'],account);assert.equal(request.headers.authorization,'Bearer fixture-session'); assert.ok(request);assert.equal(request.body.toString(),body);assert.equal(request.headers['idempotency-key'],key);assert.equal(request.headers['x-expected-account'],account);assert.equal(request.headers.authorization,'Bearer fixture-session');
// 资产回执和元数据是 JSON 路径;元数据还检查身份传递与 no-store,避免误走图片 body 验证。 // 资产回执和元数据是 JSON 路径;元数据还检查身份传递与 no-store,避免误走图片 body 验证。
const receiptPath=`workspaces/10000000-0000-4000-8000-000000000003/assets/operations/${key}`; const receiptPath=`workspaces/10000000-0000-4000-8000-000000000003/assets/operations/${key}`;
const assetReceipt=await fetch(`http://127.0.0.1:${port}/api/foundry/${receiptPath}`);assert.equal(assetReceipt.status,200);assert.deepEqual(await assetReceipt.json(),{id:'fixture'}); const assetReceipt=await fetch(`http://127.0.0.1:${port}/api/bedrock/${receiptPath}`);assert.equal(assetReceipt.status,200);assert.deepEqual(await assetReceipt.json(),{id:'fixture'});
const metadata=await fetch(`http://127.0.0.1:${port}/api/foundry/${receiptPath.replace('/operations/','/metadata/')}`,{headers:{'X-Expected-Account':account,Cookie:'foundry_session=fixture-session'}});assert.equal(metadata.status,200);assert.deepEqual(await metadata.json(),{id:'fixture'});assert.match(metadata.headers.get('cache-control'),/no-store/);const metadataRequest=received.find(item=>item.path.includes('/assets/metadata/'));assert.equal(metadataRequest.headers['x-expected-account'],account);assert.equal(metadataRequest.headers.authorization,'Bearer fixture-session'); const metadata=await fetch(`http://127.0.0.1:${port}/api/bedrock/${receiptPath.replace('/operations/','/metadata/')}`,{headers:{'X-Expected-Account':account,Cookie:'foundry_session=fixture-session'}});assert.equal(metadata.status,200);assert.deepEqual(await metadata.json(),{id:'fixture'});assert.match(metadata.headers.get('cache-control'),/no-store/);const metadataRequest=received.find(item=>item.path.includes('/assets/metadata/'));assert.equal(metadataRequest.headers['x-expected-account'],account);assert.equal(metadataRequest.headers.authorization,'Bearer fixture-session');
console.log('PASS asset metadata JSON uses the actual authenticated Next proxy without image-body validation or caching'); console.log('PASS asset metadata JSON uses the actual authenticated Next proxy without image-body validation or caching');
// FormData 自带 boundary;下面核对文件内容片段、Content-Type 和资源/幂等身份头,未逐字节比较整份 multipart 包。 // FormData 自带 boundary;下面核对文件内容片段、Content-Type 和资源/幂等身份头,未逐字节比较整份 multipart 包。
const multipart=new FormData();multipart.append('image',new Blob(['immutable file'],{type:'image/png'}),'fixture.png'); const multipart=new FormData();multipart.append('image',new Blob(['immutable file'],{type:'image/png'}),'fixture.png');
const assetPath=receiptPath.split('/operations/')[0],resourceId='10000000-0000-4000-8000-000000000006'; const assetPath=receiptPath.split('/operations/')[0],resourceId='10000000-0000-4000-8000-000000000006';
const uploaded=await fetch(`http://127.0.0.1:${port}/api/foundry/${assetPath}`,{method:'POST',body:multipart,headers:{'X-Resource-Id':resourceId,'Idempotency-Key':key,'X-Expected-Account':account}});await uploaded.text();assert.equal(uploaded.status,200); const uploaded=await fetch(`http://127.0.0.1:${port}/api/bedrock/${assetPath}`,{method:'POST',body:multipart,headers:{'X-Resource-Id':resourceId,'Idempotency-Key':key,'X-Expected-Account':account}});await uploaded.text();assert.equal(uploaded.status,200);
const upload=received.find(item=>item.path.endsWith('/assets'));assert.equal(upload.headers['x-resource-id'],resourceId);assert.equal(upload.headers['idempotency-key'],key);assert.match(upload.body.toString(),/immutable file/);assert.match(upload.headers['content-type'],/^multipart\/form-data; boundary=/); const upload=received.find(item=>item.path.endsWith('/assets'));assert.equal(upload.headers['x-resource-id'],resourceId);assert.equal(upload.headers['idempotency-key'],key);assert.match(upload.body.toString(),/immutable file/);assert.match(upload.headers['content-type'],/^multipart\/form-data; boundary=/);
console.log('PASS asset receipt JSON and multipart resource identity cross the actual Next proxy'); console.log('PASS asset receipt JSON and multipart resource identity cross the actual Next proxy');
// AI 受理同样保留冻结 JSON 空白、幂等键和 If-Match,并协商 canvas v2;查询回执与事件游标单独检查。 // AI 受理同样保留冻结 JSON 空白、幂等键和 If-Match,并协商 canvas v2;查询回执与事件游标单独检查。
const aiPath=path.replace('/model/operations','/ai/runs'); const aiPath=path.replace('/model/operations','/ai/runs');
const frozenAI=' {\n "protocol_version":2,"request_id":"'+key+'","prompt":"保留请求字节" } '; const frozenAI=' {\n "protocol_version":2,"request_id":"'+key+'","prompt":"保留请求字节" } ';
const aiResponse=await fetch(`http://127.0.0.1:${port}/api/foundry/${aiPath}`,{method:'POST',body:frozenAI,headers:{'Content-Type':'application/json','Idempotency-Key':key,'If-Match':'"7"','X-Expected-Account':account,Cookie:'foundry_session=fixture-session'}}); const aiResponse=await fetch(`http://127.0.0.1:${port}/api/bedrock/${aiPath}`,{method:'POST',body:frozenAI,headers:{'Content-Type':'application/json','Idempotency-Key':key,'If-Match':'"7"','X-Expected-Account':account,Cookie:'foundry_session=fixture-session'}});
await aiResponse.text();assert.equal(aiResponse.status,200); await aiResponse.text();assert.equal(aiResponse.status,200);
const ai=received.find(item=>item.path.endsWith('/ai/runs')); const ai=received.find(item=>item.path.endsWith('/ai/runs'));
assert.equal(ai.body.toString(),frozenAI);assert.equal(ai.headers['if-match'],'"7"');assert.equal(ai.headers['idempotency-key'],key);assert.equal(ai.headers['x-expected-account'],account);assert.equal(ai.headers.authorization,'Bearer fixture-session');assert.equal(ai.headers.accept,'application/vnd.foundry.canvas+json;version=2'); assert.equal(ai.body.toString(),frozenAI);assert.equal(ai.headers['if-match'],'"7"');assert.equal(ai.headers['idempotency-key'],key);assert.equal(ai.headers['x-expected-account'],account);assert.equal(ai.headers.authorization,'Bearer fixture-session');assert.equal(ai.headers.accept,'application/vnd.foundry.canvas+json;version=2');
const aiReceipt=await fetch(`http://127.0.0.1:${port}/api/foundry/${aiPath.replace('/runs','/operations')}/${key}`);await aiReceipt.text();assert.equal(aiReceipt.status,200); const aiReceipt=await fetch(`http://127.0.0.1:${port}/api/bedrock/${aiPath.replace('/runs','/operations')}/${key}`);await aiReceipt.text();assert.equal(aiReceipt.status,200);
assert.ok(received.some(item=>item.path.endsWith('/ai/operations/'+key))); assert.ok(received.some(item=>item.path.endsWith('/ai/operations/'+key)));
const aiEvents=await fetch(`http://127.0.0.1:${port}/api/foundry/${aiPath}/${key}?after_seq=41&limit=100`);await aiEvents.text();assert.equal(aiEvents.status,200); const aiEvents=await fetch(`http://127.0.0.1:${port}/api/bedrock/${aiPath}/${key}?after_seq=41&limit=100`);await aiEvents.text();assert.equal(aiEvents.status,200);
assert.ok(received.some(item=>item.path.endsWith('/ai/runs/'+key+'?limit=100&after_seq=41'))); assert.ok(received.some(item=>item.path.endsWith('/ai/runs/'+key+'?limit=100&after_seq=41')));
console.log('PASS frozen AI bytes, identity, version header, admission receipt and event cursor cross the actual Next proxy'); console.log('PASS frozen AI bytes, identity, version header, admission receipt and event cursor cross the actual Next proxy');
// 上游尾部仍挂起时读取第一块,随后释放并核对余下字节,验证端到端增量转发。 // 上游尾部仍挂起时读取第一块,随后释放并核对余下字节,验证端到端增量转发。
const streamed=await fetch(`http://127.0.0.1:${port}/api/foundry/${path.replace('/operations','')}`,{headers:{Accept:'application/vnd.foundry.canvas-model+ndjson;version=1'}}); const streamed=await fetch(`http://127.0.0.1:${port}/api/bedrock/${path.replace('/operations','')}`,{headers:{Accept:'application/vnd.foundry.canvas-model+ndjson;version=1'}});
assert.equal(streamed.headers.get('content-type'),'application/vnd.foundry.canvas-model+ndjson;version=1'); assert.equal(streamed.headers.get('content-type'),'application/vnd.foundry.canvas-model+ndjson;version=1');
// 尾部 gate 尚未放开就等待首块,才能区分增量转发和整条缓冲;随后放开并排空剩余 body。 // 尾部 gate 尚未放开就等待首块,才能区分增量转发和整条缓冲;随后放开并排空剩余 body。
const reader=streamed.body.getReader(),first=await reader.read();assert.equal(new TextDecoder().decode(first.value),streamPrefix);streamRelease();let rest='';while(true){const next=await reader.read();if(next.done)break;rest+=new TextDecoder().decode(next.value);}assert.equal(rest,streamTail);reader.releaseLock(); const reader=streamed.body.getReader(),first=await reader.read();assert.equal(new TextDecoder().decode(first.value),streamPrefix);streamRelease();let rest='';while(true){const next=await reader.read();if(next.done)break;rest+=new TextDecoder().decode(next.value);}assert.equal(rest,streamTail);reader.releaseLock();
console.log('PASS negotiated canonical NDJSON and first chunk cross the actual Next proxy before the gated tail'); console.log('PASS negotiated canonical NDJSON and first chunk cross the actual Next proxy before the gated tail');
// 多余路径段应在代理 allowlist 被拒绝,不能发到上游再依赖上游返回错误。 // 多余路径段应在代理 allowlist 被拒绝,不能发到上游再依赖上游返回错误。
const before=received.length,invalid=await fetch(`http://127.0.0.1:${port}/api/foundry/${path}/unexpected/extra`,{signal:AbortSignal.timeout(10000)});await invalid.text();assert.equal(invalid.status,404);assert.equal(received.length,before); const before=received.length,invalid=await fetch(`http://127.0.0.1:${port}/api/bedrock/${path}/unexpected/extra`,{signal:AbortSignal.timeout(10000)});await invalid.text();assert.equal(invalid.status,404);assert.equal(received.length,before);
console.log('PASS actual Next proxy preserves frozen request bytes/key/account and raw terminal receipt above 1 MiB'); console.log('PASS actual Next proxy preserves frozen request bytes/key/account and raw terminal receipt above 1 MiB');
console.log('PASS canonical route allowlist rejects unexpected paths without contacting the upstream'); console.log('PASS canonical route allowlist rejects unexpected paths without contacting the upstream');
}finally{ }finally{
+2 -2
View File
@@ -216,7 +216,7 @@ module.exports=function(source){return nativeTransform.call(this,source).replace
await symlink(join(source, 'node_modules'), join(directory, 'node_modules')); await symlink(join(source, 'node_modules'), join(directory, 'node_modules'));
// 统一 Next 子进程启动和日志尾部收集;独立进程组供 finally 一并终止,API origin 指向本次上游。 // 统一 Next 子进程启动和日志尾部收集;独立进程组供 finally 一并终止,API origin 指向本次上游。
const launchNext=args=>{ const launchNext=args=>{
const child=spawn(process.execPath,[join(source,'node_modules/next/dist/bin/next'),...args],{cwd:directory,detached:true,env:{...process.env,NEXT_TELEMETRY_DISABLED:'1',FOUNDRY_API_ORIGIN:`http://127.0.0.1:${upstream.address().port}`,NEXT_PUBLIC_FOUNDRY_PROJECT:'endoleap'},stdio:['ignore','pipe','pipe']}); const child=spawn(process.execPath,[join(source,'node_modules/next/dist/bin/next'),...args],{cwd:directory,detached:true,env:{...process.env,NEXT_TELEMETRY_DISABLED:'1',BEDROCK_API_ORIGIN:`http://127.0.0.1:${upstream.address().port}`,NEXT_PUBLIC_BEDROCK_PROJECT:'endoleap'},stdio:['ignore','pipe','pipe']});
child.stdout.on('data',chunk=>{logs=(logs+chunk).slice(-16000);});child.stderr.on('data',chunk=>{logs=(logs+chunk).slice(-16000);});return child; child.stdout.on('data',chunk=>{logs=(logs+chunk).slice(-16000);});child.stderr.on('data',chunk=>{logs=(logs+chunk).slice(-16000);});return child;
}; };
let buildMs; let buildMs;
@@ -229,7 +229,7 @@ module.exports=function(source){return nativeTransform.call(this,source).replace
next=launchNext([productionMode?'start':'dev',...productionMode?[]:[`--${bundler}`],'--hostname','127.0.0.1','--port',String(port)]); next=launchNext([productionMode?'start':'dev',...productionMode?[]:[`--${bundler}`],'--hostname','127.0.0.1','--port',String(port)]);
// 有界探测真实代理 profile,并检查 Next 提前退出;后续页面等待还会验证应用是否实际可用。 // 有界探测真实代理 profile,并检查 Next 提前退出;后续页面等待还会验证应用是否实际可用。
// 循环结束后未另设 ready 断言;120 次都未成功时仍进入浏览器阶段,由后续导航/页面等待暴露未就绪。 // 循环结束后未另设 ready 断言;120 次都未成功时仍进入浏览器阶段,由后续导航/页面等待暴露未就绪。
for (let i = 0; i < 120; i++) { if (next.exitCode !== null) throw new Error(logs); try { const r = await fetch(`http://127.0.0.1:${port}/api/foundry/profile`, { signal: AbortSignal.timeout(1000) }); if (r.ok) break; } catch {} await pause(250); } for (let i = 0; i < 120; i++) { if (next.exitCode !== null) throw new Error(logs); try { const r = await fetch(`http://127.0.0.1:${port}/api/bedrock/profile`, { signal: AbortSignal.timeout(1000) }); if (r.ok) break; } catch {} await pause(250); }
// 只保留本次隔离 Chrome 的日志尾部,CHROME_BIN 可覆盖可执行路径,不连接日常 profile。 // 只保留本次隔离 Chrome 的日志尾部,CHROME_BIN 可覆盖可执行路径,不连接日常 profile。
let browserLogs=''; let browserLogs='';
chrome = spawn(process.env.CHROME_BIN ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', ['--headless=new', '--no-first-run', '--disable-background-networking', '--disable-component-update', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore','ignore','pipe'] }); chrome = spawn(process.env.CHROME_BIN ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', ['--headless=new', '--no-first-run', '--disable-background-networking', '--disable-component-update', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore','ignore','pipe'] });