diff --git a/AGENTS.md b/AGENTS.md index 04748d6..1b80b2f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,7 +60,7 @@ AGENTS.md # 本文档 | [note-style](skills/note-style/README.md) | 把材料整理成可长期查阅的知识笔记 | | [orc](skills/orc/README.md) | 把开发、发版、DEB / Docker 意图编排成阶段,按档位分发给对应 skill | | [pouch](skills/pouch/README.md) | 创建、校验、安装和维护 builtin skill | -| [previewer](skills/previewer/README.md) | 通过 Tailscale Serve 将静态文件暴露为 tailnet 内 HTTP 预览 | +| [previewer](skills/previewer/README.md) | 用 Node 提供 HTML/静态文件预览,返回 URL 并复用已有服务 | | [pr-ship](skills/pr-ship/README.md) | 把已有 PR 从检查、合并推进到回归、构建和部署 | | [releaser](skills/releaser/README.md) | 给已准备好的 commit 发版本:更新说明、tag、可选 Forge Release | | [ship](skills/ship/README.md) | short-ship / long-ship / pr-ship 共用的交付记录格式 | diff --git a/README.md b/README.md index b321d36..651bd8a 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ AGENTS.md # 详细规范与架构说明 | [note-style](skills/note-style/README.md) | 把材料整理成可长期查阅的知识笔记 | | [orc](skills/orc/README.md) | 把开发、发版、DEB / Docker 意图编排成阶段,按档位分发给对应 skill | | [pouch](skills/pouch/README.md) | 创建、校验、安装和维护 builtin skill | -| [previewer](skills/previewer/README.md) | 用 Node 渲染 HTML/静态文件,并通过 Tailscale 返回访问 IP 和 HTTP 预览 | +| [previewer](skills/previewer/README.md) | 用 Node 提供 HTML/静态文件预览,返回 URL 并复用已有服务 | | [pr-ship](skills/pr-ship/README.md) | 把已有 PR 从检查、合并推进到回归、构建和部署 | | [releaser](skills/releaser/README.md) | 给已准备好的 commit 发版本:更新说明、tag、可选 Forge Release | | [ship](skills/ship/README.md) | short-ship / long-ship / pr-ship 共用的交付记录格式 | diff --git a/skills/previewer/README.md b/skills/previewer/README.md index 3dd31dc..251b71a 100644 --- a/skills/previewer/README.md +++ b/skills/previewer/README.md @@ -1,42 +1,34 @@ # previewer -用 Node 启动默认存活 1 小时的轻量静态服务,再通过 Tailscale Serve 把本机的 HTML、PRD、报告 -或其它静态文件暴露给 tailnet,并返回应该使用的 Tailscale IP 和 HTTP URL。 +用 Node 直接预览已有 HTML 和静态文件,返回可打开的 HTTP URL。只需要 Node.js,无需安装 +npm 依赖,也不配置隧道或代理。 -## 什么时候使用 +## 用法 -- 想在手机、平板或另一台电脑查看本机生成的 HTML。 -- 可以直接说“把这个 HTML 渲染出来,并告诉我用哪个 IP”。 -- 其它 skill 需要把某个文件交给通用预览服务。 - -只面向 Tailscale tailnet,不提供公网访问,也不启动动态 Web 服务。 - -## 使用前准备 - -- 本机已安装 Node.js、已登录 Tailscale,且访问者也在允许访问的 tailnet 中。 -- 提供要展示的文件路径;文件所在目录会被作为静态目录服务。 - -## 使用示例 - -```text -用 previewer 展示这个文件:/workspace/docs/prd-v002.html,挂载到 /preview/billing。 +```bash +node ~/.pouch/skills/previewer/scripts/serve_file.js /workspace/preview/index.html ``` -```text -把 /workspace/docs/prd-v002.html 渲染出来,告诉我用哪个 IP 和 URL 查看。 +默认只允许同机访问,自动选择空闲端口,一小时后关闭。需要局域网访问时: + +```bash +node ~/.pouch/skills/previewer/scripts/serve_file.js /workspace/preview/index.html --host 0.0.0.0 --port 8088 ``` -## Agent 会做什么 +输出包含 URL、监听地址、端口、PID、过期时间和停止命令。绑定所有接口时还会列出本机网卡 +的候选 URL,实际可达性取决于访问者所在网络。 -1. 检查 Tailscale 是否在线,以及 Serve 状态是否可读取。 -2. 用 Node 在 localhost 启动文件所在目录的静态服务。 -3. 将指定 Tailscale 路径代理到本地端口。 -4. 返回 Tailscale IPv4、完整 HTTP URL、Node PID、过期时间和停止命令,并明确告诉用户 - 应该使用哪个 IP。 +## 复用方式 -默认 1 小时后自动关闭 Node 服务和对应的 Tailscale 路由;需要其它时长时可传 `--ttl` 秒数。 +其它 skill 生成文件后,直接执行上面的同一份脚本,读取 JSON,不需要再次委派 Agent。 +相同文件和参数的连续或并发调用会复用仍存活的服务,端口与过期时间保持不变。 +HTML、CSS 或 JavaScript 更新后刷新页面即可;React 等项目需先由调用方构建成静态文件。 -## 如何判断完成 +文件父目录作为服务目录,相对资源可以正常加载;不提供目录列表,也不允许访问目录外的文件。 +本工具提供文件,页面由浏览器渲染;不执行模板生成或截图。 -- 得到一个 HTTP URL,并能从 tailnet 内的另一台设备打开目标文件。 -- 失败时明确说明是 Tailscale 未安装、未登录、路由冲突还是 Serve 命令失败。 +## 验证 + +```bash +node --test ~/.pouch/skills/previewer/tests/serve_file.test.js +``` diff --git a/skills/previewer/SKILL.md b/skills/previewer/SKILL.md index e78c487..3476204 100644 --- a/skills/previewer/SKILL.md +++ b/skills/previewer/SKILL.md @@ -1,73 +1,48 @@ --- name: previewer description: >- - 将本地 HTML、PRD、报告、截图或其它静态文件用 Node 渲染成 HTTP 预览,并通过 Tailscale - tailnet 暴露;用户说“把这个 HTML 渲染出来”“给我访问 IP/URL”或要求远程查看文件时使用; - 不用于公网发布、动态应用部署或业务服务反向代理。 + 用 Node 将已有 HTML、PRD、报告、截图或其它静态文件提供为 HTTP 预览。 + 用户说“把这个 HTML 渲染出来”“预览这个文件”“给我预览 URL”时使用; + 不生成页面内容,不执行构建,不配置代理、隧道或动态业务服务。 --- -# Previewer:HTML/静态文件渲染预览 +# Previewer:HTML/静态文件预览 -调用方只提供一个要展示的文件。Previewer 用 Node 启动本地静态服务,再让 -`tailscale serve` 代理这个 localhost 端口,最后返回 tailnet 内 HTTP URL。它是独立的通用 -HTML 渲染能力,specifier、report 或其它 skill 都可以调用。 - -## 何时使用 - -- 展示本机生成的 HTML、PRD、报告、截图或其它静态文件。 -- 用户直接说“把这个 HTML 渲染出来”,并希望从手机或另一台机器打开。 -- 其它 skill 需要一个通用的“给我文件,返回可访问链接”能力。 -- 用户明确要求通过 Tailscale 访问预览内容。 - -## 不适用 - -- 公网访问:不使用 Funnel,也不替用户开放公网入口。 -- 动态服务、API、WebSocket 或需要构建/运行的应用:交给部署或开发工具。 -- 不需要远程访问的本地预览:直接用本地浏览器或文件路径。 +调用方提供一个文件,脚本启动静态 HTTP 服务并返回 JSON。HTML 的实际排版和 JavaScript +由浏览器执行,previewer 不编译模板、不构建 React,也不生成截图。 ## 调用方式 -前置条件:本机安装 Node.js 和 Tailscale,并已登录目标 tailnet。找到本 skill 目录 -``,执行: +前置条件只有 Node.js。读取 [contract.md](references/contract.md),执行: ```bash -node /scripts/serve_file.js \ - \ - --mount-path /preview/ +node /scripts/serve_file.js ``` -脚本默认使用 Tailscale HTTP 80 端口,并为本地 Node 服务自动选择空闲端口;可用 `--port` -指定 Tailscale 对外端口、`--local-port` 指定本地端口。Node 服务默认 1 小时后自动关闭, -到期时同时关闭对应 Serve 路由;可用 `--ttl` 以秒覆盖。它输出一个 JSON,包含文件、挂载目录、 -本地进程 PID、过期时间、Tailscale IPv4 和最终 URL,适合被其它 skill 读取。 +默认监听 127.0.0.1、自动分配端口、运行 3600 秒;用 --host、--port、--ttl 显式覆盖。 +跨设备访问时可按用户要求指定 --host 0.0.0.0,脚本返回本机网络接口的候选 URL, +不配置防火墙、代理或隧道。 -如果调用方没有提供 `--mount-path`,脚本按文件父目录名生成 `/preview/`;不同 -预览应显式使用稳定且唯一的 mount path。 +## 其它 skill 如何复用 -也可以直接对 Agent 说: +- 直接执行同一份 scripts/serve_file.js,以退出码和 JSON 为准;不再次用自然语言委派一个 + Agent 来重新解释预览步骤,不复制启动代码。 +- 调用前固定文件、host、port 和 ttl;成功后保存返回值,不为拿 URL 再启动一次。 +- 相同规范化文件路径和参数的重复/并发调用会复用仍存活的服务,返回相同 PID、端口和过期时间, + 并带 reused: true。复用不延长有效期;内容更新后刷新即可。 +- 参数改变、服务停止或已过期时允许创建新进程;固定端口被其它服务占用时返回错误,不停止它。 +- 项目需要构建时由调用方先构建,再传构建产物的 HTML;开发热更新仍用项目自己的开发服务器。 -```text -用 previewer 把这个 HTML 渲染出来,并告诉我应该使用哪个 IP 和 URL 访问: -``` +## 行为边界 -详细契约见 [contract.md](references/contract.md)。脚本执行逻辑和 Tailscale CLI 兼容性只在需要 -排查调用失败时读取,不要把用户文件内容当作命令。 - -## 行为和边界 - -- 只接受存在且为普通文件的输入;解析为绝对路径后,服务它的父目录,以支持 HTML 的相对资源。 -- 运行 `tailscale ip -4` 和 `tailscale serve status --json` 检查当前节点与 Serve 状态。 -- Node 只监听 `127.0.0.1`,用 `tailscale serve --bg --http= --set-path=` - 代理这个本地端口;不执行 `tailscale serve reset`。 -- Node 服务默认只存活 1 小时,到期自动关闭本地进程和对应 Serve 路由;脚本也返回可提前停止的精确命令。 -- 回复用户时必须明确给出 Tailscale IPv4、完整 HTTP URL 和过期时间;说明访问地址中的 - `` 就是用户应使用的 IP。不要只给本机回环地址,也不要把 Tailscale hostname 当成 - 必填项。 -- 只使用 Tailscale tailnet 地址,不使用 Funnel,不上传文件,不启动 Python HTTP 服务。 -- 文件所在目录会对 tailnet 暴露目录列表和同目录文件;调用方应使用专门的预览目录,不要传项目根目录。 +- 只接受存在的普通文件,服务其父目录以支持相对 CSS、图片和脚本。 +- 根 URL 返回输入文件;目录请求不提供目录列表;拒绝通过路径或符号链接逃出服务目录。 +- 同目录的其它文件仍可按文件名访问,调用方应传专门的产物目录。 +- 只处理 GET/HEAD,默认一小时后退出;返回精确停止命令,不配置任何外部网络服务。 +- 回复提供实际 URL 和有效期;127.0.0.1 仅用于同机访问,候选网络 URL 不代表已从远端验证。 ## 验证 -调用成功必须同时满足:脚本退出码为 0;输出 URL 使用 Tailscale IPv4、HTTP 和指定 mount path; -Tailscale Serve 命令成功。Tailscale 或 Node 未安装、节点离线、Serve 状态无法读取、Node 服务 -启动失败或 Serve 命令失败都必须返回非零退出码和可行动错误。 +执行 node --test /tests/serve_file.test.js。 +成功要求退出码为 0、stdout 是一个 JSON、HTTP 服务可用;失败写 stderr JSON 并非零退出。 +无需安装依赖。文件错误、参数错误、端口冲突和启动失败必须明确返回错误码。 diff --git a/skills/previewer/agents/openai.yaml b/skills/previewer/agents/openai.yaml index da9fead..69ea7a4 100644 --- a/skills/previewer/agents/openai.yaml +++ b/skills/previewer/agents/openai.yaml @@ -1,6 +1,6 @@ interface: display_name: "HTML Previewer" - short_description: "Render local HTML over Tailscale and return the access IP" - default_prompt: "Use $previewer to render this HTML over Tailscale and tell me which IP and HTTP URL to use." + short_description: "Serve existing HTML and static files with Node and return a preview URL" + default_prompt: "Use $previewer to serve this HTML file locally and return its HTTP URL and expiration time." policy: allow_implicit_invocation: true diff --git a/skills/previewer/references/contract.md b/skills/previewer/references/contract.md index 75e6eea..81b4d67 100644 --- a/skills/previewer/references/contract.md +++ b/skills/previewer/references/contract.md @@ -3,51 +3,55 @@ ## 输入 ```text -node scripts/serve_file.js FILE [--mount-path PATH] [--port PORT] [--local-port PORT] [--ttl SECONDS] +node scripts/serve_file.js FILE [--host IP] [--port PORT] [--ttl SECONDS] ``` -- `FILE`:必须是存在的普通文件,建议使用绝对路径。 -- `--mount-path`:以 `/` 开头的 URL 路径,不能包含 `?`、`#`、空段或 `..`;不提供时按父目录名生成。 -- `--port`:Tailscale 对外 HTTP 端口,默认 `80`。 -- `--local-port`:Node 监听的 localhost 端口,默认自动选择空闲端口。 -- `--ttl`:服务存活时间,单位为秒,默认 `3600`(1 小时);到期同时关闭 Node 服务和对应 - Tailscale Serve 路由。 +- FILE:存在的普通文件;解析为规范绝对路径,服务其父目录。 +- --host:默认 127.0.0.1;支持 IP 或 localhost(等价于 127.0.0.1)。0.0.0.0 表示所有 IPv4 接口。 +- --port:默认 0,自动选择空闲端口;显式端口范围为 1..65535。 +- --ttl:默认 3600 秒,允许 1..2147483;过期关闭该服务。 -Node 服务 `FILE` 的父目录,而不是把文件复制到其它地方。这样 HTML 可以加载同目录的 CSS、 -图片和其它资源,但也意味着同目录其它文件会对 tailnet 可见。Node 只监听 `127.0.0.1`, -Tailscale Serve 负责把指定路径代理到这个本地端口。 +旧的 --mount-path、--local-port、--tailscale-port 参数不再接受。--port 现在仅表示 Node +静态服务的监听端口。脚本不读取或改写任何外部网络配置。 ## 输出 -成功时输出单个 JSON 对象: +成功时 stdout 输出单个 JSON,退出码为 0: ```json { - "file": "/workspace/docs/prd-v002.html", - "directory": "/workspace/docs", - "mountPath": "/preview/billing", - "ip": "100.101.102.103", - "port": 80, - "localPort": 43721, + "file": "/workspace/preview/index.html", + "directory": "/workspace/preview", + "host": "127.0.0.1", + "port": 43721, "pid": 12345, "ttl": 3600, - "expiresAt": "2026-10-11T13:00:00.000Z", - "url": "http://100.101.102.103/preview/billing/prd-v002.html", - "stopCommand": "kill 12345 2>/dev/null || true; tailscale serve --http=80 --set-path=/preview/billing off" + "expiresAt": "2026-10-19T13:00:00.000Z", + "url": "http://127.0.0.1:43721/index.html", + "urls": ["http://127.0.0.1:43721/index.html"], + "reused": false, + "stopCommand": "kill -TERM 12345" } ``` -调用方应把 `ip` 字段和 `url` 一起展示给用户:`ip` 是访问这次预览时应使用的 Tailscale -IPv4,`url` 是可直接打开的完整 HTTP 地址。不要把 `127.0.0.1` 当成远程访问地址,也不 -要求用户必须使用 Tailscale hostname。 +url 是该服务器的本地可访问入口。绑定所有接口时,urls 还列出系统网络接口的 IPv4 候选链接; +脚本不判断访问者在哪个网络,也不保证远端可达。路径含空格和中文时 URL 自动编码。 +根路径 / 同样返回输入文件;HTML 的相对 CSS/JS/图片按原目录提供。 -失败时输出到 stderr,退出码非 0;调用方不能把部分 stdout 当成有效 URL。 +失败时 stderr 输出单个 JSON,例如: -## 状态和冲突 +```json +{ "code": "PORT_IN_USE", "message": "listen EADDRINUSE ..." } +``` -脚本先读取 `tailscale serve status --json`,确认当前 Tailscale Serve 可用,然后启动 Node 本地 -服务并追加指定 `--set-path` 路由。应为不同预览使用不同 mount path;脚本不会执行全量重置。 +错误码包括 ARGUMENT、FILE_INVALID、PORT_IN_USE、START_FAILED、START_TIMEOUT、 +VERIFY_FAILED、BUSY;退出码为 2。成功 JSON 不包含认证探测 token。 -Serve 配置由 Tailscale 持久保存,但 Node 服务默认在 1 小时后自动关闭并清理对应路由。需要 -提前停止时使用输出的命令,不能使用 `tailscale serve reset`,因为 reset 会清除该节点的全部 -Serve 配置。 +## 重复调用和生命周期 + +脚本按规范化文件路径、host、请求端口和 ttl 建立服务标识。在系统临时目录内保存当前用户 +的进程记录,启动通过目录锁串行化。调用时会以服务标识和探测 token 验证原进程;仍可用则 +返回 reused: true,且不续期。否则重新启动并更新记录,不凭 PID 盲目停止进程。 + +服务在 ttl 到期或接到 SIGTERM/SIGINT 后停止。重复调用不意味着续期;要改变有效期可使用 +新的 --ttl 参数或先停止原服务。调用方保存一次成功结果,之后直接使用 URL。 diff --git a/skills/previewer/scripts/serve_file.js b/skills/previewer/scripts/serve_file.js index 692a765..241df95 100644 --- a/skills/previewer/scripts/serve_file.js +++ b/skills/previewer/scripts/serve_file.js @@ -1,310 +1,252 @@ #!/usr/bin/env node -/* - * Start a tiny local static server and expose it through Tailscale Serve. - * Node is used for the local server so the Tailscale route only needs to - * proxy a localhost port. - */ - 'use strict'; +// Serve existing HTML and static assets. No build step, proxy, or network configuration. const fs = require('node:fs'); const http = require('node:http'); -const net = require('node:net'); +const os = require('node:os'); const path = require('node:path'); -const { spawn, spawnSync } = require('node:child_process'); +const crypto = require('node:crypto'); +const net = require('node:net'); +const { spawn } = require('node:child_process'); -class PreviewError extends Error {} - -function usage() { - return `Usage: node serve_file.js FILE [--mount-path PATH] [--port PORT] [--ttl SECONDS] - -Expose FILE through Tailscale Serve. Node serves FILE's parent directory on -localhost; Tailscale proxies that local server to the tailnet. -`; +class PreviewError extends Error { + constructor(code, message) { super(message); this.code = code; } } +const fail = (code, message) => { throw new PreviewError(code, message); }; +const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const statusPath = '/.previewer-status'; +const types = { + '.html': 'text/html; charset=utf-8', '.htm': 'text/html; charset=utf-8', + '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8', + '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', + '.gif': 'image/gif', '.webp': 'image/webp', '.ico': 'image/x-icon', + '.woff': 'font/woff', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', + '.pdf': 'application/pdf', '.wasm': 'application/wasm', +}; function parseArgs(argv) { - const args = { - file: null, root: null, mountPath: null, port: 80, localPort: 0, - ttl: 3600, tailscalePort: null, server: false, - }; - for (let i = 0; i < argv.length; i += 1) { - const value = argv[i]; - if (value === '--help' || value === '-h') { - console.log(usage()); - process.exit(0); - } - if (value === '--server') { - args.server = true; - continue; - } - if (value === '--root') { - args.root = argv[++i]; - continue; - } - if (value === '--mount-path') { - args.mountPath = argv[++i]; - continue; - } - if (value === '--port') { - args.port = Number(argv[++i]); - continue; - } - if (value === '--local-port') { - args.localPort = Number(argv[++i]); - continue; - } - if (value === '--ttl') { - args.ttl = Number(argv[++i]); - continue; - } - if (value === '--tailscale-port') { - args.tailscalePort = Number(argv[++i]); - continue; - } - if (value.startsWith('-')) { - throw new PreviewError(`未知参数:${value}`); - } - if (args.file === null) { - args.file = value; - } else { - throw new PreviewError(`多余参数:${value}`); - } + const args = { host: '127.0.0.1', port: 0, ttl: 3600, file: null }; + for (let index = 0; index < argv.length; index++) { + const value = argv[index]; + if (['--host', '--port', '--ttl'].includes(value)) { + const next = argv[++index]; + if (next === undefined || next.startsWith('--')) fail('ARGUMENT', 'Missing value for ' + value); + args[value.slice(2)] = value === '--host' ? next : Number(next); + } else if (value.startsWith('-')) { + fail('ARGUMENT', 'Unknown option: ' + value); + } else if (args.file === null) args.file = value; + else fail('ARGUMENT', 'Unexpected argument: ' + value); + } + if (!args.file) fail('ARGUMENT', 'An HTML or static file is required'); + if (args.host === 'localhost') args.host = '127.0.0.1'; + if (!net.isIP(args.host)) fail('ARGUMENT', '--host must be an IPv4 or IPv6 address'); + if (!Number.isInteger(args.port) || args.port < 0 || args.port > 65535) fail('ARGUMENT', '--port must be 0..65535'); + // Node timers use a signed 32-bit millisecond delay. + if (!Number.isInteger(args.ttl) || args.ttl < 1 || args.ttl > 2147483) fail('ARGUMENT', '--ttl must be 1..2147483 seconds'); + try { + args.file = fs.realpathSync(path.resolve(args.file)); + if (!fs.statSync(args.file).isFile()) fail('FILE_INVALID', 'Input is not a regular file'); + } catch (error) { + if (error instanceof PreviewError) throw error; + fail('FILE_INVALID', 'File is unavailable: ' + path.resolve(args.file)); } return args; } -function validPort(port, name) { - if (!Number.isInteger(port) || port < 0 || port > 65535 || (name === 'port' && port === 0)) { - throw new PreviewError(`${name} 必须是有效端口`); - } -} - -function validTtl(ttl) { - if (!Number.isInteger(ttl) || ttl <= 0) { - throw new PreviewError('ttl 必须是正整数秒数'); - } -} - -function normalizeMountPath(value) { - const mountPath = value.trim(); - if (!mountPath.startsWith('/') || mountPath === '/') { - throw new PreviewError('mount path 必须以 / 开头且不能是根路径'); - } - if (mountPath.includes('?') || mountPath.includes('#') || mountPath.includes('//')) { - throw new PreviewError('mount path 不能包含 query、fragment 或空路径段'); - } - const parts = mountPath.split('/'); - if (parts.some((part) => part === '.' || part === '..')) { - throw new PreviewError('mount path 不能包含 . 或 ..'); - } - return mountPath.replace(/\/$/, ''); -} - -function defaultMountPath(directory) { - const slug = path.basename(directory).replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, ''); - if (!slug) { - throw new PreviewError('无法从文件目录生成 mount path,请显式提供 --mount-path'); - } - return `/preview/${slug}`; -} - -function run(command, commandArgs) { - const result = spawnSync(command, commandArgs, { encoding: 'utf8' }); - if (result.error) { - throw new PreviewError(`无法运行 ${command}:${result.error.message}`); - } - return result; -} - -function tailscaleIPv4() { - const result = run('tailscale', ['ip', '-4']); - if (result.status !== 0) { - throw new PreviewError(`Tailscale 节点不可用:${(result.stderr || result.stdout).trim() || 'tailscale ip -4 失败'}`); - } - const address = result.stdout.split(/\s+/).find((candidate) => net.isIPv4(candidate)); - if (!address) { - throw new PreviewError('tailscale 没有返回 IPv4 地址;请确认节点已连接 tailnet'); - } - return address; -} - -function checkTailscaleServe() { - const result = run('tailscale', ['serve', 'status', '--json']); - if (result.status !== 0) { - throw new PreviewError(`无法读取 Tailscale Serve 状态:${(result.stderr || result.stdout).trim() || 'status 失败'}`); - } -} - -function serveStatic(root, mountPath, port, ttl, tailscalePort) { - const contentTypes = { - '.css': 'text/css; charset=utf-8', - '.gif': 'image/gif', - '.html': 'text/html; charset=utf-8', - '.jpeg': 'image/jpeg', - '.jpg': 'image/jpeg', - '.js': 'text/javascript; charset=utf-8', - '.json': 'application/json; charset=utf-8', - '.png': 'image/png', - '.svg': 'image/svg+xml', - '.txt': 'text/plain; charset=utf-8', - '.webp': 'image/webp', - }; - - const server = http.createServer((request, response) => { - let pathname; - try { - pathname = decodeURIComponent(new URL(request.url, 'http://127.0.0.1').pathname); - } catch { - response.writeHead(400).end('Bad request'); - return; +function urlHost(host) { return net.isIPv6(host) ? '[' + host + ']' : host; } +function probeHost(host) { return host === '0.0.0.0' ? '127.0.0.1' : host === '::' ? '::1' : host; } +function urlsFor(config, port) { + const filename = encodeURIComponent(path.basename(config.file)); + const address = probeHost(config.host); + const local = 'http://' + urlHost(address) + ':' + port + '/' + filename; + const urls = [local]; + if (config.host === '0.0.0.0' || config.host === '::') { + for (const entries of Object.values(os.networkInterfaces())) for (const entry of entries ?? []) { + if (entry.internal || entry.family !== 'IPv4') continue; + const url = 'http://' + entry.address + ':' + port + '/' + filename; + if (!urls.includes(url)) urls.push(url); } - if (pathname === mountPath || pathname.startsWith(`${mountPath}/`)) { - pathname = pathname.slice(mountPath.length) || '/'; - } - const relativePath = pathname.replace(/^\/+/, ''); - const candidate = path.resolve(root, relativePath); - if (candidate !== root && !candidate.startsWith(`${root}${path.sep}`)) { - response.writeHead(403).end('Forbidden'); - return; - } - fs.stat(candidate, (statError, info) => { - if (statError || !info.isFile()) { - response.writeHead(404).end('Not found'); + } + return { url: local, urls }; +} + +function probe(state) { + return new Promise((resolve) => { + if (!state || !Number.isInteger(state.port) || typeof state.token !== 'string') return resolve(false); + const request = http.get({ + host: probeHost(state.host), port: state.port, path: statusPath, + headers: { 'X-Previewer-Token': state.token }, timeout: 1000, + }, (response) => { + let body = ''; + response.on('data', (chunk) => { body += chunk; }); + response.on('end', () => { + try { + const actual = JSON.parse(body); + resolve(response.statusCode === 200 && actual.pid === state.pid && actual.key === state.key && actual.file === state.file); + } catch { resolve(false); } + }); + response.on('error', () => resolve(false)); + }); + request.on('error', () => resolve(false)); + request.on('timeout', () => { request.destroy(); resolve(false); }); + }); +} + +function publicResult(state, reused) { + const { token, key, ...result } = state; + return { ...result, reused, stopCommand: 'kill -TERM ' + state.pid }; +} + +function startWorker(config) { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [__filename, '--worker'], { + detached: true, stdio: ['ignore', 'ignore', 'pipe', 'ipc'], + }); + let diagnostics = ''; + child.stderr.on('data', (chunk) => { diagnostics += chunk; }); + const timer = setTimeout(() => { + child.kill(); + reject(new PreviewError('START_TIMEOUT', 'Static server did not become ready')); + }, 5000); + child.once('message', (message) => { + clearTimeout(timer); + if (message.error) { + child.kill(); + reject(new PreviewError(message.code ?? 'START_FAILED', message.error)); return; } - response.setHeader('Content-Type', contentTypes[path.extname(candidate).toLowerCase()] || 'application/octet-stream'); - fs.createReadStream(candidate).on('error', () => response.destroy()).pipe(response); - }); - }); - - server.listen(port, '127.0.0.1', () => { - const address = server.address(); - console.log(`READY ${address.port}`); - }); - - setTimeout(() => { - spawnSync('tailscale', [ - 'serve', `--http=${tailscalePort}`, `--set-path=${mountPath}`, 'off', - ], { stdio: 'ignore' }); - server.close(() => process.exit(0)); - setTimeout(() => process.exit(0), 1000); - }, ttl * 1000); -} - -function startDetachedServer(root, mountPath, localPort, ttl, tailscalePort) { - const child = spawn(process.execPath, [ - __filename, '--server', '--root', root, '--mount-path', mountPath, - '--port', String(localPort), '--ttl', String(ttl), '--tailscale-port', String(tailscalePort), - ], { - detached: true, - stdio: ['ignore', 'pipe', 'pipe'], - }); - - return new Promise((resolve, reject) => { - let output = ''; - const timeout = setTimeout(() => { - child.kill(); - reject(new PreviewError('Node 静态服务启动超时')); - }, 5000); - child.stdout.on('data', (chunk) => { - output += chunk.toString(); - const match = output.match(/READY (\d+)/); - if (!match) return; - clearTimeout(timeout); - child.stdout.destroy(); + child.disconnect(); child.stderr.destroy(); child.unref(); - resolve({ pid: child.pid, port: Number(match[1]) }); + resolve(message); }); - child.on('error', (error) => { - clearTimeout(timeout); - reject(new PreviewError(`Node 静态服务启动失败:${error.message}`)); + child.once('error', (error) => { + clearTimeout(timer); + reject(new PreviewError('START_FAILED', error.message)); }); - child.on('exit', (code) => { - if (code !== null && code !== 0) { - clearTimeout(timeout); - reject(new PreviewError(`Node 静态服务退出,code=${code}`)); - } + child.once('exit', (code) => { + clearTimeout(timer); + reject(new PreviewError('START_FAILED', 'Static server exited: ' + code + ' ' + diagnostics.trim())); }); + child.send(config); }); } -function stopChild(pid) { - if (!pid) return; - try { - process.kill(pid, 'SIGTERM'); - } catch { - // The child may have exited while Tailscale was being configured. - } -} - -async function launch(args) { - if (!args.file) throw new PreviewError('缺少要展示的文件'); - validPort(args.port, 'port'); - validPort(args.localPort, 'local-port'); - validTtl(args.ttl); - - const filePath = path.resolve(args.file); - let info; - try { - info = fs.statSync(filePath); - } catch { - throw new PreviewError(`输入文件不存在:${filePath}`); - } - if (!info.isFile()) throw new PreviewError(`输入不是普通文件:${filePath}`); - - const root = path.dirname(filePath); - const mountPath = args.mountPath ? normalizeMountPath(args.mountPath) : defaultMountPath(root); - const ip = tailscaleIPv4(); - checkTailscaleServe(); - const child = await startDetachedServer(root, mountPath, args.localPort, args.ttl, args.port); - - try { - const result = run('tailscale', [ - 'serve', '--bg', `--http=${args.port}`, `--set-path=${mountPath}`, '--yes', - `http://127.0.0.1:${child.port}`, - ]); - if (result.status !== 0) { - throw new PreviewError(`Tailscale Serve 配置失败:${(result.stderr || result.stdout).trim() || 'serve 命令失败'}`); +async function launch(config) { + const root = path.dirname(config.file); + const key = crypto.createHash('sha256').update(JSON.stringify(config)).digest('hex'); + const stateDir = path.join(os.tmpdir(), 'previewer-' + (process.getuid?.() ?? os.userInfo().username)); + fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 }); + const statePath = path.join(stateDir, key + '.json'); + const lockPath = statePath + '.lock'; + let locked = false; + for (let attempt = 0; attempt < 120; attempt++) { + try { fs.mkdirSync(lockPath); locked = true; break; } + catch (error) { + if (error.code !== 'EEXIST') throw error; + try { + // Recover an empty lock left by a launcher that crashed. + if (Date.now() - fs.statSync(lockPath).mtimeMs > 15000) fs.rmdirSync(lockPath); + } catch {} + await delay(50); } + } + if (!locked) fail('BUSY', 'Another launcher is starting this preview; retry shortly'); + let childState; + try { + let previous; + try { previous = JSON.parse(fs.readFileSync(statePath, 'utf8')); } catch {} + if (previous && await probe(previous)) return publicResult(previous, true); + childState = await startWorker({ ...config, root, key, statePath, token: crypto.randomUUID() }); + if (!await probe(childState)) fail('VERIFY_FAILED', 'Static server readiness check failed'); + fs.writeFileSync(statePath, JSON.stringify(childState), { mode: 0o600 }); + return publicResult(childState, false); } catch (error) { - stopChild(child.pid); + if (childState?.pid) { try { process.kill(childState.pid, 'SIGTERM'); } catch {} } throw error; + } finally { + fs.rmdirSync(lockPath); } - - const relative = path.relative(root, filePath).split(path.sep).map(encodeURIComponent).join('/'); - const suffix = args.port === 80 ? '' : `:${args.port}`; - const url = `http://${ip}${suffix}${mountPath}/${relative}`; - console.log(JSON.stringify({ - file: filePath, - directory: root, - mountPath, - ip, - port: args.port, - localPort: child.port, - pid: child.pid, - ttl: args.ttl, - expiresAt: new Date(Date.now() + args.ttl * 1000).toISOString(), - url, - stopCommand: `kill ${child.pid} 2>/dev/null || true; tailscale serve --http=${args.port} --set-path=${mountPath} off`, - })); } -async function main() { - const args = parseArgs(process.argv.slice(2)); - if (args.server) { - if (!args.mountPath || !args.root || !args.tailscalePort) throw new PreviewError('内部参数不完整'); - validPort(args.port, 'local-port'); - validPort(args.tailscalePort, 'port'); - validTtl(args.ttl); - serveStatic(path.resolve(args.root), args.mountPath, args.port, args.ttl, args.tailscalePort); - return; +function runWorker(config) { + let shuttingDown = false; + let timer; + let state; + const server = http.createServer((request, response) => { + if (!['GET', 'HEAD'].includes(request.method)) { + response.writeHead(405, { Allow: 'GET, HEAD' }).end('Method not allowed'); + return; + } + let pathname; + try { pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname); } + catch { response.writeHead(400).end('Bad request'); return; } + if (pathname === statusPath) { + if (request.headers['x-previewer-token'] !== config.token) { response.writeHead(404).end('Not found'); return; } + response.setHeader('Content-Type', 'application/json'); + response.end(request.method === 'HEAD' ? undefined : JSON.stringify(state)); + return; + } + let candidate; + try { + const relative = pathname === '/' ? path.basename(config.file) : pathname.replace(/^\/+/, ''); + candidate = fs.realpathSync(path.resolve(config.root, relative)); + const inside = path.relative(config.root, candidate); + if (inside === '..' || inside.startsWith('..' + path.sep) || path.isAbsolute(inside)) { + response.writeHead(403).end('Forbidden'); + return; + } + // Explicit filenames only; no directory listings. + if (!fs.statSync(candidate).isFile()) { response.writeHead(404).end('Not found'); return; } + } catch { response.writeHead(404).end('Not found'); return; } + response.writeHead(200, { + 'Content-Type': types[path.extname(candidate).toLowerCase()] ?? 'application/octet-stream', + 'Cache-Control': 'no-store', + 'X-Content-Type-Options': 'nosniff', + }); + if (request.method === 'HEAD') { response.end(); return; } + fs.createReadStream(candidate).on('error', () => response.destroy()).pipe(response); + }); + function shutdown() { + if (shuttingDown) return; + shuttingDown = true; + clearTimeout(timer); + try { + const record = JSON.parse(fs.readFileSync(config.statePath, 'utf8')); + if (record.pid === process.pid && record.token === config.token) fs.unlinkSync(config.statePath); + } catch {} + server.close(() => process.exit(0)); + setTimeout(() => process.exit(0), 1000).unref(); } - await launch(args); + process.on('SIGTERM', shutdown); + process.on('SIGINT', shutdown); + server.once('error', (error) => { + process.send?.({ code: error.code === 'EADDRINUSE' ? 'PORT_IN_USE' : 'START_FAILED', error: error.message }); + process.exitCode = 2; + }); + server.listen(config.port, config.host, () => { + const port = server.address().port; + state = { + file: config.file, directory: config.root, host: config.host, port, pid: process.pid, + ttl: config.ttl, expiresAt: new Date(Date.now() + config.ttl * 1000).toISOString(), + ...urlsFor(config, port), token: config.token, key: config.key, + }; + timer = setTimeout(shutdown, config.ttl * 1000); + process.send?.(state); + }); } -main().catch((error) => { - console.error(`previewer: ${error.message}`); - process.exitCode = 2; -}); +if (process.argv[2] === '--worker') { + process.once('message', runWorker); +} else if (process.argv.includes('--help') || process.argv.includes('-h')) { + console.log('Usage: node serve_file.js FILE [--host IP] [--port PORT] [--ttl SECONDS]\nServe existing HTML/static assets. Defaults: 127.0.0.1, automatic port, 3600 seconds.'); +} else { + Promise.resolve().then(() => launch(parseArgs(process.argv.slice(2)))).then((result) => { + console.log(JSON.stringify(result)); + }).catch((error) => { + console.error(JSON.stringify({ code: error.code ?? 'PREVIEW_FAILED', message: error.message })); + process.exitCode = 2; + }); +} diff --git a/skills/previewer/tests/serve_file.test.js b/skills/previewer/tests/serve_file.test.js new file mode 100644 index 0000000..cc9d492 --- /dev/null +++ b/skills/previewer/tests/serve_file.test.js @@ -0,0 +1,184 @@ +'use strict'; +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const http = require('node:http'); +const { spawn } = require('node:child_process'); + +const script = path.resolve(__dirname, '../scripts/serve_file.js'); +const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); + +async function invoke(args) { + return new Promise((resolve, reject) => { + // An empty PATH proves there is no dependency on an external networking CLI. + const child = spawn(process.execPath, [script, ...args], { env: { ...process.env, PATH: '' } }); + let stdout = '', stderr = ''; + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + child.once('error', reject); + child.once('close', (code) => resolve({ code, stdout, stderr })); + }); +} + +function request(url, method = 'GET') { + return new Promise((resolve, reject) => { + const req = http.request(url, { method, timeout: 1000 }, (response) => { + let body = ''; + response.on('data', (chunk) => { body += chunk; }); + response.on('end', () => resolve({ status: response.statusCode, headers: response.headers, body })); + response.on('error', reject); + }); + req.on('error', reject); + req.on('timeout', () => req.destroy(new Error('timeout'))); + req.end(); + }); +} + +async function fixture(t) { + const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'previewer-test-')); + const root = path.join(directory, 'site'); + await fs.mkdir(root); + const file = path.join(root, '预览 page.html'); + await fs.writeFile(file, '预览

HTML preview

'); + await fs.writeFile(path.join(root, 'theme.css'), 'body { color: red; }'); + await fs.writeFile(path.join(root, 'app.js'), 'document.title = "preview";'); + await fs.mkdir(path.join(root, 'assets')); + await fs.writeFile(path.join(directory, 'secret.txt'), 'outside-root'); + const pids = new Set(); + t.after(async () => { + for (const pid of pids) { try { process.kill(pid, 'SIGTERM'); } catch {} } + await wait(80); + await fs.rm(directory, { recursive: true, force: true }); + }); + return { + directory, root, file, + async launch(extra = []) { + const result = await invoke([file, '--ttl', '30', ...extra]); + assert.equal(result.code, 0, result.stderr); + assert.equal(result.stderr, ''); + const state = JSON.parse(result.stdout); + pids.add(state.pid); + return state; + }, + track(state) { pids.add(state.pid); }, + }; +} + +test('serves existing HTML, relative assets and HEAD without network tools', async (t) => { + const f = await fixture(t); + const state = await f.launch(); + assert.equal(state.host, '127.0.0.1'); + assert.equal(state.reused, false); + assert.ok(state.port > 0); + assert.equal('token' in state, false); + assert.equal('ip' in state, false); + assert.match(state.stopCommand, /^kill -TERM \d+$/); + const html = await request(state.url); + assert.equal(html.status, 200); + assert.match(html.headers['content-type'], /^text\/html/); + assert.match(html.body, /HTML preview/); + assert.match((await request(new URL('/', state.url))).body, /HTML preview/); + const css = await request(new URL('theme.css', state.url)); + assert.equal(css.status, 200); + assert.match(css.headers['content-type'], /^text\/css/); + assert.match(css.body, /color: red/); + const js = await request(new URL('app.js', state.url)); + assert.equal(js.status, 200); + assert.match(js.headers['content-type'], /^text\/javascript/); + assert.equal((await request(state.url, 'HEAD')).body, ''); + assert.equal((await request(state.url, 'POST')).status, 405); + assert.equal((await request(new URL('assets/', state.url))).status, 404); +}); + +test('sequential and concurrent calls reuse a verified service without extending TTL', async (t) => { + const f = await fixture(t); + const first = await f.launch(); + const again = await f.launch(); + assert.equal(again.reused, true); + assert.equal(again.pid, first.pid); + assert.equal(again.url, first.url); + assert.equal(again.expiresAt, first.expiresAt); + const concurrent = await Promise.all(Array.from({ length: 4 }, () => f.launch())); + for (const state of concurrent) { + assert.equal(state.pid, first.pid); + assert.equal(state.reused, true); + assert.equal(state.expiresAt, first.expiresAt); + } + // Race the first launch too, not just reuse of an already running worker. + const other = path.join(f.root, 'second.html'); + await fs.writeFile(other, '

second

'); + const created = await Promise.all(Array.from({ length: 4 }, () => invoke([other, '--ttl', '30']))); + const states = created.map((result) => { + assert.equal(result.code, 0, result.stderr); + const state = JSON.parse(result.stdout); + f.track(state); + return state; + }); + assert.equal(new Set(states.map((state) => state.pid)).size, 1); + assert.equal(states.filter((state) => state.reused === false).length, 1); +}); + +test('occupied port fails instead of replacing its owner', async (t) => { + const f = await fixture(t); + const first = await f.launch(); + const other = path.join(f.root, 'other.html'); + await fs.writeFile(other, '

other

'); + const conflict = await invoke([other, '--port', String(first.port), '--ttl', '30']); + assert.equal(conflict.code, 2); + assert.equal(conflict.stdout, ''); + assert.equal(JSON.parse(conflict.stderr).code, 'PORT_IN_USE'); + assert.equal((await request(first.url)).status, 200); +}); + +test('outside symlinks, traversal and private status endpoint cannot disclose files', async (t) => { + const f = await fixture(t); + await fs.symlink(path.join(f.directory, 'secret.txt'), path.join(f.root, 'external.txt')); + const state = await f.launch(); + const symlink = await request(new URL('external.txt', state.url)); + assert.equal(symlink.status, 403); + const traversal = await request(new URL('/..%2fsecret.txt', state.url)); + assert.equal(traversal.status, 403); + assert.equal((await request(new URL('/.previewer-status', state.url))).status, 404); + assert.equal((await request(new URL('/%ZZ', state.url))).status, 400); +}); + +test('expiry stops the service and a later call creates a fresh preview', async (t) => { + const f = await fixture(t); + const first = await f.launch(['--ttl', '1']); + const deadline = Date.now() + 4000; + let stopped = false; + while (Date.now() < deadline) { + try { await request(first.url); } catch { stopped = true; break; } + await wait(80); + } + assert.equal(stopped, true); + const next = await f.launch(['--ttl', '1']); + assert.equal(next.reused, false); + assert.notEqual(next.pid, first.pid); + assert.notEqual(next.expiresAt, first.expiresAt); +}); + +test('all-interface preview uses only Node and lists local access URLs', async (t) => { + const f = await fixture(t); + const state = await f.launch(['--host', '0.0.0.0']); + assert.equal(state.host, '0.0.0.0'); + assert.match(state.url, /^http:\/\/127\.0\.0\.1:/); + assert.ok(state.urls.includes(state.url)); + assert.equal((await request(state.url)).status, 200); +}); + +test('invalid inputs and removed options return structured errors without starting servers', async () => { + for (const args of [ + [], ['/missing/preview.html'], [__filename, '--port', '65536'], + [__filename, '--ttl', '0'], [__filename, '--ttl', '2147484'], + [__filename, '--host', 'not-an-ip'], [__filename, '--host'], + [__filename, '--mount-path', '/preview/test'], [__filename, '--tailscale-port', '80'], + ]) { + const result = await invoke(args); + assert.equal(result.code, 2); + assert.equal(result.stdout, ''); + assert.ok(['ARGUMENT', 'FILE_INVALID'].includes(JSON.parse(result.stderr).code)); + } +}); diff --git a/skills/product-prototype/README.md b/skills/product-prototype/README.md index ac0d894..b06806e 100644 --- a/skills/product-prototype/README.md +++ b/skills/product-prototype/README.md @@ -84,6 +84,10 @@ npm test # 离线合约 + mock + Playwright 关键交互与 ## 四类数据与审核 +默认按用户动线阅读:第一栏展示完整首页,后续每栏展示一个用户任务的完整页面和主要连线。 +例如「广场与关注」一栏并排展示广场首页、关注页、创建关注;「文章写作」另起一栏。 +左侧目录可以直接定位到对应动线,总关系画布保留为辅助视图。 + - `requirements.md` 描述目标、场景和验收上下文,供作者、Agent 和评审阅读。 - `flow.json` 声明 page/dialog/state 节点及 Action/条件边,是导航唯一事实来源;组件只能发出 registry 中的 Action ID。 diff --git a/skills/product-prototype/SKILL.md b/skills/product-prototype/SKILL.md index a0bfd1e..85be925 100644 --- a/skills/product-prototype/SKILL.md +++ b/skills/product-prototype/SKILL.md @@ -43,6 +43,9 @@ description: >- mock 检查和 Playwright 交互/三视口检查。测试产物只写入 `.prototype-artifacts/`。 7. 增量变更按稳定 ID 维护 flow、layout、review 和相关实现/截图;新增、修改、删除都必须同步 引用并做离线 diff,不能重编号或漂移无关节点。删除前要报告受影响的边、布局和批注。 +8. 默认按用户动线分栏评审,先读 [journeys.md](references/journeys.md):首栏为完整首页, + 后续每栏一个用户任务,横向展示完整页面与本栏主要连线;其它动线另起一栏。 + 分组写入 layout.groups,导航仍由 flow 唯一驱动。总关系图只能作为辅助视图。 ## 输入与输出 @@ -68,6 +71,7 @@ description: >- - `SKILL.md` 的 frontmatter 名称与目录一致,README 和 references 链接可读。 - 模板有锁定的 npm 依赖声明、React/TypeScript/React Flow 入口、本地样式和四类源数据;Studio 可查看节点/边、预览 runtime、保存/恢复 layout 并导出 review。 +- 默认预览有首页全貌、独立用户动线栏、真实页面展示与组内连线;没有贯穿不同动线的连线。 - `init` 重复运行不会覆盖已有源数据;静态检查失败时返回非零码并指出文件。 - `validate`、离线合约、增量检查和 TypeScript/Vite build 可复核;浏览器截图与 Playwright 结果 必须按实际环境报告,未运行或因宿主环境失败的项目只能记录为 test gap。 diff --git a/skills/product-prototype/assets/studio-template/prototype/layout.json b/skills/product-prototype/assets/studio-template/prototype/layout.json index b66d8a1..914486b 100644 --- a/skills/product-prototype/assets/studio-template/prototype/layout.json +++ b/skills/product-prototype/assets/studio-template/prototype/layout.json @@ -1,6 +1,13 @@ { "layoutVersion": 1, "viewport": { "x": 0, "y": 0, "zoom": 1 }, + "groups": { + "journey.home": { "label": "首页", "nodeIds": ["page.studio-placeholder"] }, + "journey.device-create": { "label": "创建设备", "nodeIds": ["page.device-list", "page.device-create", "page.device-config", "state.device-connecting", "state.device-connected", "page.device-detail"] }, + "journey.device-retry": { "label": "连接失败与重试", "nodeIds": ["state.device-connection-failed", "state.device-connecting", "state.device-connected"] }, + "journey.device-empty": { "label": "从空列表开始", "nodeIds": ["state.device-empty", "page.device-create"] }, + "journey.help": { "label": "帮助与空状态", "nodeIds": ["dialog.studio-help", "state.studio-empty"] } + }, "nodes": { "page.studio-placeholder": { "x": 80, "y": 80 }, "dialog.studio-help": { "x": 420, "y": 40 }, diff --git a/skills/product-prototype/assets/studio-template/scripts/snapshot.mjs b/skills/product-prototype/assets/studio-template/scripts/snapshot.mjs index fc9430d..1a07371 100644 --- a/skills/product-prototype/assets/studio-template/scripts/snapshot.mjs +++ b/skills/product-prototype/assets/studio-template/scripts/snapshot.mjs @@ -41,7 +41,17 @@ try { screenshots.push({ scene: "device-management", scenario: scene === "failed" ? "retry-success" : scene === "empty" ? "empty" : "normal", page: scene, nodeId: testId.replace("device-page-", ""), viewport, path: `snapshots/${file}`, bytes: stat.size }); } finally { await page.close(); } } - if (screenshots.length !== viewports.length * pages.length) fail("MANIFEST_INCOMPLETE", "not every page/viewport pair produced a screenshot"); + for (const viewport of viewports) { + const page = await browser.newPage({ viewport: { width: viewport.width, height: viewport.height } }); + try { + await page.goto(server.url, { waitUntil: "networkidle" }); + await page.getByTestId("journey-board").waitFor(); + const file = "journeys." + viewport.name + ".png"; + await page.screenshot({ path: path.join(staging, file), fullPage: true, animations: "disabled" }); + screenshots.push({ scene: "journeys", groupIds: Object.keys(JSON.parse(await fs.readFile(path.join(root, "prototype/layout.json"), "utf8")).groups ?? {}), viewport, path: "snapshots/" + file, bytes: (await fs.stat(path.join(staging, file))).size }); + } finally { await page.close(); } + } + if (screenshots.length !== viewports.length * (pages.length + 1)) fail("MANIFEST_INCOMPLETE", "not every page/viewport pair produced a screenshot"); const manifest = { version: 1, status: "generated", generatedBy: "npm run snapshot", baseUrl: server.url, screenshots }; await fs.mkdir(outputDir, { recursive: true }); await fs.rm(outputDir, { recursive: true, force: true }); await fs.rename(staging, outputDir); await fs.writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); console.log(`snapshot: OK (${screenshots.length} actual screenshots)`); console.log(`manifest: ${manifestPath}`); @@ -49,7 +59,7 @@ try { finally { if (!shuttingDown) await cleanup(); } async function driveToScene(page, url, scene) { - await page.goto(url, { waitUntil: "networkidle", timeout: 20_000 }); await page.locator("[data-testid='flow-node-page.studio-placeholder']").waitFor({ state: "attached", timeout: 10_000 }); + await page.goto(url + "/?view=graph", { waitUntil: "networkidle", timeout: 20_000 }); await page.locator("[data-testid='flow-node-page.studio-placeholder']").waitFor({ state: "attached", timeout: 10_000 }); if (scene === "failed") await page.getByTestId("device-scenario").selectOption("retry-success", { force: true }); await page.getByTestId("dispatch-device.open-management").click(); await page.getByTestId("device-page-list").waitFor(); if (scene === "list") return; if (scene === "empty") { await page.getByTestId("device-scenario").selectOption("empty", { force: true }); return; } diff --git a/skills/product-prototype/assets/studio-template/scripts/validate.mjs b/skills/product-prototype/assets/studio-template/scripts/validate.mjs index 7a73e2a..eba2a9c 100644 --- a/skills/product-prototype/assets/studio-template/scripts/validate.mjs +++ b/skills/product-prototype/assets/studio-template/scripts/validate.mjs @@ -118,6 +118,17 @@ function validateFlow(flow) { function validateLayout(layout, nodes) { const file = "layout.json"; if (!isObject(layout) || layout.layoutVersion !== 1 || !isObject(layout.viewport) || !isObject(layout.nodes) || typeof layout.viewport.x !== "number" || !Number.isFinite(layout.viewport.x) || typeof layout.viewport.y !== "number" || !Number.isFinite(layout.viewport.y) || typeof layout.viewport.zoom !== "number" || !Number.isFinite(layout.viewport.zoom) || layout.viewport.zoom <= 0) { push(file, "layout", "SCHEMA_INVALID", "layout requires version 1, viewport and nodes"); return; } + if (layout.groups !== undefined) { + if (!isObject(layout.groups)) push(file, "groups", "SCHEMA_INVALID", "groups must be an object"); + else for (const [id, group] of Object.entries(layout.groups)) { + if (!isObject(group) || !Array.isArray(group.nodeIds) || !group.nodeIds.length) { + push(file, id, "SCHEMA_INVALID", "group requires non-empty nodeIds"); + continue; + } + duplicateId(group.nodeIds, file, "group node"); + for (const nodeId of group.nodeIds) if (!nodes.has(nodeId)) push(file, nodeId, "DANGLING_REFERENCE", "group references unknown node"); + } + } for (const [id, position] of Object.entries(layout.nodes)) { if (!nodes.has(id)) push(file, id, "DANGLING_REFERENCE", `layout node ${id} does not exist in flow`); if (!isObject(position) || typeof position.x !== "number" || !Number.isFinite(position.x) || typeof position.y !== "number" || !Number.isFinite(position.y)) push(file, id, "SCHEMA_INVALID", `layout node ${id} requires finite x/y coordinates`); diff --git a/skills/product-prototype/assets/studio-template/src/App.tsx b/skills/product-prototype/assets/studio-template/src/App.tsx index e1739dd..2284441 100644 --- a/skills/product-prototype/assets/studio-template/src/App.tsx +++ b/skills/product-prototype/assets/studio-template/src/App.tsx @@ -13,6 +13,7 @@ import { addReviewComment, exportReview, reviewTargetLabel, updateReviewStatus } import { createNavigationRuntime, type DispatchResult } from "./runtime"; import { DeviceManagementPreview, isDevicePreview } from "./examples/device-management/DeviceManagementPreview"; import { createDeviceMock, reduceDeviceMock, type DeviceDraft, type DeviceScenario } from "./mocks/device-management"; +import { JourneyBoard } from "./studio/JourneyBoard"; const flow = flowSource as FlowDocument; const initialLayout = layoutSource as LayoutDocument; @@ -50,6 +51,7 @@ function StudioApp() { const runtime = useMemo(() => createNavigationRuntime(flow), []); const [nodes, setNodes] = useState[]>(() => layoutNodes(flow, initialLayout)); const [viewport, setViewport] = useState(initialLayout.viewport); + const [layoutGroups, setLayoutGroups] = useState(initialLayout.groups); const [selectedNodeId, setSelectedNodeId] = useState(flow.startNodeId); const [selectedEdgeId, setSelectedEdgeId] = useState(null); const [currentNodeId, setCurrentNodeId] = useState(flow.startNodeId); @@ -93,8 +95,8 @@ function StudioApp() { const dispatch = (edge: FlowEdge) => dispatchAction(edge.actionId); const changeDeviceScenario = (scenario: DeviceScenario) => { const nextMock = createDeviceMock(scenario); setDeviceScenario(scenario); setDeviceMock(nextMock); setDeviceDraft(nextMock.draft); setDeviceFormErrors([]); setRuntimeError(false); setRuntimeMessage(`Device mock scenario: ${scenario}`); }; const updateDeviceDraft = (patch: Partial) => { setDeviceDraft((current) => ({ ...current, ...patch })); setDeviceFormErrors([]); }; - const saveLayout = () => { downloadText("layout.json", serializeLayout(captureLayout(nodes, viewport))); setRuntimeError(false); setRuntimeMessage("layout.json exported from current node coordinates and viewport."); }; - const restoreLayout = async (file: File) => { try { const next = parseLayout(await file.text(), flow); setNodes(layoutNodes(flow, next)); setViewport(next.viewport); setRuntimeError(false); setRuntimeMessage("layout.json restored; coordinates are keyed by stable node ID."); } catch (error) { setRuntimeError(true); setRuntimeMessage(error instanceof Error ? error.message : "LAYOUT_INVALID: unable to restore layout.json"); } }; + const saveLayout = () => { downloadText("layout.json", serializeLayout(captureLayout(nodes, viewport, layoutGroups))); setRuntimeError(false); setRuntimeMessage("layout.json exported from current node coordinates and viewport."); }; + const restoreLayout = async (file: File) => { try { const next = parseLayout(await file.text(), flow); setNodes(layoutNodes(flow, next)); setViewport(next.viewport); setLayoutGroups(next.groups); setRuntimeError(false); setRuntimeMessage("layout.json restored; coordinates are keyed by stable node ID."); } catch (error) { setRuntimeError(true); setRuntimeMessage(error instanceof Error ? error.message : "LAYOUT_INVALID: unable to restore layout.json"); } }; const addComment = () => { const target = selectedTarget(selectedNodeId, selectedEdgeId); if (!target || !commentBody.trim()) return; try { setReview((current) => addReviewComment(current, flow, { id: `comment.${current.comments.length + 1}`, body: commentBody.trim(), target, status: "open", author: "Studio" })); setCommentBody(""); setRuntimeError(false); setRuntimeMessage(`Review comment attached to ${reviewTargetLabel(target)}.`); } @@ -102,6 +104,19 @@ function StudioApp() { }; const exportReviewFile = () => { try { const next = updateReviewStatus(review, reviewStatus); setReview(next); downloadText("review.json", exportReview(next, flow)); setRuntimeError(false); setRuntimeMessage("review.json exported with stable node/edge targets."); } catch (error) { setRuntimeError(true); setRuntimeMessage(error instanceof Error ? error.message : "DANGLING_TARGET: review export rejected"); } }; const previewNode = selectedNode ?? currentNode; + if (Object.keys(initialLayout.groups ?? {}).length && new URLSearchParams(window.location.search).get("view") !== "graph") { + return { window.location.search = "?view=graph"; }} + prepareAction={(actionId) => { + if (!actionId.startsWith("device.")) return { showEmpty }; + const result = reduceDeviceMock(deviceMock, actionId, deviceDraft); + setDeviceMock(result.state); setDeviceDraft(result.state.draft); setDeviceFormErrors(result.errors); + return result.ok ? { ...result.context, showEmpty, deviceScenario, deviceExists: result.state.devices.length > 0 } : null; + }} + renderScreen={(node, available, onAction) => isDevicePreview(node) + ? + :

{node.title}

{node.description}

{node.thumbnail ? {node.title} : null}{available.map((edge) => )}
} + />; + } return

PRODUCT PROTOTYPE / T3

Prototype Studio

offline · flow-driven { const file = event.target.files?.[0]; if (file) void restoreLayout(file); event.target.value = ""; }} />
diff --git a/skills/product-prototype/assets/studio-template/src/layout/index.ts b/skills/product-prototype/assets/studio-template/src/layout/index.ts index 09595fc..97f6d35 100644 --- a/skills/product-prototype/assets/studio-template/src/layout/index.ts +++ b/skills/product-prototype/assets/studio-template/src/layout/index.ts @@ -17,7 +17,7 @@ export function layoutNodes(flow: FlowDocument, layout: LayoutDocument): ReactFl }); } -export function captureLayout(nodes: Array>, viewport: Viewport): LayoutDocument { +export function captureLayout(nodes: Array>, viewport: Viewport, groups?: LayoutDocument["groups"]): LayoutDocument { const result: Record = {}; nodes.forEach((node) => { result[node.id] = { @@ -27,7 +27,7 @@ export function captureLayout(nodes: Array void) => ReactNode; + onOpenGraph: () => void; + prepareAction?: (actionId: string) => Record | null; +} + +export function JourneyBoard({ title, flow, layout, renderScreen, onOpenGraph, prepareAction }: JourneyBoardProps) { + const runtime = createNavigationRuntime(flow); + const groups = Object.entries(layout.groups ?? {}).map(([id, group]) => ({ id, ...group })); + const [activeGroup, setActiveGroup] = useState(groups[0]?.id ?? ""); + const [previewId, setPreviewId] = useState(null); + const [message, setMessage] = useState(""); + const [error, setError] = useState(false); + const [inspection, setInspection] = useState(false); + const preview = flow.nodes.find((node) => node.id === previewId); + + function act(sourceId: string, actionId: string) { + const context = prepareAction ? prepareAction(actionId) : {}; + if (context === null) return; + const result = runtime.dispatch(sourceId, actionId, context); + setError(!result.ok); + if (result.ok) { + setPreviewId(result.nodeId); + setMessage(""); + } else { + setMessage(result.error.code + ": " + result.error.message); + } + } + + return
+ +
+

用户动线预览

{title}

从首页开始,每一栏看完一条完整动线。点击页面中的操作,可单独体验跳转。
{groups.length} 组动线 · {flow.nodes.length} 个页面与状态
+ {groups.map((group, groupIndex) => { + const groupNodes = group.nodeIds.map((id) => flow.nodes.find((node) => node.id === id)).filter((node): node is FlowNode => Boolean(node)); + return
+
{String(groupIndex + 1).padStart(2, "0")}

{group.label ?? group.id}

{groupIndex === 0 ? "首页全貌" : groupNodes.map((node) => node.title).join(" → ")}

{groupNodes.length} 个画面
+
+ {groupNodes.map((node, index) => { + const next = groupNodes[index + 1]; + const edge = next ? flow.edges.find((item) => item.source === node.id && item.target === next.id) : undefined; + return
+
+
{String(index + 1).padStart(2, "0")}

{node.title}

+
{renderScreen(node, runtime.outgoing(node.id), (actionId) => act(node.id, actionId))}
+
+ {edge ?
{edge.label ?? edge.actionId}
: next ?
: null} +
; + })} +
+
; + })} +
+ {preview ?
setPreviewId(null)}>
event.stopPropagation()}> +

交互预览

{preview.title}

+
{renderScreen(preview, runtime.outgoing(preview.id), (actionId) => act(preview.id, actionId))}
+
setInspection(event.currentTarget.open)}>页面与交互信息{preview.id}
    {runtime.outgoing(preview.id).map((edge) =>
  • {edge.label} → {flow.nodes.find((node) => node.id === edge.target)?.title}
  • )}
+
: null} + {message ?
{message}
: null} +
; +} diff --git a/skills/product-prototype/assets/studio-template/src/studio/journeys.css b/skills/product-prototype/assets/studio-template/src/studio/journeys.css new file mode 100644 index 0000000..aeb4ca3 --- /dev/null +++ b/skills/product-prototype/assets/studio-template/src/studio/journeys.css @@ -0,0 +1,60 @@ +:root { --journey-paper: #f5f5f2; --journey-ink: #242b31; --journey-muted: #747d85; --journey-rule: #dddfdf; } +.journey-shell { min-height: 100vh; background: var(--journey-paper); color: var(--journey-ink); font-family: "PingFang SC", system-ui, sans-serif; } +.journey-sidebar { position: fixed; inset: 0 auto 0 0; width: 208px; padding: 32px 18px; background: #fff; border-right: 1px solid var(--journey-rule); overflow-y: auto; } +.journey-wordmark { display: block; color: var(--journey-ink); text-decoration: none; font-weight: 700; font-size: 18px; } +.journey-caption { margin: 36px 12px 12px; color: var(--journey-muted); font-size: 12px; } +.journey-sidebar nav { display: grid; gap: 5px; } +.journey-sidebar nav a { display: flex; gap: 12px; padding: 11px 12px; border-radius: 5px; color: #505a64; text-decoration: none; font-size: 14px; } +.journey-sidebar nav a span { color: #90979d; font-size: 12px; line-height: 21px; } +.journey-sidebar nav a:hover, .journey-sidebar nav a[aria-current] { background: #edf0ee; color: #293f35; } +.journey-graph-button { margin: 30px 12px 0; padding: 0; border: 0; border-radius: 0; background: transparent; color: #6a756f; font-size: 12px; } +.journey-graph-button:hover { background: transparent; color: #243b2f; } +.journey-content { margin-left: 208px; padding: 38px 36px 100px; min-width: 0; } +.journey-header { display: flex; justify-content: space-between; align-items: flex-end; gap: 20px; padding-bottom: 36px; } +.journey-header p { margin: 0 0 10px; color: var(--journey-muted); font-size: 13px; } +.journey-header h1 { margin: 0 0 12px; font-size: 28px; font-weight: 650; letter-spacing: -.03em; } +.journey-header span { color: var(--journey-muted); font-size: 13px; line-height: 1.8; } +.journey-header > small { color: var(--journey-muted); font-size: 12px; white-space: nowrap; } +.journey-section { scroll-margin-top: 24px; border-top: 1px solid var(--journey-rule); padding: 28px 0 32px; } +.journey-section-heading { display: flex; align-items: flex-start; gap: 14px; margin-bottom: 24px; } +.journey-number { font-size: 13px; color: #87928b; padding-top: 5px; font-variant-numeric: tabular-nums; } +.journey-section-heading h2 { font-size: 19px; margin: 0; font-weight: 650; } +.journey-section-heading p { font-size: 12px; color: var(--journey-muted); margin: 7px 0 0; line-height: 1.6; } +.journey-section-heading > small { margin-left: auto; padding-top: 5px; color: var(--journey-muted); white-space: nowrap; } +.journey-strip { display: flex; overflow-x: auto; align-items: flex-start; padding: 0 1px 16px; scrollbar-color: #c7cec9 transparent; } +.journey-step { display: flex; flex: 0 0 auto; align-items: flex-start; } +.journey-screen { width: 340px; min-width: 0; border: 1px solid #d5dad6; background: white; border-radius: 7px; overflow: hidden; } +.journey-screen-heading { display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-bottom: 1px solid #e6e9e6; color: #26342c; } +.journey-screen-heading span { color: #9aaba0; font-size: 12px; } +.journey-screen-heading h3 { margin: 0; font-size: 13px; font-weight: 600; } +.journey-screen-heading button { margin-left: auto; padding: 0 3px; border: 0; background: transparent; color: #718278; font-size: 20px; } +.journey-screen-body { min-height: 260px; } +.journey-connector { display: flex; flex-direction: column; align-items: center; justify-content: center; width: 64px; margin-top: 150px; color: #74877b; } +.journey-connector span { max-width: 88px; font-size: 11px; line-height: 1.6; text-align: center; } +.journey-connector b { font-size: 34px; font-weight: 400; } +.journey-spacer { width: 40px; } +.journey-overlay { position: fixed; inset: 0; z-index: 100; padding: 32px 16px; background: #13241c80; display: flex; align-items: flex-start; justify-content: center; overflow: auto; } +.journey-preview { width: 480px; max-width: 100%; padding: 18px; background: var(--journey-paper); border-radius: 8px; } +.journey-preview > header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 16px; } +.journey-preview > header p { color: #78857b; margin: 0 0 4px; font-size: 12px; } +.journey-preview h2 { margin: 0; font-size: 19px; } +.journey-preview > header button, .journey-message button { color: #3d5043; background: white; border: 1px solid #cdd7cf; } +.journey-preview details { color: #748277; margin-top: 16px; font-size: 12px; } +.journey-preview code { color: #546b5b; } +.journey-preview ul { padding-left: 20px; } +.journey-message { position: fixed; bottom: 20px; right: 20px; z-index: 110; padding: 14px; color: #6a3128; background: #fff9f5; border: 1px solid #cfa99d; font-size: 13px; max-width: calc(100vw - 40px); } +.journey-message button { margin-left: 12px; } +@media (max-width: 800px) { + .journey-sidebar { position: relative; width: auto; padding: 20px; border-right: 0; border-bottom: 1px solid var(--journey-rule); } + .journey-caption { display: none; } + .journey-sidebar nav { display: flex; overflow-x: auto; margin-top: 16px; } + .journey-sidebar nav a { flex: 0 0 auto; font-size: 13px; } + .journey-graph-button { margin: 16px 0 0; } + .journey-content { margin-left: 0; padding: 26px 20px 60px; } + .journey-header { display: block; padding-bottom: 25px; } + .journey-header h1 { font-size: 25px; } + .journey-header > small { display: block; margin-top: 14px; } + .journey-screen { width: min(390px, calc(100vw - 42px)); } + .journey-connector { width: 72px; } + .journey-section-heading p { max-width: 260px; } +} diff --git a/skills/product-prototype/assets/studio-template/tests/e2e/device-management.spec.ts b/skills/product-prototype/assets/studio-template/tests/e2e/device-management.spec.ts index 653fe32..ce71f90 100644 --- a/skills/product-prototype/assets/studio-template/tests/e2e/device-management.spec.ts +++ b/skills/product-prototype/assets/studio-template/tests/e2e/device-management.spec.ts @@ -1,7 +1,7 @@ import { expect, test, type Page } from "@playwright/test"; async function openDeviceManagement(page: Page) { - await page.goto("/"); + await page.goto("/?view=graph"); await expect(page.getByTestId("flow-node-page.studio-placeholder")).toBeAttached(); await page.getByTestId("dispatch-device.open-management").click(); await expect(page.getByTestId("device-page-list")).toBeVisible(); @@ -61,7 +61,7 @@ test("device empty state is visible and can start creation", async ({ page }) => test("Studio loads the real flow canvas at desktop/tablet/mobile viewports", async ({ page }) => { for (const viewport of [{ name: "desktop", width: 1440, height: 900 }, { name: "tablet", width: 1024, height: 900 }, { name: "mobile", width: 390, height: 844 }]) { await page.setViewportSize({ width: viewport.width, height: viewport.height }); - await page.goto("/"); + await page.goto("/?view=graph"); await expect(page.getByTestId("flow-node-page.studio-placeholder")).toBeAttached(); await expect(page.getByTestId("runtime-status")).toContainText("Ready"); } diff --git a/skills/product-prototype/assets/studio-template/tests/e2e/journeys.spec.ts b/skills/product-prototype/assets/studio-template/tests/e2e/journeys.spec.ts new file mode 100644 index 0000000..b90a044 --- /dev/null +++ b/skills/product-prototype/assets/studio-template/tests/e2e/journeys.spec.ts @@ -0,0 +1,24 @@ +import { expect, test } from "@playwright/test"; + +test("default preview separates homepage and complete task screens", async ({ page }) => { + await page.goto("/"); + await expect(page.getByTestId("journey-board")).toBeVisible(); + await expect(page.getByTestId("journey.home").locator(".journey-screen")).toHaveCount(1); + await expect(page.getByTestId("journey.device-create").locator(".journey-screen")).toHaveCount(6); + const connectorGroups = await page.getByTestId("journey-connector").evaluateAll((lines) => + lines.every((line) => { + const section = line.closest(".journey-section"); + return [line.getAttribute("data-source"), line.getAttribute("data-target")] + .every((id) => [...(section?.querySelectorAll("[data-node-id]") ?? [])].some((screen) => screen.getAttribute("data-node-id") === id)); + })); + expect(connectorGroups).toBe(true); + await page.getByTestId("journey.device-create").getByTestId("device-action-device.create").first().click(); + await expect(page.getByRole("dialog").getByTestId("device-page-create")).toBeVisible(); + await page.getByRole("dialog").getByTestId("device-name").fill("动线设备"); + await page.getByRole("dialog").getByTestId("device-host").fill("10.0.0.8"); + await page.getByRole("dialog").getByTestId("device-action-device.continue-to-config").click(); + await expect(page.getByRole("dialog").getByTestId("device-page-config")).toBeVisible(); + await page.getByRole("button", { name: "关闭 ✕" }).click(); + await page.setViewportSize({ width: 375, height: 844 }); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); +}); diff --git a/skills/product-prototype/references/artifacts.md b/skills/product-prototype/references/artifacts.md index 29524cc..7504d23 100644 --- a/skills/product-prototype/references/artifacts.md +++ b/skills/product-prototype/references/artifacts.md @@ -15,5 +15,7 @@ 都应非零退出。`snapshot` 覆盖 device-management 的 list/create/config/connecting/connected/ failed/detail/empty 八个页面和 desktop/tablet/mobile 三种视口(24 张 PNG),manifest 在全部 截图完成后原子发布,不能用 SVG、占位图或手工假截图代替。 +默认动线视图另生成 desktop/tablet/mobile 三张完整预览,manifest 用 groupIds 记录分组; +设备示例的 24 张页面截图保留在辅助画布视图中生成,总计 27 张。 `npm test` 的 Playwright HTML 报告和失败 trace 写入 `.prototype-artifacts/playwright-report/` 及 `test-results/`;缺浏览器明确失败,不会被跳过。 diff --git a/skills/product-prototype/references/data-contract.md b/skills/product-prototype/references/data-contract.md index 542bc42..51e1a35 100644 --- a/skills/product-prototype/references/data-contract.md +++ b/skills/product-prototype/references/data-contract.md @@ -42,6 +42,12 @@ action.device-list.create ## 当前实现与边界 +### 动线展示分组 + +layout.groups 的每个键是稳定动线 ID,值包含 label 和有序 nodeIds。对象声明顺序是目录顺序; +首组为首页。同一节点可被多组引用,组件与导航始终从原 flow 节点解析。完整规则见 +[journeys.md](journeys.md)。分组不新增业务导航,不需要改动无关 flow ID 或原有节点坐标。 + - 已实现:TypeScript contracts、共享 registry、schema/引用/可达性 validator、按稳定 ID 的 layout 合并与冲突检查、React Flow Studio、NavigationRuntime、review 校验/导出、设备管理 页面与确定性 mock,以及离线 `validate`/`build`/`test:incremental` 检查。 diff --git a/skills/product-prototype/references/journeys.md b/skills/product-prototype/references/journeys.md new file mode 100644 index 0000000..5660c58 --- /dev/null +++ b/skills/product-prototype/references/journeys.md @@ -0,0 +1,37 @@ +# 按用户动线评审原型 + +## 默认阅读方式 + +原型默认使用纵向目录和独立动线栏。第一项是完整首页;之后按用户任务拆开,例如 +「广场与关注」展示广场首页、关注页、创建关注,「文章写作」展示列表、编辑、保存、发布。 +每栏横向排列完整页面,栏与栏纵向分隔;窄屏允许该栏独立横向滚动。 + +先根据现有产品明确每栏的用户目标、入口、涉及页面和主要动作,再生成数据和预览。 +不能把整个产品的所有节点和边堆在一张默认总图中,也不能只摆页面名称占位卡片。 + +## 数据规则 + +- 用 layout.json 的 groups 声明稳定分组 ID、label 和有序 nodeIds;首组只放首页。 +- 分组只是展示投影,不产生第二套跳转规则。连接的 source/target/actionId 始终从 flow.json 读取。 +- 同一真实页面可在不同分组重复展示,仍引用相同节点 ID,不复制或重编号 flow 节点。 +- 每栏只画本栏主要前进步骤之间的线;返回、全局导航和跨组跳转保留在 flow/runtime 中。 +- 跨组跳转显示为可点击操作或目标提示,不画穿越其它栏的长线。 +- 辅助空状态、失败状态和非主路径可独立成栏;所有 flow 节点都应可从目录、栏或预览访问。 + +## 模板约定 + +共享 src/studio/JourneyBoard.tsx 接收 flow、layout 和页面渲染回调,读取 groups 展示真实页面。 +应用通过回调提供完整页面组件;点击任意页面中的 Action 时以该页面的节点 ID 为来源, +交给 NavigationRuntime 校验后打开目标预览。默认动线视图,完整 React Flow 画布可作为辅助视图。 + +## 回归示例 + +首页栏:只展示首页全貌,不画出所有全局导航连线。 + +广场与关注栏:广场首页 → 关注页 → 创建关注。只展示这组的主要前进线,取消和返回仍可点击。 + +文章写作栏:稿件列表 → 编辑器 → 发布结果。若用户切换到设置,打开设置预览,不连接到别栏。 + +验收需检查:首组为首页、至少一组多页、每页可读且完整、分组不存在悬空节点, +没有跨组线、重复页面引用同一 flow ID、任意页面上的操作从正确来源解析,移动端栏可滚动。 +截图至少包含首页全貌、一组多页动线和移动端;manifest 记录分组或节点稳定 ID。 diff --git a/skills/product-prototype/scripts/check_structure.py b/skills/product-prototype/scripts/check_structure.py index 8eb74c7..265abeb 100644 --- a/skills/product-prototype/scripts/check_structure.py +++ b/skills/product-prototype/scripts/check_structure.py @@ -18,6 +18,9 @@ REQUIRED = ( "references/commands.md", "references/incremental.md", "references/artifacts.md", + "references/journeys.md", + "assets/studio-template/src/studio/JourneyBoard.tsx", + "assets/studio-template/src/studio/journeys.css", "scripts/init.py", "scripts/check_structure.py", "scripts/check_docs.py", diff --git a/skills/specifier/README.md b/skills/specifier/README.md index 910d71f..4a91fbc 100644 --- a/skills/specifier/README.md +++ b/skills/specifier/README.md @@ -31,8 +31,8 @@ 3. 生成可离线打开的版本化 HTML PRD;保留每个历史版本并记录本轮变更。 4. 根据用户意见反复修改,直到用户明确批准指定版本。 5. 仅在批准后生成 `spec/handoff.yaml`,供 `long-ship` 创建和执行任务。 -6. 用户需要远程查看,或说“把 HTML 渲染出来”时,可调用独立的 `previewer` skill;它用 Node - 渲染并通过 Tailscale 暴露为 HTTP URL,同时返回应该使用的 Tailscale IP。 +6. 用户需要查看 HTML 时,按独立 `previewer` 的契约直接执行共享 Node 脚本,返回 HTTP URL + 和有效期;跨设备查看时可显式设置监听地址。 Specifier 只负责需求规格,不修改业务代码,也不替代 long-ship 的开发和独立测试。 diff --git a/skills/specifier/SKILL.md b/skills/specifier/SKILL.md index 5298797..5814e74 100644 --- a/skills/specifier/SKILL.md +++ b/skills/specifier/SKILL.md @@ -83,10 +83,10 @@ description: >- 6. 按可独立验证的垂直切片拆任务,写出依赖、关键路径、`expected` 和 `verification`, 但不要写入 `.pouch/ack/tasks.yaml` 或本 ship 的 `tasks.yaml`(任务由 long-ship 在批准后创建)。 7. 按模板生成自包含 HTML PRD,并在回复中说明文件路径、版本、待确认问题和下一步。 -8. 用户需要在其它设备查看 HTML,或说“把这个 HTML 渲染出来”时,调用已安装的 - `previewer` 能力传入该文件;不要在 `specifier` 内复制 Node/Tailscale Serve 逻辑。 - previewer 返回结果后,必须把对应 PRD 版本、Tailscale IPv4、完整 HTTP URL、过期时间 - 和停止命令一起给出,并明确说明应使用返回的哪个 IP 访问。 +8. 用户需要查看 HTML,或说“把这个 HTML 渲染出来”时,读取已安装 `previewer` 的调用契约, + 直接执行其共享脚本并传入该文件;不要再次委派 Agent 或在 `specifier` 内复制服务代码。 + 固定文件和参数,保存一次成功 JSON。回复提供对应 PRD 版本、HTTP URL、过期时间和停止命令。 + 跨设备预览时按用户请求指定监听地址;本机回环 URL 仅供同机访问。 如果调研发现需求边界、目标或关键依赖存在两种互相冲突的解释,停止在 `review`,明确列出 冲突,不能自行替用户拍板。 @@ -104,9 +104,9 @@ description: >- 按 [review-loop.md](references/review-loop.md) 记录状态和审计信息。 -如果需要远程预览,读取 `previewer` 的调用契约并把 PRD 文件路径交给它;previewer 不改变 -需求评审状态,HTML 被展示不等于用户批准。回复中要同时给出 Tailscale IP 和 URL,不能只 -说“已经渲染”或只返回本机 `127.0.0.1`。 +如果需要预览,读取 `previewer` 的调用契约并直接执行其共享脚本;previewer 不改变需求 +评审状态,HTML 被展示不等于用户批准。回复提供完整 URL 和有效期;跨设备预览需设置可访问的 +监听地址,不能把本机 `127.0.0.1` 描述为远程访问地址。 ## 批准和 long-ship 交接