Files
claude-code/packages/cloud-artifacts/scripts/test.sh
claude-code-best 084e487943 feat: 新增 artifacts 功能 (#1278)
* feat: 新增 cloud-artifacts 包(Cloudflare Worker HTML artifact 托管)

POST /upload 鉴权上传 HTML 到 R2 返回 hash URL,GET /<7d|30d>/<id>.html
由 Worker 代理读取并直出 text/html。R2 lifecycle rule 自动 7/30 天删除。
独立服务,不被主 CLI 引用(类似 packages/remote-control-server/ 定位)。

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* docs: 完善 cloud-artifacts 文档并统一出口域名

- CLAUDE.md 加 cloud-artifacts 到 Workspace Packages 表和新增 HTML Artifact Hosting 段落
- docs.json 注册 cloud-artifacts 到运行模式 group
- README 加 Quickstart、架构图(含 Deno Deploy 代理层)、Security Considerations、Troubleshooting
- 统一出口域名为 https://cloud-artifacts.claude-code-best.win(wrangler.toml PUBLIC_URL、test.sh 默认 WORKER_URL、所有文档示例)
- test.sh expect() 加 [via body] fallback:经 Deno Deploy 代理(status 抹平为 200)时按 body 的 error 字段断言

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* docs: 修正 CLAUDE.md cloud-artifacts 引用死链

之前指向不存在的 docs/features/cloud-artifacts.md(用户未注册到 docs.json),
改为指向已存在的 packages/cloud-artifacts/README.md,并补充生产出口域名
与 Deno Deploy status 抹平副作用的说明。

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* chore: 同步 cloud-artifacts 测试默认 TOKEN 到新值

用户已通过 wrangler secret put 把生产 TOKEN 改为 claude-code-best,
test.sh 的默认值(之前用旧 token 作 fallback)和注释示例同步更新。
现在直接 bash scripts/test.sh 即可跑通(无需显式传 TOKEN)。

src/index.ts 不依赖具体 token 值(只读 env.TOKEN 做比较),
wrangler.toml 不含 secret,README/.dev.vars.example 用 <your-token>
占位符故无需改。

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* docs: add artifacts feature implementation plan

* feat(artifact): add cloud-artifacts config with token/URL defaults

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add HTTP client with body-error parsing

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add tool name, description, and prompt

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add buildTool definition with file validation

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* test(artifact): add end-to-end tool tests for upload/error paths

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): export ArtifactTool from builtin-tools barrel

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): register ArtifactTool in tools list

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add /use-artifacts bundled skill

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add extractArtifacts message scanner

Scans Message[] for artifact tool_use/tool_result pairs, parses URL/id/expires
from the upload response string, and returns ArtifactInfo[] newest-first.

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* fix(artifact): scanner type narrowing and url regex

- Use double assertion (`as unknown as Record<string, unknown>`) at lines 30
  and 90 to fix TS2352 per project convention
- Tighten URL_REGEX to avoid capturing trailing punctuation (parens,
  quotes, commas) when URL is embedded in text
- Add test case for array-form tool_result content path

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add ArtifactsMenu Ink component

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): add /artifacts slash command entry

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): register /artifacts command

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* fix(artifact): use setClipboard instead of pbcopy for cross-platform support

* fix(artifact): drop userFacingName override so display matches /artifacts

* fix(rcs): add resJson helper to resolve strict mode type errors in tests

Hono Response.json() returns Promise<unknown> under strict TypeScript,
causing 121 TS errors across middleware and routes test files.

Co-Authored-By: glm-5-turbo <zai-org@claude-code-best.win>

* fix(cloud-artifacts): add type stubs so tsc passes without worker-configuration.d.ts

The wrangler-generated worker-configuration.d.ts is gitignored, causing CI to
fail with missing ExportedHandler/Env/R2Bucket types. This file provides minimal
stubs for all Cloudflare Workers types used by the artifact upload Worker.

Co-Authored-By: glm-5-turbo <zai-org@claude-code-best.win>

* fix(query): shallow-copy messages before stripping toolUseResult

Previously the per-query cleanup mutated messagesForQuery entries in
place via `delete msg.toolUseResult`. Those entries are references
shared with mutableMessages (UI state), so the delete stripped the
field from the live message object. The next query can start within
milliseconds of tool_result creation — before the React UI commit
lands — so UserToolSuccessMessage's `!message.toolUseResult` check
returned null and tool.renderToolResultMessage was never called,
leaving tool-result rows blank.

Map to a stripped copy instead so mutableMessages keeps the original
for the UI. Downstream API transformations (applyToolResultBudget,
snip, microcompact) already build new arrays via .map(), so they
compose cleanly with this copy.

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* feat(artifact): show uploaded URL inline below ExecuteExtraTool

Deferred tools (shouldDefer: true) are invoked via SearchExtraTools →
ExecuteExtraTool, so their tool_result rows used to render blank —
the UI looked up ExecuteExtraTool, which had no renderToolResultMessage,
and returned null. Add a generic delegation in ExecuteTool that forwards
renderToolResultMessage to the inner tool when it defines one, unwrapping
the { result, tool_name } envelope and the params from the input shape.
All 28 deferred tools can now render their own UI by defining
renderToolResultMessage.

For ArtifactTool specifically, render the uploaded URL as an OSC 8
hyperlink (Link component) in warning color so it's visually prominent,
with the expiry timestamp on a second line and a separate error branch.
Also add `error: z.string().optional()` to outputSchema — zod's default
strip mode was dropping the field, so error states never reached the UI.

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

* fix(cloud-artifacts): make Env stubs actually take effect in CI

The previous stub file (2e29e362) wrapped `interface Env` in
`declare global { ... }`, but the file has no top-level import/export so
it's a script, not a module. TS2669 forbids `declare global` in scripts,
and in .d.ts files that error is silently swallowed — so the Env stubs
were never merged into the global scope. Locally typecheck passed only
because worker-configuration.d.ts (gitignored) provided Env separately;
in CI / fresh clones, `BUCKET`, `MAX_BYTES`, `DEFAULT_TTL_DAYS`,
`PUBLIC_URL` were all missing on Env.

Drop the wrapper. Top-level `interface Env` in a script .d.ts is already
global ambient and merges with worker-configuration.d.ts via interface
declaration merging, so both environments typecheck cleanly.

Co-Authored-By: glm-5.2 <zai-org@claude-code-best.win>

---------

Co-authored-by: glm-5.2 <zai-org@claude-code-best.win>
2026-06-20 19:52:08 +08:00

163 lines
5.5 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
# cloud-artifacts 端到端测试脚本
# 用法:
# WORKER_URL=https://cloud-artifacts.claude-code-best.workers.dev \
# TOKEN=claude-code-best \
# bash scripts/test.sh
#
# 如本机连不上 workers.dev可通过代理
# HTTPS_PROXY=http://127.0.0.1:7890 bash scripts/test.sh ...
set -uo pipefail
WORKER_URL="${WORKER_URL:-https://cloud-artifacts.claude-code-best.win}"
TOKEN="${TOKEN:-claude-code-best}"
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
# 颜色
G=$'\033[32m'; R=$'\033[31m'; Y=$'\033[33m'; D=$'\033[0m'
# 准备测试 html
echo '<!doctype html><title>t</title><h1>hello v1</h1>' > "$TMP/v1.html"
echo '<!doctype html><title>t</title><h1>hello v2 (overwritten)</h1>' > "$TMP/v2.html"
# 11MB 的 html用于 413 测试)
yes '<p>x</p>' | head -c 11000000 > "$TMP/big.html"
pass=0; fail=0
# expect: 主断言 status code如代理把所有 status 抹平为 200 但 body 仍是 error JSON
# 则按 body 中的 error 字段做 fallback 断言(标 [via body])。
expect() {
local label="$1" want_code="$2" resp="$3" code="$4" body="$5"
if [[ "$code" == "$want_code" ]]; then
printf "${G}✓ %s -> HTTP %s${D}\n" "$label" "$code"
[[ -n "$resp" ]] && printf " body: %s\n" "$body"
pass=$((pass+1))
return
fi
# 代理透传 fallbackHTTP 200 + body 是 {"error":"..."} JSON
if [[ "$code" == "200" && "$body" == {\"error\":* ]]; then
local want_error=""
case "$want_code" in
401) want_error="unauthorized" ;;
415) want_error="unsupported_media_type" ;;
413) want_error="payload_too_large" ;;
404) want_error="not_found" ;;
400) want_error="invalid_" ;; # invalid_ttl 或 invalid_hash前缀匹配
esac
if [[ -z "$want_error" ]] || echo "$body" | grep -q "\"error\":\"$want_error"; then
printf "${G}✓ %s -> HTTP 200 [via body] %s${D}\n" "$label" "$body"
pass=$((pass+1))
return
fi
fi
printf "${R}✗ %s -> HTTP %s (expected %s)${D}\n" "$label" "$code" "$want_code"
printf " body: %s\n" "$body"
fail=$((fail+1))
}
call() {
local label="$1" want="$2"
shift 2
curl -sS -o "$TMP/resp" -w "%{http_code}" "$@" > "$TMP/code"
expect "$label" "$want" "" "$(cat "$TMP/code")" "$(cat "$TMP/resp")"
}
echo "===== 错误用例 ====="
# 1. 401 未授权
call "no token" 401 \
-X POST "$WORKER_URL/upload" \
-H "Content-Type: text/html" --data-binary "@$TMP/v1.html"
# 2. 401 token 错
call "wrong token" 401 \
-X POST "$WORKER_URL/upload" \
-H "Authorization: Bearer wrong" \
-H "Content-Type: text/html" --data-binary "@$TMP/v1.html"
# 3. 415 错误 MIME
call "wrong content-type" 415 \
-X POST "$WORKER_URL/upload" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" --data-binary '{"x":1}'
# 4. 400 invalid_ttl
call "ttl=999" 400 \
-X POST "$WORKER_URL/upload?ttl=999" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: text/html" --data-binary "@$TMP/v1.html"
# 5. 400 invalid_ttl (负数)
call "ttl=0" 400 \
-X POST "$WORKER_URL/upload?ttl=0" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: text/html" --data-binary "@$TMP/v1.html"
# 6. 400 invalid_hash
call "hash=bad/slash" 400 \
-X POST "$WORKER_URL/upload?hash=bad/slash" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: text/html" --data-binary "@$TMP/v1.html"
# 7. 413 payload_too_large (11MB > 10MB)
call "11MB body" 413 \
-X POST "$WORKER_URL/upload" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: text/html" --data-binary "@$TMP/big.html"
# 8. 404 not_found (错路径)
call "wrong path" 404 \
-X POST "$WORKER_URL/notupload" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: text/html" --data-binary "@$TMP/v1.html"
echo
echo "===== 成功用例 ====="
# 9. 200 随机 ID + 7 天(默认)
echo "--- 默认上传(随机 ID + 7 天)---"
curl -sS -o "$TMP/resp" -w "HTTP %{http_code}\n" \
-X POST "$WORKER_URL/upload" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: text/html" --data-binary "@$TMP/v1.html"
cat "$TMP/resp"; echo
RANDOM_ID=$(python3 -c "import json,sys;print(json.load(open('$TMP/resp'))['id'])" 2>/dev/null || echo "")
[[ -n "$RANDOM_ID" ]] && printf "${G}随机 ID: %s${D}\n" "$RANDOM_ID"
# 10. 200 自定义 hash + 30 天
echo "--- 自定义 hash + 30 天 ---"
curl -sS -o "$TMP/resp" -w "HTTP %{http_code}\n" \
-X POST "$WORKER_URL/upload?ttl=30&hash=test-artifact-v1" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: text/html" --data-binary "@$TMP/v1.html"
cat "$TMP/resp"; echo
# 11. 覆盖(同 hash
echo "--- 覆盖:同 hash 上传 v2 ---"
curl -sS -o "$TMP/resp" -w "HTTP %{http_code}\n" \
-X POST "$WORKER_URL/upload?ttl=30&hash=test-artifact-v1" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: text/html" --data-binary "@$TMP/v2.html"
cat "$TMP/resp"; echo
echo
echo "===== R2 写入验证(不走 CDN走 Cloudflare API ====="
# 用 wrangler r2 object get 验证文件实际写入了 R2
if [[ -n "$RANDOM_ID" ]]; then
echo "--- 验证随机 ID 文件存在: 7d/$RANDOM_ID.html ---"
npx wrangler r2 object get "cloud-artifacts/7d/$RANDOM_ID.html" --remote --file "$TMP/got.html" 2>&1 | tail -5
echo "下载内容:" ; cat "$TMP/got.html" 2>/dev/null
fi
echo "--- 验证覆盖后 test-artifact-v1 是 v2 内容 ---"
npx wrangler r2 object get "cloud-artifacts/30d/test-artifact-v1.html" --remote --file "$TMP/got2.html" 2>&1 | tail -5
echo "下载内容:" ; cat "$TMP/got2.html" 2>/dev/null
echo
echo "===== 汇总 ====="
printf "${G}pass=%d${D} ${R}fail=%d${D}\n" "$pass" "$fail"
[[ "$fail" -gt 0 ]] && exit 1 || exit 0