Compare commits

..

9 Commits

Author SHA1 Message Date
liangshuo-1
40840915c7 chore: release v1.0.73 (#1971) 2026-07-20 21:38:05 +08:00
hugang-lark
fb57e17905 feat: check room availability for calendar +update (#1965) 2026-07-20 21:08:55 +08:00
cl900811
4cdfa2fcda feat(whiteboard): enhance whiteboard svg parser (#1970) 2026-07-20 20:56:43 +08:00
anngo-nk
3c2cc273f7 feat(apps): design_html support, creative-design skill, unified TOS publish (#1901)
* feat(apps): add design_html app type support and credential author identity

- Add design_html to appTypePolicies (same as modern_html: skip install/env-pull/skills-sync)
- Route +html-publish via policy (useTOSPublish) instead of hardcoded type check
- Parse commit_author_name/commit_author_email from +git-credential-init response
- Use server-provided author identity for repo-local git config, fallback to defaults
- Support meta_token as identifier in +get command
- Use envvars.AgentName() for source_agent in +create (reads LARKSUITE_CLI_AGENT_NAME)
- Add creative HTML guide reference skeleton and SKILL.md routing entry
- Update git-credential skill docs with new output fields

* fix(apps): unify html-publish to TOS path, add html to init skip policy

- Remove useTOSPublish policy field, html-publish always uses TOS upload
- Add html type to appTypePolicies (skip install/env-pull/skills-sync)
- Remove design_html from policies (not yet in use)
- Fix git credential dry-run test for new local_effects entry

* feat(apps): validate --app-id format to reject meta_token with resolution hint

* feat(apps): integrate creative-design skill and update skill docs

- Add creative-design skill under lark-apps/ (same level as references/)
- Update SKILL.md description with creative design trigger keywords
- Add creative design routing in development path selection table
- Add --path relative path guidance in html-publish reference
- Remove old creative-html-guide skeleton (replaced by creative-design)

* feat(apps): skip app sync for html/modern_html in +init

Add skipAppSync policy field; html and modern_html skip npx app sync
on non-empty repo path since static HTML sites don't need it.

* fix(apps): merge creative-design into html routing and add intent entry

- Merge static HTML and creative-design into one path selection row
- Add creative-design intent routing entry before html-publish

* docs(apps): add html local dev flow, unify publish link source

- Add html端到端 flow in local-dev.md (create → init → dev → release-create)
- Unify publish link source: html and full_stack both use +release-get
- Update SKILL.md routing and publish护栏 accordingly

* fix(apps): update html-publish dry-run and skill docs for TOS flow

- DryRun shows actual 3-step TOS flow (pre_release → TOS PUT → release-create)
- Skill docs: output is release_id, use +release-get to poll for online_url
- Remove references to legacy multipart upload and data.url

* TEMP: pin miaoda-cli alpha and add BOE header for testing

- Pin miaoda-cli to 0.1.24-alpha.fb2cf0a (revert to @latest before merge)
- Add x-tt-env=boe_aily_lark_cli header globally (remove before merge)
- html app-type uses --template design-html instead of --app-type (remove before merge)

* docs(apps): add creative mode link format and meta_token recognition

- Add creative mode (html) link format `https://{tenant}/page/{meta_token}` in publish护栏
- Note dev and publish URLs are the same for creative mode, unlike full_stack
- Add meta_token to app_id resolution with full link format in app_id获取

* docs(apps): route html apps through local-dev git pipeline by default

- Select dev path: html apps now default to local-dev pipeline instead of skipping local/cloud axis
- Intent routing: creative-design publishes via local-dev flow instead of +html-publish
- Remove +html-publish fallback from local-dev "when not to use" section

* docs(apps): generalize skill references to cover both html and full_stack

Remove full_stack-only wording from init, create, list, env-pull, and
release-create references since html apps now share the same local dev
and release flow.

* feat(apps): add meta_token to +get pretty output and dry-run description

* docs(apps): unify html as creative mode, fix routing and local-dev flow

- Remove "HTML" as separate dev path; html and full_stack both go through local-dev
- Intent routing: read local-dev before creative-design to establish git pipeline first
- Mark +html-publish as legacy, redirect to local-dev for creative mode
- Split html local-dev into 3 scenarios: first-time, iteration, pre-generated files
- git add . instead of selective add to capture all creative-design output files

* docs(apps): remove dev link from html-publish output, only return release-get online_url

* fix: add license header to deck-stage.js

* docs(apps): clarify dev link only for full_stack, creative mode shares dev/pub URL

* docs(apps): remove +html-publish from intent routing, description, and guardrails

All HTML apps now go through local-dev pipeline. +html-publish is deprecated.

* docs(apps): remove html-publish references from create/release-create/cloud-dev pages

html-publish is no longer the recommended path for HTML apps; all html
and full_stack apps now follow the same local-dev + release-create flow.

* fix(apps): address PR review feedback

- html-publish dry-run: register all 3 API calls (GET pre_release, PUT TOS, POST release-create) instead of hiding steps in metadata
- validateRealAppID: remove cli_ prefix check (not a valid app_id prefix)
- E2E: update git-credential dry-run to expect 4 local_effects
- E2E: update html-publish dry-run to expect GET pre_release

* fix(apps): address PR review — remove legacy multipart dead code, fix docs

- Delete html_publish_client.go and html_publish_client_test.go (legacy multipart)
- Remove runHTMLPublish, enrichHTMLPublishAPIError, buildHTMLPublishFailureHint
- Migrate tests from runHTMLPublish to prepareHTMLPublishTarball (same coverage)
- Remove cli_ prefix from validateRealAppID (not a valid app_id prefix)
- Fix html-publish.md error wording to match actual message
- Register all 3 TOS API calls in html-publish dry-run
- Update E2E tests for new dry-run contract

* fix(apps): correctly merge SKILL.md with main (role mgmt, auth wording, source boundary)

Rebuild SKILL.md from our branch version, then merge in main's additions:
- description: add HTML静态站点发布, 应用角色与成员管理, 应用角色/角色成员
- 身份与授权: use main's updated wording (no proactive re-login)
- intent routing: add +role-* row, +init refs 平台资源与应用源码边界
- 能力边界 → 平台资源与应用源码边界 (7 rules from main)
- 禁止预授权底线: add role ② and html-publish ③ clauses

* docs(apps): route legacy html-publish only for non-git html apps

* docs(apps): strengthen local-dev routing and git recovery guidance

fix:cherry-pick and resolve conflicts

* fix: gofmt apps_errors.go and apps_errors_test.go

* docs(apps): strengthen git credential recovery and add file-upload guidance

- Generalize git error recovery: any git operation failure triggers
  +git-credential-init refresh, with environment analysis on failure
- Add resource file upload rule: use +file-upload instead of local
  paths, base64 inlining, or git commits; files are app-scoped

* test(apps): strengthen html-publish dry-run assertions for TOS 3-step contract

* fix: 文件资源上传

* docs(apps): update creative-design skill content

* fix: re-add license header to deck-stage.js

* refactor(apps): merge system-prompt.md into SKILL.md for creative-design skill

Consolidate the thin SKILL.md wrapper and the full system-prompt.md
methodology into a single file, eliminating an unnecessary indirection.
Update references in claude.md and codex.md accordingly.

* chore: revert TEMP changes — miaoda-cli back to @latest, remove BOE header

* docs(apps): remove 可见范围 from 发布态护栏

创意模式的可见范围权限走 lark-drive 文档权限体系,而非妙搭应用
权限体系,当前的 +access-scope-set/get 无法正确管理创意模式应用
的可见范围。待文档协作支持妙搭能力后,再通过 lark-drive 域能力
引导修改。

TODO: 等文档协作支持妙搭能力后,在 skill 中加入使用文档域权限
能力修改创意模式可见范围的引导。

* docs(lark-apps): 在平台资源与应用源码边界添加路径规则,引导 agent 使用相对路径

`apps` 命令的 `--path`、`--file`、`--output` 只接受 cwd 下的相对路径,传绝对路径会报错。

* docs(lark-apps): 新增创意模式评论路由和裸 meta_token 识别引导

- 意图路由表新增创意模式应用评论,引导走 lark-drive 文档评论体系
- app_id 获取章节补充裸 meta_token 识别:非链接非 app_ 开头时尝试用 +get 解析

* refactor(apps): flatten creative-design built-in-skills into references

- Delete built-in-skills/ directory (9 nested sub-skill folders)
- Move media skill content to references/ as flat .md files
- Add assets/index.html React+Babel starter template
- Integrate publishing flow into creative-design SKILL.md
- Update harness reference docs (aily/claude/codex.md)
- Simplify lark-apps SKILL.md routing to point directly to creative-design
- Remove creative-design standalone .git directory

* refactor(apps): rename creative-design/SKILL.md to creative-design.md

Avoid being mistaken as an independent skill entry point.
Update all internal references (lark-apps routing table + 10 reference files).

* fix(apps): fail closed when queryAppType fails instead of falling back to full_stack

queryAppType now returns an error instead of silently returning "".
+init aborts if the app type cannot be determined, preventing wrong
scaffold type from being committed and pushed to the repository.

---------

Co-authored-by: zhangli <zhangli.268@bytedance.com>
2026-07-20 20:15:43 +08:00
林晓江(XiaoJiang Lin)
b52677269e [codex] support bot menu events (#1765)
* feat(event): support bot menu event

* fix(event): normalize bot menu timestamp
2026-07-20 20:07:21 +08:00
R0bynZhu
78390f8ea1 chore(slides): update lark-slides skill to 0715 snapshot (#1933)
* chore(slides): update lark-slides skill to 0715 snapshot

* fix: 补回lark-share 内容

* fix: 补回一些内容

* fix: 移除豆包特有工具

* fix: 移除多余的xml版本头

* fix: 补回示例xml头

* fix: remove xml-format-guide
2026-07-20 19:23:05 +08:00
木杉
d6cebd6723 docs: clarify local trigger automation (#1958)
* feat: clarify local trigger automation

* docs: refine trigger automation guidance

* docs: correct trigger release contracts

* docs: separate trigger enable and probe authorization

* docs: link the enable-only trigger path

* test: harden trigger authorization contracts

* docs: harden trigger disabled-state handling

* docs: harden trigger release state handling

* docs: verify a finished release before enable

* docs: split trigger start and test flows

* docs: fail closed after trigger probe errors

* docs(apps): fail closed on trigger test and release-create failures

Harden the automation guide's state handling. When testing an existing
online trigger, a formerly-disabled trigger is always restored to
disabled on probe success, failure, uncertain result, or early exit.
When +release-create itself errors or returns no release_id, treat it as
not published and restore the prior trigger state; when the result is
unknown, keep it disabled and verify via +release-list before deciding.

* docs(apps): flag online_url as creator-only before sharing

Point the local-dev and release-get release flows to the access-scope
step so a returned online_url is not presented as a shareable link
without the creator-only visibility caveat, matching the SKILL.md
visibility contract.

* docs(apps): drop out-of-scope SKILL.md edits from the trigger change

The local trigger automation work does not require touching the lark-apps
SKILL.md: its description already routed automation, so compressing it only
dropped routing keywords (access scope, monitoring metrics, trigger
subtypes) to satisfy a non-blocking length convention. Restore SKILL.md to
its prior state and remove the description/optional-output assertions that
only guarded those reverted edits. Release-output-as-optional correctness
remains covered by the release-get contract.
2026-07-20 18:27:32 +08:00
calendar-assistant
79adf89beb docs(vc): default transcript routing to smart notes over minutes (#1961)
Clarify that smart notes (AI summary) and their verbatim docs are
auto-authorized to participants, while minutes carry the raw recording
and require explicit authorization. Rewrite the artifact-selection rule
to cover transcripts: use whichever exists when only one is present,
follow the user's explicit choice, and default to smart notes when both
exist and the user is unspecified.
2026-07-20 16:49:03 +08:00
luozhixiong01
9dd355a52d test: synchronize temporary Git maintenance (#1946) 2026-07-20 16:30:09 +08:00
131 changed files with 12969 additions and 3358 deletions

View File

@@ -9,54 +9,10 @@ permissions:
contents: read
jobs:
preflight:
goreleaser:
runs-on: ubuntu-22.04
permissions:
contents: read
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
fetch-depth: 0
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version: '22.14.0'
- name: Validate tag and commit
env:
TAG: ${{ github.ref_name }}
REHEARSAL_BRANCH: test/npm-staged-publish-rehearsal
run: |
set -euo pipefail
node scripts/release-preflight.js --tag "$TAG"
HEAD_SHA="$(git rev-parse --verify 'HEAD^{commit}')"
TAG_SHA="$(git rev-parse --verify "refs/tags/${TAG}^{commit}")"
if [[ "$TAG_SHA" != "$HEAD_SHA" ]]; then
echo "Tag ${TAG} does not resolve to the checked-out HEAD commit." >&2
exit 1
fi
if [[ "$TAG" == *-beta.* ]]; then
git fetch origin "$REHEARSAL_BRANCH"
REHEARSAL_SHA="$(git rev-parse --verify 'FETCH_HEAD^{commit}')"
if [[ "$HEAD_SHA" != "$REHEARSAL_SHA" ]]; then
echo "Beta rehearsal tag ${TAG} must point to the current origin/${REHEARSAL_BRANCH} commit." >&2
exit 1
fi
else
git fetch origin main
MAIN_SHA="$(git rev-parse --verify 'FETCH_HEAD^{commit}')"
if ! git merge-base --is-ancestor "$HEAD_SHA" "$MAIN_SHA"; then
echo "Tag ${TAG} does not point to a commit contained in origin/main." >&2
exit 1
fi
fi
build-release:
needs: preflight
runs-on: ubuntu-22.04
permissions:
contents: read
contents: write
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
@@ -70,77 +26,35 @@ jobs:
with:
python-version: '3.x'
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
with:
node-version: '22.14.0'
registry-url: 'https://registry.npmjs.org'
package-manager-cache: false
- name: Install pinned npm
run: npm install --global npm@11.16.0
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@e435ccd777264be153ace6237001ef4d979d3a7a # v6
with:
version: '~> v2'
args: release --clean --skip=publish
- name: Include release checksums
run: |
set -euo pipefail
test -s dist/checksums.txt
(cd dist && sha256sum --check checksums.txt)
cp dist/checksums.txt checksums.txt
- name: Collect release asset
run: |
set -euo pipefail
mkdir npm-publish-asset
cp dist/*.tar.gz dist/*.zip dist/checksums.txt npm-publish-asset/
- name: Upload release asset
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: npm-publish-asset-${{ github.run_id }}
path: npm-publish-asset/
if-no-files-found: error
overwrite: true
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
publish-npm:
needs: build-release
needs: goreleaser
runs-on: ubuntu-22.04
environment: npm-production
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: '22.14.0'
node-version: '20'
registry-url: 'https://registry.npmjs.org'
package-manager-cache: false
- name: Install pinned npm
run: npm install --global npm@11.16.0
- name: Download release asset
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
with:
name: npm-publish-asset-${{ github.run_id }}
path: npm-publish-asset
- name: Verify npm publish asset
- name: Download checksums from release
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
(cd npm-publish-asset && sha256sum --check checksums.txt)
cp npm-publish-asset/checksums.txt checksums.txt
PACK_JSON="$(npm pack --ignore-scripts --json)"
PACK_FILE="$(node -e 'const p=JSON.parse(process.argv[1]); if(p.length!==1 || !p[0].filename) process.exit(1); process.stdout.write(p[0].filename)' "$PACK_JSON")"
test -s "$PACK_FILE"
tar -tzf "$PACK_FILE" | grep -qx 'package/checksums.txt'
rm "$PACK_FILE"
TAG="${GITHUB_REF_NAME}"
gh release download "${TAG}" --pattern checksums.txt --dir .
test -s checksums.txt || { echo "checksums.txt missing or empty for ${TAG}"; exit 1; }
- name: Stage npm package
run: npm stage publish --access public --tag beta
- name: Publish to npm
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
run: npm publish --access public

View File

@@ -2,6 +2,33 @@
All notable changes to this project will be documented in this file.
## [v1.0.73] - 2026-07-20
### Features
- **apps**: design_html support, creative-design skill, unified TOS publish (#1901)
### Bug Fixes
- **slides**: detect visual elements outside canvas
- reduce public content credential fixture false positives
- standardize CLI shortcut text in English (#1942)
### Documentation
- **base**: reduce filter and update retry loops (#1879)
- **vc**: default transcript routing to smart notes over minutes (#1961)
- clarify local trigger automation (#1958)
### Tests
- synchronize temporary Git maintenance (#1946)
### Misc
- **slides**: update lark-slides skill to 0715 snapshot (#1933)
- [codex] support bot menu events (#1765)
## [v1.0.72] - 2026-07-17
### Features
@@ -1552,6 +1579,7 @@ Bundled AI agent skills for intelligent assistance:
- Bilingual documentation (English & Chinese).
- CI/CD pipelines: linting, testing, coverage reporting, and automated releases.
[v1.0.73]: https://github.com/larksuite/cli/releases/tag/v1.0.73
[v1.0.72]: https://github.com/larksuite/cli/releases/tag/v1.0.72
[v1.0.71]: https://github.com/larksuite/cli/releases/tag/v1.0.71
[v1.0.70]: https://github.com/larksuite/cli/releases/tag/v1.0.70

View File

@@ -51,7 +51,7 @@ script-test:
bash scripts/resolve-changed-from.test.sh
bash scripts/ci-workflow.test.sh
bash scripts/semantic-review-workflow.test.sh
$(NODE) --test scripts/e2e_domains.test.js scripts/fetch_e2e_tat.test.js scripts/install.test.js scripts/release-preflight.test.js scripts/semantic-review-verify-artifact.test.js scripts/pr-quality-summary.test.js scripts/semantic-review-publish.test.js scripts/ci-quality-summary-publish.test.js
$(NODE) --test scripts/e2e_domains.test.js scripts/fetch_e2e_tat.test.js scripts/semantic-review-verify-artifact.test.js scripts/pr-quality-summary.test.js scripts/semantic-review-publish.test.js scripts/ci-quality-summary-publish.test.js
# ./extension/... keeps the public plugin SDK in the default test matrix.
unit-test: fetch_meta

107
events/application/menu.go Normal file
View File

@@ -0,0 +1,107 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package application
import (
"context"
"encoding/json"
"strings"
"github.com/larksuite/cli/internal/event"
)
// BotMenuOutput is the flattened shape for application.bot.menu_v6.
type BotMenuOutput struct {
Type string `json:"type" desc:"Event type; always application.bot.menu_v6"`
EventID string `json:"event_id,omitempty" desc:"Globally unique event ID; safe for deduplication"`
Timestamp string `json:"timestamp,omitempty" desc:"Event delivery time (ms timestamp string); prefers header.create_time" kind:"timestamp_ms"`
AppID string `json:"app_id,omitempty" desc:"Application ID from the event header"`
TenantKey string `json:"tenant_key,omitempty" desc:"Tenant key from the event header"`
EventKey string `json:"event_key,omitempty" desc:"Developer-defined bot menu event key"`
MenuTimestamp string `json:"menu_timestamp,omitempty" desc:"Menu click timestamp from the event body" kind:"timestamp_ms"`
OperatorID string `json:"operator_id,omitempty" desc:"Operator open_id; kept as a short alias of operator_open_id" kind:"open_id"`
OperatorOpenID string `json:"operator_open_id,omitempty" desc:"Operator open_id" kind:"open_id"`
OperatorUnionID string `json:"operator_union_id,omitempty" desc:"Operator union_id" kind:"union_id"`
OperatorUserID string `json:"operator_user_id,omitempty" desc:"Operator user_id" kind:"user_id"`
OperatorName string `json:"operator_name,omitempty" desc:"Operator display name"`
}
func processBotMenu(_ context.Context, _ event.APIClient, raw *event.RawEvent, _ map[string]string) (json.RawMessage, error) {
var envelope struct {
Header struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
CreateTime string `json:"create_time"`
AppID string `json:"app_id"`
TenantKey string `json:"tenant_key"`
} `json:"header"`
Event struct {
EventKey string `json:"event_key"`
Timestamp json.RawMessage `json:"timestamp"`
Operator struct {
OperatorID struct {
OpenID string `json:"open_id"`
UnionID string `json:"union_id"`
UserID string `json:"user_id"`
} `json:"operator_id"`
OperatorName string `json:"operator_name"`
} `json:"operator"`
} `json:"event"`
}
if err := json.Unmarshal(raw.Payload, &envelope); err != nil {
return raw.Payload, nil //nolint:nilerr // passthrough on malformed payload so consumers still see the event
}
menuTimestamp := timestampMillisString(envelope.Event.Timestamp)
timestamp := envelope.Header.CreateTime
if timestamp == "" {
timestamp = menuTimestamp
}
operatorID := envelope.Event.Operator.OperatorID.OpenID
out := &BotMenuOutput{
Type: eventTypeBotMenuV6,
EventID: envelope.Header.EventID,
Timestamp: timestamp,
AppID: envelope.Header.AppID,
TenantKey: envelope.Header.TenantKey,
EventKey: envelope.Event.EventKey,
MenuTimestamp: menuTimestamp,
OperatorID: operatorID,
OperatorOpenID: operatorID,
OperatorUnionID: envelope.Event.Operator.OperatorID.UnionID,
OperatorUserID: envelope.Event.Operator.OperatorID.UserID,
OperatorName: envelope.Event.Operator.OperatorName,
}
return json.Marshal(out)
}
func rawScalarString(raw json.RawMessage) string {
s := strings.TrimSpace(string(raw))
if s == "" || s == "null" {
return ""
}
var text string
if err := json.Unmarshal(raw, &text); err == nil {
return text
}
return s
}
func timestampMillisString(raw json.RawMessage) string {
s := rawScalarString(raw)
if len(s) == 10 && allDigits(s) {
return s + "000"
}
return s
}
func allDigits(s string) bool {
for _, r := range s {
if r < '0' || r > '9' {
return false
}
}
return s != ""
}

View File

@@ -0,0 +1,227 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package application
import (
"context"
"encoding/json"
"reflect"
"testing"
"time"
"github.com/larksuite/cli/internal/event"
)
func TestKeysBotMenuMetadata(t *testing.T) {
keys := Keys()
if len(keys) != 1 {
t.Fatalf("len(Keys()) = %d, want 1", len(keys))
}
def := keys[0]
if def.Key != eventTypeBotMenuV6 {
t.Errorf("Key = %q, want %q", def.Key, eventTypeBotMenuV6)
}
if def.EventType != eventTypeBotMenuV6 {
t.Errorf("EventType = %q, want %q", def.EventType, eventTypeBotMenuV6)
}
if def.SubscriptionType != "" {
t.Errorf("SubscriptionType = %q, want default event subscription", def.SubscriptionType)
}
if def.Schema.Custom == nil {
t.Fatal("Schema.Custom is nil")
}
if def.Schema.Custom.Type != reflect.TypeOf(BotMenuOutput{}) {
t.Errorf("custom type = %v, want BotMenuOutput", def.Schema.Custom.Type)
}
if def.Schema.Native != nil {
t.Fatal("Schema.Native must be nil for processed output")
}
if def.Process == nil {
t.Fatal("Process is nil")
}
if !reflect.DeepEqual(def.AuthTypes, []string{"bot"}) {
t.Errorf("AuthTypes = %#v", def.AuthTypes)
}
if !reflect.DeepEqual(def.RequiredConsoleEvents, []string{eventTypeBotMenuV6}) {
t.Errorf("RequiredConsoleEvents = %#v", def.RequiredConsoleEvents)
}
}
func TestBotMenuRegistersCleanly(t *testing.T) {
const key = eventTypeBotMenuV6
event.UnregisterKeyForTest(key)
t.Cleanup(func() { event.UnregisterKeyForTest(key) })
for _, def := range Keys() {
event.RegisterKey(def)
}
if _, ok := event.Lookup(key); !ok {
t.Fatalf("event.Lookup(%q) not registered", key)
}
}
func TestProcessBotMenu(t *testing.T) {
payload := `{
"schema": "2.0",
"header": {
"event_id": "ev_menu_001",
"event_type": "application.bot.menu_v6",
"create_time": "1776409469273",
"app_id": "cli_test",
"tenant_key": "tenant_test"
},
"event": {
"event_key": "start_eval",
"timestamp": 1776409469000,
"operator": {
"operator_id": {
"open_id": "ou_operator",
"union_id": "on_operator",
"user_id": "user_operator"
},
"operator_name": "Test User"
}
}
}`
out := runBotMenu(t, payload)
if out.Type != eventTypeBotMenuV6 {
t.Errorf("Type = %q, want %q", out.Type, eventTypeBotMenuV6)
}
if out.EventID != "ev_menu_001" {
t.Errorf("EventID = %q", out.EventID)
}
if out.Timestamp != "1776409469273" {
t.Errorf("Timestamp = %q", out.Timestamp)
}
if out.EventKey != "start_eval" {
t.Errorf("EventKey = %q", out.EventKey)
}
if out.MenuTimestamp != "1776409469000" {
t.Errorf("MenuTimestamp = %q", out.MenuTimestamp)
}
if out.OperatorID != "ou_operator" || out.OperatorOpenID != "ou_operator" {
t.Errorf("OperatorID/OperatorOpenID = %q/%q", out.OperatorID, out.OperatorOpenID)
}
if out.OperatorUnionID != "on_operator" {
t.Errorf("OperatorUnionID = %q", out.OperatorUnionID)
}
if out.OperatorUserID != "user_operator" {
t.Errorf("OperatorUserID = %q", out.OperatorUserID)
}
if out.OperatorName != "Test User" {
t.Errorf("OperatorName = %q", out.OperatorName)
}
if out.AppID != "cli_test" || out.TenantKey != "tenant_test" {
t.Errorf("AppID/TenantKey = %q/%q", out.AppID, out.TenantKey)
}
}
func TestProcessBotMenuStringTimestampFallback(t *testing.T) {
payload := `{
"schema": "2.0",
"header": {
"event_id": "ev_menu_002",
"event_type": "application.bot.menu_v6"
},
"event": {
"event_key": "start_eval",
"timestamp": "1776409469001",
"operator": {
"operator_id": {"open_id": "ou_operator"}
}
}
}`
out := runBotMenu(t, payload)
if out.Timestamp != "1776409469001" {
t.Errorf("Timestamp fallback = %q", out.Timestamp)
}
if out.MenuTimestamp != "1776409469001" {
t.Errorf("MenuTimestamp = %q", out.MenuTimestamp)
}
}
func TestProcessBotMenuSecondsTimestampFallback(t *testing.T) {
payload := `{
"schema": "2.0",
"header": {
"event_id": "ev_menu_seconds",
"event_type": "application.bot.menu_v6"
},
"event": {
"event_key": "start_eval",
"timestamp": 1694592375,
"operator": {
"operator_id": {"open_id": "ou_operator"}
}
}
}`
out := runBotMenu(t, payload)
if out.Timestamp != "1694592375000" {
t.Errorf("Timestamp fallback = %q, want seconds normalized to milliseconds", out.Timestamp)
}
if out.MenuTimestamp != "1694592375000" {
t.Errorf("MenuTimestamp = %q, want seconds normalized to milliseconds", out.MenuTimestamp)
}
}
func TestProcessBotMenuTypeUsesLocalConstant(t *testing.T) {
payload := `{
"schema": "2.0",
"header": {
"event_id": "ev_menu_003",
"event_type": "unexpected.event_type",
"create_time": "1776409469275"
},
"event": {
"event_key": "start_eval",
"operator": {
"operator_id": {"open_id": "ou_operator"}
}
}
}`
out := runBotMenu(t, payload)
if out.Type != eventTypeBotMenuV6 {
t.Errorf("Type = %q, want %q", out.Type, eventTypeBotMenuV6)
}
}
func TestProcessBotMenuMalformedPayload(t *testing.T) {
raw := &event.RawEvent{
EventID: "ev_bad",
EventType: eventTypeBotMenuV6,
Payload: json.RawMessage(`not json`),
Timestamp: time.Now(),
}
got, err := processBotMenu(context.Background(), nil, raw, nil)
if err != nil {
t.Fatalf("Process should swallow parse errors, got %v", err)
}
if string(got) != "not json" {
t.Errorf("malformed fallback output = %q, want original bytes", string(got))
}
}
func runBotMenu(t *testing.T, payload string) BotMenuOutput {
t.Helper()
raw := &event.RawEvent{
EventID: "ev_test",
EventType: eventTypeBotMenuV6,
Payload: json.RawMessage(payload),
Timestamp: time.Now(),
}
got, err := processBotMenu(context.Background(), nil, raw, nil)
if err != nil {
t.Fatalf("processBotMenu: %v", err)
}
var out BotMenuOutput
if err := json.Unmarshal(got, &out); err != nil {
t.Fatalf("unmarshal output: %v\n%s", err, got)
}
return out
}

View File

@@ -0,0 +1,31 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
// Package application registers Application-domain EventKeys.
package application
import (
"reflect"
"github.com/larksuite/cli/internal/event"
)
const eventTypeBotMenuV6 = "application.bot.menu_v6"
// Keys returns all Application-domain EventKey definitions.
func Keys() []event.KeyDefinition {
return []event.KeyDefinition{
{
Key: eventTypeBotMenuV6,
DisplayName: "Bot menu",
Description: "Triggered when a user clicks a custom bot menu item whose action is configured as a push event.",
EventType: eventTypeBotMenuV6,
Schema: event.SchemaDef{
Custom: &event.SchemaSpec{Type: reflect.TypeOf(BotMenuOutput{})},
},
Process: processBotMenu,
AuthTypes: []string{"bot"},
RequiredConsoleEvents: []string{eventTypeBotMenuV6},
},
}
}

View File

@@ -5,6 +5,7 @@
package events
import (
"github.com/larksuite/cli/events/application"
"github.com/larksuite/cli/events/approval"
"github.com/larksuite/cli/events/im"
"github.com/larksuite/cli/events/minutes"
@@ -17,6 +18,7 @@ import (
// Mail is intentionally omitted in this phase.
func init() {
all := [][]event.KeyDefinition{
application.Keys(),
approval.Keys(),
im.Keys(),
minutes.Keys(),

View File

@@ -6,10 +6,11 @@ package diff
import (
"context"
"os"
"os/exec"
"path/filepath"
"reflect"
"testing"
"github.com/larksuite/cli/internal/testutil/gitcmd"
)
func TestScopeIncludesChangedSkillAndRelatedDomain(t *testing.T) {
@@ -122,8 +123,7 @@ func writeFile(t *testing.T, repo, rel, content string) {
func runGit(t *testing.T, repo string, args ...string) {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = repo
cmd := gitcmd.Command(repo, args...)
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("git %v failed: %v\n%s", args, err, out)
}
@@ -131,8 +131,7 @@ func runGit(t *testing.T, repo string, args ...string) {
func gitOutput(t *testing.T, repo string, args ...string) string {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = repo
cmd := gitcmd.Command(repo, args...)
out, err := cmd.Output()
if err != nil {
t.Fatalf("git %v failed: %v", args, err)

View File

@@ -6,10 +6,11 @@ package publiccontent
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/larksuite/cli/internal/testutil/gitcmd"
)
func TestCollectScansOnlyCurrentContributionAndMetadata(t *testing.T) {
@@ -839,8 +840,7 @@ func runGit(t *testing.T, repo string, args ...string) {
if len(args) > 0 && args[0] == "commit" {
args = append([]string{"commit", "--no-verify"}, args[1:]...)
}
cmd := exec.Command("git", args...)
cmd.Dir = repo
cmd := gitcmd.Command(repo, args...)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v failed: %v\n%s", args, err, out)
@@ -849,8 +849,7 @@ func runGit(t *testing.T, repo string, args ...string) {
func runGitOutput(t *testing.T, repo string, args ...string) []byte {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = repo
cmd := gitcmd.Command(repo, args...)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v failed: %v\n%s", args, err, out)

View File

@@ -7,7 +7,6 @@ import (
"context"
"encoding/json"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
@@ -15,6 +14,7 @@ import (
qdiff "github.com/larksuite/cli/internal/qualitygate/diff"
"github.com/larksuite/cli/internal/qualitygate/manifest"
"github.com/larksuite/cli/internal/qualitygate/report"
"github.com/larksuite/cli/internal/testutil/gitcmd"
"github.com/larksuite/cli/internal/vfs"
)
@@ -600,7 +600,8 @@ func TestNormalizeDiagnosticFileHandlesAbsoluteRepo(t *testing.T) {
func runGit(t *testing.T, repo string, args ...string) {
t.Helper()
cmd := exec.Command("git", append([]string{"-c", "core.hooksPath=/dev/null", "-C", repo}, args...)...)
commandArgs := append([]string{"-c", "core.hooksPath=/dev/null"}, args...)
cmd := gitcmd.Command(repo, commandArgs...)
cmd.Env = append(os.Environ(), "GIT_AUTHOR_DATE=2026-06-17T00:00:00Z", "GIT_COMMITTER_DATE=2026-06-17T00:00:00Z")
out, err := cmd.CombinedOutput()
if err != nil {

View File

@@ -0,0 +1,55 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
// Package gitcmd provides Git process helpers for tests that use temporary
// repositories.
package gitcmd
import (
"os"
"os/exec"
"strconv"
"testing"
)
const (
maintenanceAutoDetach = "maintenance.autoDetach"
gcAutoDetach = "gc.autoDetach"
)
// Command creates a Git command whose automatic maintenance stays in the
// command lifecycle, so temporary repository cleanup cannot race a detached
// maintenance process.
func Command(dir string, args ...string) *exec.Cmd {
commandArgs := make([]string, 0, len(args)+4)
commandArgs = append(commandArgs,
"-c", maintenanceAutoDetach+"=false",
"-c", gcAutoDetach+"=false",
)
commandArgs = append(commandArgs, args...)
cmd := exec.Command("git", commandArgs...)
cmd.Dir = dir
return cmd
}
// SetSynchronousMaintenanceEnv applies the same lifecycle contract to every
// Git process started by the current test, including processes created through
// production command runners. Tests using it must not run in parallel.
func SetSynchronousMaintenanceEnv(t *testing.T) {
t.Helper()
count := 0
if value, ok := os.LookupEnv("GIT_CONFIG_COUNT"); ok {
parsed, err := strconv.Atoi(value)
if err != nil || parsed < 0 {
t.Fatalf("invalid GIT_CONFIG_COUNT %q", value)
}
count = parsed
}
for _, key := range []string{maintenanceAutoDetach, gcAutoDetach} {
index := strconv.Itoa(count)
t.Setenv("GIT_CONFIG_KEY_"+index, key)
t.Setenv("GIT_CONFIG_VALUE_"+index, "false")
count++
}
t.Setenv("GIT_CONFIG_COUNT", strconv.Itoa(count))
}

View File

@@ -0,0 +1,47 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package gitcmd
import (
"os/exec"
"strings"
"testing"
)
func TestCommandDisablesDetachedMaintenance(t *testing.T) {
for _, key := range []string{"maintenance.autoDetach", "gc.autoDetach"} {
cmd := Command(t.TempDir(), "config", "--get", "--type=bool", key)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git config %s: %v\n%s", key, err, out)
}
if got := strings.TrimSpace(string(out)); got != "false" {
t.Fatalf("%s = %q, want false", key, got)
}
}
}
func TestSetSynchronousMaintenanceEnv(t *testing.T) {
t.Setenv("GIT_CONFIG_COUNT", "1")
t.Setenv("GIT_CONFIG_KEY_0", "user.name")
t.Setenv("GIT_CONFIG_VALUE_0", "Existing Test User")
SetSynchronousMaintenanceEnv(t)
for key, want := range map[string]string{
"user.name": "Existing Test User",
maintenanceAutoDetach: "false",
gcAutoDetach: "false",
} {
cmd := exec.Command("git", "config", "--get", "--type=bool", key)
if key == "user.name" {
cmd = exec.Command("git", "config", "--get", key)
}
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git config %s: %v\n%s", key, err, out)
}
if got := strings.TrimSpace(string(out)); got != want {
t.Fatalf("%s = %q, want %q", key, got, want)
}
}
}

View File

@@ -34,7 +34,12 @@ func writeFixture(t *testing.T, files fixtureRepo) string {
func runGit(t *testing.T, root string, args ...string) string {
t.Helper()
cmd := exec.Command("git", args...)
commandArgs := []string{
"-c", "maintenance.autoDetach=false",
"-c", "gc.autoDetach=false",
}
commandArgs = append(commandArgs, args...)
cmd := exec.Command("git", commandArgs...)
cmd.Dir = root
out, err := cmd.CombinedOutput()
if err != nil {
@@ -43,6 +48,14 @@ func runGit(t *testing.T, root string, args ...string) string {
return strings.TrimSpace(string(out))
}
func TestRunGitDisablesDetachedMaintenance(t *testing.T) {
for _, key := range []string{"maintenance.autoDetach", "gc.autoDetach"} {
if got := runGit(t, t.TempDir(), "config", "--get", "--type=bool", key); got != "false" {
t.Fatalf("%s = %q, want false", key, got)
}
}
}
func TestLoadSubtypeAllowlist_ExtractsTypedConstValues(t *testing.T) {
root := writeFixture(t, fixtureRepo{
"errs/subtypes.go": `package errs

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@larksuite/cli",
"version": "1.0.73-beta.5",
"version": "1.0.11",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@larksuite/cli",
"version": "1.0.73-beta.5",
"version": "1.0.11",
"cpu": [
"x64",
"arm64"

View File

@@ -1,13 +1,12 @@
{
"name": "@larksuite/cli",
"version": "1.0.73-beta.5",
"version": "1.0.73",
"description": "The official CLI for Lark/Feishu open platform",
"bin": {
"lark-cli": "scripts/run.js"
},
"scripts": {
"postinstall": "node scripts/install.js",
"release:check": "node scripts/release-preflight.js"
"postinstall": "node scripts/install.js"
},
"os": [
"darwin",

View File

@@ -265,7 +265,10 @@ function getExpectedChecksum(archiveName, checksumsDir) {
const checksumsPath = path.join(dir, "checksums.txt");
if (!fs.existsSync(checksumsPath)) {
throw new Error(`[SECURITY] checksums.txt not found at ${checksumsPath}`);
console.error(
"[WARN] checksums.txt not found, skipping checksum verification"
);
return null;
}
const content = fs.readFileSync(checksumsPath, "utf8");
@@ -283,14 +286,7 @@ function getExpectedChecksum(archiveName, checksumsDir) {
}
function verifyChecksum(archivePath, expectedHash) {
if (typeof expectedHash !== "string" || expectedHash.length === 0) {
throw new Error("[SECURITY] Expected checksum is missing or invalid");
}
if (!/^[0-9a-f]{64}$/i.test(expectedHash)) {
throw new Error(
"[SECURITY] Expected checksum must be a 64-character hexadecimal SHA-256 digest"
);
}
if (expectedHash === null) return;
// Stream the file to avoid loading the entire archive into memory.
// Archives can be 10-100MB; streaming keeps RSS constant.

View File

@@ -52,12 +52,11 @@ describe("getExpectedChecksum", () => {
);
});
it("throws [SECURITY]-prefixed Error when checksums.txt does not exist", () => {
it("returns null when checksums.txt does not exist", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "checksum-test-"));
assert.throws(
() => getExpectedChecksum("anything.tar.gz", dir),
{ message: /^\[SECURITY\] checksums\.txt not found/ }
);
// No checksums.txt in dir
const result = getExpectedChecksum("anything.tar.gz", dir);
assert.equal(result, null);
});
it("skips malformed lines and still finds valid entry", () => {
@@ -107,7 +106,7 @@ describe("verifyChecksum", () => {
verifyChecksum(filePath, hash);
});
it("accepts a valid uppercase 64-character hex hash", () => {
it("matches case-insensitively", () => {
const content = "case test";
const filePath = makeTmpFile(content);
const hash = sha256(content).toUpperCase();
@@ -115,40 +114,6 @@ describe("verifyChecksum", () => {
verifyChecksum(filePath, hash);
});
for (const [name, expectedHash] of [
["null", null],
["empty", ""],
["non-string", 123],
]) {
it(`throws [SECURITY]-prefixed Error for ${name} expected hash`, () => {
const filePath = makeTmpFile("real content");
assert.throws(
() => verifyChecksum(filePath, expectedHash),
(err) => {
assert.match(err.message, /^\[SECURITY\]/);
assert.match(err.message, /Expected checksum is missing or invalid/);
return true;
}
);
});
}
it("throws [SECURITY] format Error for an incorrectly sized hash", () => {
const filePath = makeTmpFile("real content");
assert.throws(
() => verifyChecksum(filePath, "abc123"),
{ message: /^\[SECURITY\] Expected checksum must be a 64-character hexadecimal SHA-256 digest$/ }
);
});
it("throws [SECURITY] format Error for a non-hex hash", () => {
const filePath = makeTmpFile("real content");
assert.throws(
() => verifyChecksum(filePath, "g".repeat(64)),
{ message: /^\[SECURITY\] Expected checksum must be a 64-character hexadecimal SHA-256 digest$/ }
);
});
it("throws [SECURITY]-prefixed Error on mismatch", () => {
const filePath = makeTmpFile("real content");
assert.throws(

View File

@@ -1,110 +0,0 @@
#!/usr/bin/env node
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
const fs = require("node:fs");
const path = require("node:path");
const STABLE_VERSION_PATTERN = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
const REHEARSAL_VERSION_PATTERN = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)-beta\.(0|[1-9][0-9]*)$/;
function isReleaseVersion(value) {
return typeof value === "string" &&
(STABLE_VERSION_PATTERN.test(value) || REHEARSAL_VERSION_PATTERN.test(value));
}
function releaseError(message, observed, hint) {
return { ok: false, error: { type: "release_preflight", message, observed, hint } };
}
function validateReleasePreflight(packageJson, packageLockJson, tag) {
const packageVersion = packageJson?.version;
const lockVersion = packageLockJson?.version;
const lockRootVersion = packageLockJson?.packages?.[""]?.version;
const observed = {
packageVersion: packageVersion ?? null,
lockVersion: lockVersion ?? null,
lockRootVersion: lockRootVersion ?? null,
tagVersion: null,
};
for (const [field, value] of [
["package.json.version", packageVersion],
["package-lock.json.version", lockVersion],
['package-lock.json.packages[""].version', lockRootVersion],
]) {
if (!isReleaseVersion(value)) {
return releaseError(
`${field} must use X.Y.Z or the rehearsal form X.Y.Z-beta.N`,
observed,
"Use the same version in all package fields; only stable releases and the temporary beta rehearsal form are allowed.",
);
}
}
if (packageVersion !== lockVersion || packageVersion !== lockRootVersion) {
return releaseError(
"Package version fields do not match",
observed,
"Synchronize package.json.version and both package-lock.json version fields.",
);
}
if (tag === undefined) {
return { ok: true, data: observed };
}
if (typeof tag !== "string" || !tag.startsWith("v") || !isReleaseVersion(tag.slice(1))) {
return releaseError(
"--tag must use vX.Y.Z or the rehearsal form vX.Y.Z-beta.N",
{ ...observed, tag },
`Use --tag v${packageVersion}.`,
);
}
const tagVersion = tag.slice(1);
if (tagVersion !== packageVersion) {
return releaseError(
"Tag version does not match the package version",
{ ...observed, tagVersion, tag },
`Use --tag v${packageVersion}.`,
);
}
return { ok: true, data: { ...observed, tagVersion } };
}
function writeResult(result) {
(result.ok ? process.stdout : process.stderr).write(`${JSON.stringify(result)}\n`);
if (!result.ok) process.exitCode = 1;
}
function main() {
const args = process.argv.slice(2);
let tag;
if (args.length === 2 && args[0] === "--tag") {
tag = args[1];
} else if (args.length !== 0) {
writeResult(releaseError(
"Expected no arguments or --tag vX.Y.Z",
{ arguments: args },
"Run release:check without arguments or pass exactly one --tag value.",
));
return;
}
const repoRoot = path.resolve(__dirname, "..");
try {
const packageJson = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8"));
const packageLockJson = JSON.parse(fs.readFileSync(path.join(repoRoot, "package-lock.json"), "utf8"));
writeResult(validateReleasePreflight(packageJson, packageLockJson, tag));
} catch (error) {
writeResult(releaseError(
"Could not read release package metadata",
{ reason: error.message },
"Ensure package.json and package-lock.json exist and contain valid JSON.",
));
}
}
module.exports = { validateReleasePreflight };
if (require.main === module) main();

View File

@@ -1,627 +0,0 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
const assert = require("node:assert/strict");
const { spawnSync } = require("node:child_process");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { describe, it } = require("node:test");
const {
validateReleasePreflight,
} = require("./release-preflight");
const repoRoot = path.resolve(__dirname, "..");
function createReleaseFixture(t, env = {}) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "tag-release-test-"));
const scriptsDir = path.join(root, "scripts");
const binDir = path.join(root, "bin");
const stateDir = path.join(root, "state");
const logPath = path.join(root, "git-calls.jsonl");
const npmLogPath = path.join(root, "npm-calls.jsonl");
fs.mkdirSync(scriptsDir);
fs.mkdirSync(binDir);
fs.mkdirSync(stateDir);
fs.copyFileSync(
path.join(repoRoot, "scripts/release-preflight.js"),
path.join(scriptsDir, "release-preflight.js"),
);
fs.copyFileSync(
path.join(repoRoot, "scripts/tag-release.sh"),
path.join(scriptsDir, "tag-release.sh"),
);
fs.writeFileSync(path.join(root, "package.json"), '{"version":"1.2.3-beta.0"}\n');
fs.writeFileSync(
path.join(root, "package-lock.json"),
'{"version":"1.2.3-beta.0","packages":{"":{"version":"1.2.3-beta.0"}}}\n',
);
const fakeGitPath = path.join(binDir, "git");
fs.writeFileSync(fakeGitPath, String.raw`#!/usr/bin/env node
const fs = require("node:fs");
const path = require("node:path");
const args = process.argv.slice(2);
const stateDir = process.env.FAKE_GIT_STATE_DIR;
const localTagPath = path.join(stateDir, "local-tag");
if (process.cwd() !== process.env.FAKE_EXPECTED_GIT_CWD) {
process.stderr.write("git invoked outside repository root: " + process.cwd() + "\n");
process.exit(96);
}
fs.appendFileSync(process.env.FAKE_GIT_LOG, JSON.stringify(args) + "\n");
function print(value) {
process.stdout.write(value + "\n");
}
switch (args[0]) {
case "branch":
print(process.env.FAKE_BRANCH || "test/npm-staged-publish-rehearsal");
break;
case "status":
if (process.env.FAKE_STATUS_OUTPUT) print(process.env.FAKE_STATUS_OUTPUT);
break;
case "fetch":
break;
case "rev-parse": {
const ref = args[args.length - 1];
if (ref === "HEAD") {
print(process.env.FAKE_HEAD_SHA);
break;
}
if (ref === "FETCH_HEAD^{commit}") {
print(process.env.FAKE_REHEARSAL_SHA);
break;
}
if (ref.startsWith("refs/tags/")) {
if (fs.existsSync(localTagPath)) {
print(fs.readFileSync(localTagPath, "utf8").trim());
break;
}
process.exit(1);
}
process.stderr.write("unexpected rev-parse ref: " + ref + "\n");
process.exit(97);
break;
}
case "ls-remote": {
const tagRef = args.find((arg) => arg.startsWith("refs/tags/") && !arg.endsWith("^{}"));
const kind = process.env.FAKE_REMOTE_TAG_KIND || "absent";
if (kind === "lightweight" || kind === "annotated") {
print(process.env.FAKE_REMOTE_TAG_SHA + "\t" + tagRef);
}
break;
}
case "show":
print(process.env.FAKE_WORKFLOW);
break;
case "tag":
fs.writeFileSync(localTagPath, args[2] || process.env.FAKE_HEAD_SHA);
break;
case "push": {
const failedMarker = path.join(stateDir, "push-failed");
if (process.env.FAKE_PUSH_FAIL_ONCE && !fs.existsSync(failedMarker)) {
fs.writeFileSync(failedMarker, "1");
process.exit(Number(process.env.FAKE_PUSH_FAIL_ONCE));
}
break;
}
default:
process.stderr.write("unexpected git command: " + args.join(" ") + "\n");
process.exit(97);
}
`);
fs.chmodSync(fakeGitPath, 0o755);
const fakeNpmPath = path.join(binDir, "npm");
fs.writeFileSync(fakeNpmPath, String.raw`#!/usr/bin/env node
const fs = require("node:fs");
const args = process.argv.slice(2);
fs.appendFileSync(process.env.FAKE_NPM_LOG, JSON.stringify(args) + "\n");
if (args[0] !== "view") {
process.stderr.write("unexpected npm command: " + args.join(" ") + "\n");
process.exit(97);
}
const output = process.env.FAKE_NPM_VIEW_OUTPUT || "npm error code E404\nnpm error 404 Not Found";
(Number(process.env.FAKE_NPM_VIEW_STATUS || "1") === 0 ? process.stdout : process.stderr).write(output + "\n");
process.exit(Number(process.env.FAKE_NPM_VIEW_STATUS || "1"));
`);
fs.chmodSync(fakeNpmPath, 0o755);
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
return {
root,
stateDir,
logPath,
env: {
...process.env,
PATH: `${binDir}${path.delimiter}${process.env.PATH}`,
LANG: "C",
LC_ALL: "C",
FAKE_GIT_LOG: logPath,
FAKE_NPM_LOG: npmLogPath,
FAKE_GIT_STATE_DIR: stateDir,
FAKE_EXPECTED_GIT_CWD: fs.realpathSync(root),
FAKE_HEAD_SHA: "aaaaaaaa",
FAKE_REHEARSAL_SHA: "aaaaaaaa",
FAKE_WORKFLOW: "args: release --clean --skip=publish\nrun: npm stage publish package.tgz --access public --tag beta",
...env,
},
};
}
function runTagRelease(fixture, options = {}) {
const { cwd = fixture.root, args = [], input = "" } = options;
return spawnSync("bash", [path.join(fixture.root, "scripts/tag-release.sh"), ...args], {
cwd,
env: fixture.env,
encoding: "utf8",
input,
});
}
function readGitCalls(fixture) {
if (!fs.existsSync(fixture.logPath)) {
return [];
}
return fs.readFileSync(fixture.logPath, "utf8")
.trim()
.split("\n")
.filter(Boolean)
.map((line) => JSON.parse(line));
}
function assertNoTagOperations(calls) {
const tagOperations = calls.filter((args) =>
args[0] === "ls-remote" ||
args[0] === "tag" ||
args[0] === "push" ||
(args[0] === "rev-parse" && args.some((arg) => arg.startsWith("refs/tags/"))),
);
assert.deepEqual(tagOperations, []);
}
function assertNoTagWrites(calls) {
assert.equal(calls.some((args) => args[0] === "tag" || args[0] === "push"), false);
}
function validInputs(version = "1.2.3") {
return {
packageJson: { version },
packageLockJson: {
version,
packages: { "": { version } },
},
};
}
function assertStructuredError(result) {
assert.equal(result.ok, false);
assert.equal(result.error.type, "release_preflight");
assert.equal(typeof result.error.message, "string");
assert.ok(result.error.message.length > 0);
assert.equal(typeof result.error.observed, "object");
assert.equal(typeof result.error.hint, "string");
assert.ok(result.error.hint.length > 0);
}
function assertInOrder(source, snippets) {
let previous = -1;
for (const snippet of snippets) {
const index = source.indexOf(snippet);
assert.ok(index >= 0, `missing fragment: ${snippet}`);
assert.ok(index > previous, `fragment is out of order: ${snippet}`);
previous = index;
}
}
describe("validateReleasePreflight", () => {
it("accepts matching stable and beta rehearsal versions", () => {
for (const version of ["1.2.3", "1.2.3-beta.0"]) {
const { packageJson, packageLockJson } = validInputs(version);
assert.deepEqual(validateReleasePreflight(packageJson, packageLockJson), {
ok: true,
data: {
packageVersion: version,
lockVersion: version,
lockRootVersion: version,
tagVersion: null,
},
});
assert.deepEqual(
validateReleasePreflight(packageJson, packageLockJson, `v${version}`),
{
ok: true,
data: {
packageVersion: version,
lockVersion: version,
lockRootVersion: version,
tagVersion: version,
},
},
);
}
});
it("rejects prerelease forms other than beta rehearsal versions", () => {
const { packageJson, packageLockJson } = validInputs("1.2.3-rc.1");
const result = validateReleasePreflight(packageJson, packageLockJson);
assertStructuredError(result);
assert.equal(
result.error.message,
"package.json.version must use X.Y.Z or the rehearsal form X.Y.Z-beta.N",
);
assert.equal(
result.error.hint,
"Use the same version in all package fields; only stable releases and the temporary beta rehearsal form are allowed.",
);
});
it("rejects build metadata package versions with the stable release contract", () => {
const { packageJson, packageLockJson } = validInputs("1.2.3+build.7");
const result = validateReleasePreflight(packageJson, packageLockJson);
assertStructuredError(result);
assert.equal(
result.error.message,
"package.json.version must use X.Y.Z or the rehearsal form X.Y.Z-beta.N",
);
assert.equal(
result.error.hint,
"Use the same version in all package fields; only stable releases and the temporary beta rehearsal form are allowed.",
);
});
it("rejects invalid and missing package or lock SemVer values", () => {
const invalid = validInputs();
invalid.packageJson.version = "01.2.3";
const missing = validInputs();
delete missing.packageLockJson.packages[""].version;
for (const result of [
validateReleasePreflight(invalid.packageJson, invalid.packageLockJson),
validateReleasePreflight(missing.packageJson, missing.packageLockJson),
]) {
assertStructuredError(result);
}
});
it("rejects a top-level package-lock version mismatch", () => {
const { packageJson, packageLockJson } = validInputs();
packageLockJson.version = "1.2.4";
const result = validateReleasePreflight(packageJson, packageLockJson);
assertStructuredError(result);
assert.deepEqual(result.error.observed, {
packageVersion: "1.2.3",
lockVersion: "1.2.4",
lockRootVersion: "1.2.3",
tagVersion: null,
});
});
it("rejects a package-lock root package version mismatch", () => {
const { packageJson, packageLockJson } = validInputs();
packageLockJson.packages[""].version = "1.2.4";
const result = validateReleasePreflight(packageJson, packageLockJson);
assertStructuredError(result);
assert.deepEqual(result.error.observed, {
packageVersion: "1.2.3",
lockVersion: "1.2.3",
lockRootVersion: "1.2.4",
tagVersion: null,
});
});
it("rejects invalid and mismatched tags", () => {
const { packageJson, packageLockJson } = validInputs();
for (const tag of ["1.2.3", "v01.2.3", "v1.2.4"]) {
const result = validateReleasePreflight(packageJson, packageLockJson, tag);
assertStructuredError(result);
assert.equal(result.error.observed.tag, tag);
}
});
});
describe("release configuration", () => {
it("writes success to stdout and structured failures to stderr", () => {
const scriptPath = path.join(repoRoot, "scripts/release-preflight.js");
const packageVersion = require(path.join(repoRoot, "package.json")).version;
const success = spawnSync(process.execPath, [scriptPath, "--tag", `v${packageVersion}`], {
cwd: repoRoot,
encoding: "utf8",
});
const failure = spawnSync(process.execPath, [scriptPath, "--tag", "invalid"], {
cwd: repoRoot,
encoding: "utf8",
});
assert.equal(success.status, 0);
assert.equal(success.stderr, "");
assert.deepEqual(JSON.parse(success.stdout), {
ok: true,
data: {
packageVersion,
lockVersion: packageVersion,
lockRootVersion: packageVersion,
tagVersion: packageVersion,
},
});
assert.equal(failure.status, 1);
assert.equal(failure.stdout, "");
assertStructuredError(JSON.parse(failure.stderr));
});
it("keeps package metadata synchronized without changing the Node engine", () => {
const packageJson = require(path.join(repoRoot, "package.json"));
const packageLockJson = require(path.join(repoRoot, "package-lock.json"));
assert.equal(packageJson.scripts["release:check"], "node scripts/release-preflight.js");
assert.equal(packageJson.engines.node, ">=16");
assert.equal(packageLockJson.version, packageJson.version);
assert.equal(packageLockJson.packages[""].version, packageJson.version);
});
it("runs every release gate before any tag query, creation, or push", () => {
const script = fs.readFileSync(path.join(repoRoot, "scripts/tag-release.sh"), "utf8");
const preflight = script.indexOf('node "${SCRIPT_DIR}/release-preflight.js" --tag "${TAG}"');
const requiredGates = [
'CURRENT_BRANCH=$(git branch --show-current)',
'git status --porcelain',
'git fetch origin "${REHEARSAL_BRANCH}"',
'git rev-parse "FETCH_HEAD^{commit}"',
'git show "${HEAD_SHA}:.github/workflows/release.yml"',
'npm view "@larksuite/cli@${VERSION}" version',
];
const tagOperations = [
'git rev-parse -q --verify "refs/tags/${TAG}"',
'git ls-remote --tags origin "refs/tags/${TAG}"',
'git tag "${TAG}" "${HEAD_SHA}"',
'git push origin "refs/tags/${TAG}:refs/tags/${TAG}"',
];
assert.ok(preflight >= 0, "release preflight invocation is missing");
assertInOrder(script, [
'REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"',
'cd "${REPO_ROOT}"',
'node "${SCRIPT_DIR}/release-preflight.js"',
]);
assert.equal(script.includes("require('${REPO_ROOT}/package.json')"), false);
for (const gate of requiredGates) {
const index = script.indexOf(gate);
assert.ok(index >= 0, `required release gate is missing: ${gate}`);
assert.ok(index < script.indexOf(tagOperations[0]), `${gate} must run before tag queries`);
}
for (const operation of tagOperations) {
const index = script.indexOf(operation);
assert.ok(index >= 0, `tag operation is missing: ${operation}`);
assert.ok(preflight < index, `preflight must run before: ${operation}`);
}
assertInOrder(script, [
'if [ "${PUSH_TAG}" != true ]',
'read -r CONFIRM_TAG',
'git tag "${TAG}" "${HEAD_SHA}"',
'git push origin "refs/tags/${TAG}:refs/tags/${TAG}"',
]);
});
});
describe("tag-release.sh behavior", () => {
it("runs repository checks from the script repository when invoked elsewhere", (t) => {
const fixture = createReleaseFixture(t);
const outside = fs.mkdtempSync(path.join(os.tmpdir(), "tag-release-cwd-"));
t.after(() => fs.rmSync(outside, { recursive: true, force: true }));
const result = runTagRelease(fixture, { cwd: outside });
assert.equal(result.status, 0, result.stderr);
});
it("rejects a non-rehearsal branch before querying or modifying tags", (t) => {
const fixture = createReleaseFixture(t, { FAKE_BRANCH: "feature/release" });
const result = runTagRelease(fixture);
const calls = readGitCalls(fixture);
assert.equal(result.status, 1);
assert.match(result.stderr, /must be created from test\/npm-staged-publish-rehearsal/i);
assertNoTagOperations(calls);
});
it("rejects a dirty working tree before tag operations", (t) => {
const fixture = createReleaseFixture(t, { FAKE_STATUS_OUTPUT: " M README.md" });
const result = runTagRelease(fixture);
const calls = readGitCalls(fixture);
assert.equal(result.status, 1);
assert.match(result.stderr, /working tree must be clean/i);
assertNoTagOperations(calls);
});
it("rejects HEAD that differs from the fetched rehearsal branch", (t) => {
const fixture = createReleaseFixture(t, { FAKE_REHEARSAL_SHA: "bbbbbbbb" });
const result = runTagRelease(fixture);
const calls = readGitCalls(fixture);
assert.equal(result.status, 1);
assert.match(result.stderr, /HEAD must exactly match origin\/test\/npm-staged-publish-rehearsal/i);
assertNoTagOperations(calls);
});
it("compares HEAD with the exact fetched rehearsal commit", (t) => {
const fixture = createReleaseFixture(t);
const result = runTagRelease(fixture);
const calls = readGitCalls(fixture);
assert.equal(result.status, 0, result.stderr);
assert.ok(calls.some((args) => args.join(" ") === "fetch origin test/npm-staged-publish-rehearsal"));
assert.ok(calls.some((args) => args.join(" ") === "rev-parse FETCH_HEAD^{commit}"));
assert.equal(calls.some((args) => args.includes("origin/test/npm-staged-publish-rehearsal")), false);
});
it("fails when the local tag already exists", (t) => {
const fixture = createReleaseFixture(t);
fs.writeFileSync(path.join(fixture.stateDir, "local-tag"), "bbbbbbbb");
const result = runTagRelease(fixture);
const calls = readGitCalls(fixture);
assert.equal(result.status, 1);
assert.match(result.stderr, /local tag .* already exists/i);
assert.equal(calls.some((args) => args[0] === "ls-remote"), false);
assert.equal(calls.some((args) => args[0] === "push"), false);
});
it("fails when a lightweight or annotated remote tag already exists", (t) => {
for (const kind of ["lightweight", "annotated"]) {
const fixture = createReleaseFixture(t, {
FAKE_REMOTE_TAG_KIND: kind,
FAKE_REMOTE_TAG_SHA: "aaaaaaaa",
});
const result = runTagRelease(fixture);
const calls = readGitCalls(fixture);
assert.equal(result.status, 1, `${kind}: ${result.stderr}`);
assert.match(result.stderr, /remote tag .* already exists/i);
assert.equal(calls.some((args) => args[0] === "tag"), false);
assert.equal(calls.some((args) => args[0] === "push"), false);
}
});
it("check mode completes without creating or pushing a tag", (t) => {
const fixture = createReleaseFixture(t);
const result = runTagRelease(fixture);
const calls = readGitCalls(fixture);
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /No tag was created or pushed/);
assertNoTagWrites(calls);
});
it("allows a stage-only workflow whose step label mentions npm publish", (t) => {
const fixture = createReleaseFixture(t, {
FAKE_WORKFLOW: [
"args: release --clean --skip=publish",
"- name: Verify npm publish asset",
" run: |",
" npm stage publish --access public --tag beta",
].join("\\n"),
});
const result = runTagRelease(fixture);
assert.equal(result.status, 0, result.stderr);
assertNoTagWrites(readGitCalls(fixture));
});
it("rejects a production version before invoking git", (t) => {
const fixture = createReleaseFixture(t);
fs.writeFileSync(path.join(fixture.root, "package.json"), '{"version":"1.2.3"}\n');
fs.writeFileSync(
path.join(fixture.root, "package-lock.json"),
'{"version":"1.2.3","packages":{"":{"version":"1.2.3"}}}\n',
);
const result = runTagRelease(fixture);
assert.equal(result.status, 1);
assert.match(result.stderr, /require an X\.Y\.Z-beta\.N version/);
assert.deepEqual(readGitCalls(fixture), []);
});
it("rejects a workflow that can publish live", (t) => {
for (const workflow of [
"args: release --clean --skip=publish\nrun: npm publish --access public",
"args: release --clean --skip=publish\nrun: npm stage publish package.tgz --access public --tag beta\nrun: gh release create v1.2.3-beta.0",
"args: release --clean --skip=publish\npermissions:\n contents: write\nrun: npm stage publish package.tgz --access public --tag beta",
"args: release --clean --skip=publish\nenv:\n GITHUB_TOKEN: ${{ github.token }}\nrun: npm stage publish package.tgz --access public --tag beta",
]) {
const fixture = createReleaseFixture(t, { FAKE_WORKFLOW: workflow });
const result = runTagRelease(fixture);
assert.equal(result.status, 1);
assert.match(result.stderr, /must be stage-only/i);
assertNoTagWrites(readGitCalls(fixture));
}
});
it("fails closed when npm cannot prove that the version is unused", (t) => {
const fixture = createReleaseFixture(t, {
FAKE_NPM_VIEW_OUTPUT: "npm error code ETIMEDOUT",
});
const result = runTagRelease(fixture);
assert.equal(result.status, 1);
assert.match(result.stderr, /npm version lookup failed/i);
assertNoTagWrites(readGitCalls(fixture));
});
it("rejects an existing npm version", (t) => {
const fixture = createReleaseFixture(t, {
FAKE_NPM_VIEW_STATUS: "0",
FAKE_NPM_VIEW_OUTPUT: "1.2.3-beta.0",
});
const result = runTagRelease(fixture);
assert.equal(result.status, 1);
assert.match(result.stderr, /already exists on npm/i);
assertNoTagWrites(readGitCalls(fixture));
});
it("requires the full tag confirmation in push mode", (t) => {
const fixture = createReleaseFixture(t);
const result = runTagRelease(fixture, { args: ["--push"], input: "no\n" });
assert.equal(result.status, 1);
assert.match(result.stderr, /confirmation did not exactly match/i);
assertNoTagWrites(readGitCalls(fixture));
});
it("pushes only the exact confirmed tag ref", (t) => {
const fixture = createReleaseFixture(t);
const result = runTagRelease(fixture, {
args: ["--push"],
input: "v1.2.3-beta.0\n",
});
const calls = readGitCalls(fixture);
assert.equal(result.status, 0, result.stderr);
assert.ok(calls.some((args) => args.join(" ") === "tag v1.2.3-beta.0 aaaaaaaa"));
assert.ok(calls.some((args) =>
args.join(" ") === "push origin refs/tags/v1.2.3-beta.0:refs/tags/v1.2.3-beta.0"));
assert.equal(
calls.some((args) => args[0] === "push" && args.includes("--tags")),
false,
);
});
it("reports an invalid package version before invoking git", (t) => {
const fixture = createReleaseFixture(t);
fs.writeFileSync(path.join(fixture.root, "package.json"), '{"version":"01.2.3"}\n');
const result = runTagRelease(fixture);
assert.equal(result.status, 1);
assert.equal(result.stdout, "");
assertStructuredError(JSON.parse(result.stderr));
assert.deepEqual(readGitCalls(fixture), []);
});
});

View File

@@ -3,102 +3,49 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
cd "${REPO_ROOT}"
VERSION=$(node -p "require('./package.json').version")
# Read version from package.json
VERSION=$(node -p "require('${REPO_ROOT}/package.json').version")
if [ -z "$VERSION" ]; then
echo "Error: could not read version from package.json" >&2
exit 1
fi
TAG="v${VERSION}"
REHEARSAL_BRANCH="test/npm-staged-publish-rehearsal"
PUSH_TAG=false
if [ "$#" -eq 1 ] && [ "$1" = "--push" ]; then
PUSH_TAG=true
elif [ "$#" -ne 0 ]; then
echo "Usage: $0 [--push]" >&2
exit 1
fi
node "${SCRIPT_DIR}/release-preflight.js" --tag "${TAG}"
if [[ ! "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+-beta\.[0-9]+$ ]]; then
echo "Error: rehearsal releases require an X.Y.Z-beta.N version." >&2
exit 1
fi
echo "Version: ${VERSION}"
echo "Tag: ${TAG}"
CURRENT_BRANCH=$(git branch --show-current)
if [ "${CURRENT_BRANCH}" != "${REHEARSAL_BRANCH}" ]; then
echo "Error: rehearsal tags must be created from ${REHEARSAL_BRANCH}; current branch is '${CURRENT_BRANCH}'." >&2
exit 1
fi
if [ -n "$(git status --porcelain)" ]; then
echo "Error: the working tree must be clean before tagging." >&2
exit 1
fi
git fetch origin "${REHEARSAL_BRANCH}"
HEAD_SHA=$(git rev-parse HEAD)
FETCHED_REHEARSAL_SHA=$(git rev-parse "FETCH_HEAD^{commit}")
if [ "${HEAD_SHA}" != "${FETCHED_REHEARSAL_SHA}" ]; then
echo "Error: HEAD must exactly match origin/${REHEARSAL_BRANCH} before tagging." >&2
exit 1
fi
WORKFLOW=$(git show "${HEAD_SHA}:.github/workflows/release.yml")
if ! grep -Fq 'args: release --clean --skip=publish' <<<"${WORKFLOW}" ||
! grep -Eq 'npm stage publish .*--tag beta' <<<"${WORKFLOW}" ||
grep -Eq '^[[:space:]]*(run:[[:space:]]*)?npm[[:space:]]+publish([[:space:]]|$)' <<<"${WORKFLOW}" ||
grep -Eq 'gh[[:space:]]+release([[:space:]]|$)' <<<"${WORKFLOW}" ||
grep -Eq 'contents:[[:space:]]*write' <<<"${WORKFLOW}" ||
grep -Fq 'GITHUB_TOKEN:' <<<"${WORKFLOW}"; then
echo "Error: the tagged workflow must be stage-only, read-only for repository contents, and must not create a GitHub Release or publish npm live." >&2
exit 1
fi
set +e
NPM_VIEW_OUTPUT=$(npm view "@larksuite/cli@${VERSION}" version --registry=https://registry.npmjs.org/ 2>&1)
NPM_VIEW_STATUS=$?
set -e
if [ "${NPM_VIEW_STATUS}" -eq 0 ]; then
echo "Error: @larksuite/cli@${VERSION} already exists on npm." >&2
exit 1
fi
if ! grep -Eq 'E404|404 Not Found' <<<"${NPM_VIEW_OUTPUT}"; then
echo "Error: npm version lookup failed; refusing to assume the version is unused." >&2
echo "${NPM_VIEW_OUTPUT}" >&2
exit 1
fi
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
echo "Error: local tag ${TAG} already exists." >&2
exit 1
fi
REMOTE_TAG=$(git ls-remote --tags origin "refs/tags/${TAG}")
if [ -n "${REMOTE_TAG}" ]; then
echo "Error: remote tag ${TAG} already exists." >&2
exit 1
fi
if [ "${PUSH_TAG}" != true ]; then
echo "Checks passed. No tag was created or pushed."
echo "Run '$0 --push' only after reviewing the commit and workflow."
# Check if tag already exists locally
if git rev-parse "$TAG" >/dev/null 2>&1; then
echo "Tag ${TAG} already exists locally, skipping."
exit 0
fi
echo "Branch: ${CURRENT_BRANCH}"
echo "Commit: ${HEAD_SHA}"
printf 'Type %s to create and push this tag: ' "${TAG}"
read -r CONFIRM_TAG
if [ "${CONFIRM_TAG}" != "${TAG}" ]; then
echo "Error: confirmation did not exactly match ${TAG}." >&2
# Check if tag already exists on remote
if git ls-remote --tags origin "$TAG" | grep -q "$TAG"; then
echo "Tag ${TAG} already exists on remote, skipping."
exit 0
fi
# Ensure package.json changes are committed before tagging
if git diff --name-only | grep -q 'package.json' || git diff --cached --name-only | grep -q 'package.json'; then
echo "Error: package.json has uncommitted changes. Please commit before tagging." >&2
exit 1
fi
git tag "${TAG}" "${HEAD_SHA}"
git push origin "refs/tags/${TAG}:refs/tags/${TAG}"
# Ensure current branch is pushed to remote before tagging
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
LOCAL_SHA=$(git rev-parse HEAD)
REMOTE_SHA=$(git rev-parse "origin/${CURRENT_BRANCH}" 2>/dev/null || echo "")
if [ "$LOCAL_SHA" != "$REMOTE_SHA" ]; then
echo "Error: local branch '${CURRENT_BRANCH}' is not in sync with remote. Please push your commits first." >&2
exit 1
fi
echo "Successfully pushed tag ${TAG}"
# Create and push tag
git tag "$TAG"
git push origin "$TAG"
echo "Successfully created and pushed tag ${TAG}"

View File

@@ -0,0 +1,469 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package apps
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
const automationSkillDoc = "../../skills/lark-apps/references/lark-apps-automation.md"
const localDevSkillDoc = "../../skills/lark-apps/references/lark-apps-local-dev.md"
const larkAppsSkillDoc = "../../skills/lark-apps/SKILL.md"
const releaseGetSkillDoc = "../../skills/lark-apps/references/lark-apps-release-get.md"
func readAutomationSkillDoc(t *testing.T) string {
return readAppsSkillDoc(t, automationSkillDoc)
}
func readLocalDevSkillDoc(t *testing.T) string {
return readAppsSkillDoc(t, localDevSkillDoc)
}
func readReleaseGetSkillDoc(t *testing.T) string {
return readAppsSkillDoc(t, releaseGetSkillDoc)
}
func readAppsSkillDoc(t *testing.T, path string) string {
t.Helper()
raw, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read skill doc %s: %v", path, err)
}
return string(raw)
}
func skillSection(t *testing.T, doc, heading string) string {
t.Helper()
start := strings.Index(doc, heading)
if start < 0 {
t.Fatalf("missing skill section %q", heading)
}
rest := doc[start+len(heading):]
if next := strings.Index(rest, "\n## "); next >= 0 {
return rest[:next]
}
return rest
}
func skillSubsection(t *testing.T, doc, heading string) string {
t.Helper()
start := strings.Index(doc, heading)
if start < 0 {
t.Fatalf("missing skill subsection %q", heading)
}
rest := doc[start+len(heading):]
end := len(rest)
for _, marker := range []string{"\n### ", "\n## "} {
if next := strings.Index(rest, marker); next >= 0 && next < end {
end = next
}
}
return rest[:end]
}
func requireInOrder(t *testing.T, text string, tokens ...string) {
t.Helper()
offset := 0
for _, token := range tokens {
idx := strings.Index(text[offset:], token)
if idx < 0 {
t.Fatalf("missing %q after %q", token, text[:offset])
}
offset += idx + len(token)
}
}
func requireFirstOccurrencesInOrder(t *testing.T, text string, tokens ...string) {
t.Helper()
previous := -1
for _, token := range tokens {
idx := strings.Index(text, token)
if idx < 0 {
t.Fatalf("missing %q", token)
}
if idx <= previous {
t.Fatalf("first %q at %d must follow the previous contract token at %d", token, idx, previous)
}
previous = idx
}
}
func TestAutomationSkillContract_ChangedHandlerStartWaitsForThisRelease(t *testing.T) {
section := skillSubsection(t, readAutomationSkillDoc(t), "### 实现或更新 handler 后发布并启动/测试")
requireInOrder(t, section,
"仅当本轮确实需要新增或修改 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` handler",
"+automation-get",
"记录发布前状态",
"--name",
"项目 guide",
"按项目 guide 完成同名业务 handler 并本地验证。",
"在 Git 已确认/预授权时 commit然后执行",
"git push origin sprint/default",
"临时停用授权",
"+automation-disable",
"确认 disabled",
"+release-create --branch sprint/default",
"data.release_id",
"+release-get",
"data.status=finished",
"仅启动",
"+automation-enable",
"+automation-get",
"不制造 runtime probe",
"测试",
"运行时验证的操作级授权",
"完成全部 preflight",
"才执行 `+automation-enable`",
"真实 runtime",
"仅要求测试",
"恢复到发布前状态",
)
requireFirstOccurrencesInOrder(t, section,
"+automation-get",
"git push origin sprint/default",
"临时停用授权",
"+automation-disable",
"+release-create --branch sprint/default",
"data.status=finished",
"仅启动",
)
for _, boundary := range []string{
"仅当本轮确实需要新增或修改 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` handler且用户要求把这次代码发布后启动或测试时才使用此路径。",
"按项目 guide 完成同名业务 handler 并本地验证。",
"在 Git 已确认/预授权时 commit然后执行 `git push origin sprint/default`。",
"若该命令本身返回错误或未返回 `data.release_id`:视为确认未创建本轮 release新代码未上线原本 enabled 的 trigger 恢复 enabled 并回读、原本 disabled 的保持 disabled 后停止;若因超时等导致结果未知,保持 disabled先用 `+release-list --status finished --page-size 1` 核对是否已产生新 release 再决定。",
"只有 `data.status=finished` 才能继续;`publishing` 时每 20 秒继续轮询,整体最多约 5 分钟。",
"确认 `failed` 时报告发布失败,原本 enabled 的 trigger 仅在确认新代码未上线后恢复 enabled原本 disabled 的保持 disabled。",
"发布状态仍不确定时不得进入 enable、probe 或状态恢复分支。",
"**仅启动**:取得持续启动授权后执行 `+automation-enable`,并用 `+automation-get` 确认 enabled到此结束不制造 runtime probe。",
"**测试(含“启动并测试”)**:先按下节“运行时验证的操作级授权”完成全部 preflight",
"若用户仅要求测试而不是持续启动,只在本轮 release 已 `finished` 且 probe 成功后恢复到发布前状态",
"无论用户是仅测试还是启动并测试probe 失败、结果不确定或 enable 后提前结束时,一律 `+automation-disable` 并回读 disabled",
"不得把“发布前 enabled”当作失败后的恢复依据",
"没有通用的 `automation-debug` 或 trigger 日志 shortcut。",
} {
if !strings.Contains(section, boundary) {
t.Errorf("complete-start section must explain %q boundary", boundary)
}
}
}
func TestAutomationSkillContract_BindsTheExactNameAsUser(t *testing.T) {
doc := readAutomationSkillDoc(t)
for _, boundary := range []string{
"全部操作需 `--as user`AuthType: user。",
"当用户希望触发器实际执行业务代码时,先确认当前工作区是已初始化的应用项目,并读取其中与触发器任务匹配的 guide。",
"`--name` 是应用内唯一的 trigger 定位键;代码侧绑定名称必须与它逐字相同。不得用 trigger ID 或方法名代替它。具体 handler 语法和接入方式以项目 guide 为准。",
} {
if !strings.Contains(doc, boundary) {
t.Errorf("automation skill must preserve %q", boundary)
}
}
}
func TestAutomationSkillContract_RoutesAndDiagnosesUnfiredTriggers(t *testing.T) {
doc := readAutomationSkillDoc(t)
routeSection := skillSection(t, doc, "## 何时用本 skill路由锚点")
errorSection := skillSection(t, doc, "## 常见错误与决策场景")
if !strings.Contains(routeSection, "「触发器没反应 / enable 了不触发 / 为什么没执行 / 验证一下触发器」→ 先按「未触发时的诊断顺序」诊断;对 UPSERT 和 feishu-approval 仅验证配置边界,不承诺 handler 或 live 验证。") {
t.Error("routing anchors must direct unfired triggers to the bounded diagnostic flow")
}
if !strings.Contains(errorSection, "已证实的 cron、webhook、record-changeINSERT/UPDATE/DELETE按「未触发时的诊断顺序」排查UPSERT 和 feishu-approval 仅核对配置边界,不承诺 handler 或 live 验证。") {
t.Error("error table must preserve the bounded unfired-trigger diagnostic flow")
}
}
func TestAutomationSkillContract_ConfigurationStopsDisabled(t *testing.T) {
section := skillSubsection(t, readAutomationSkillDoc(t), "### 仅创建/配置触发器")
for _, boundary := range []string{
"用 `+automation-create` 创建,并省略 `--status` 或显式传 `disabled`,然后报告 name 和 disabled 状态。",
"不要传 `--status enabled`,也不要写 handler、commit/push、release 或 enable更不能把创建 API 成功称为“可运行”。",
"默认 disabled 是这个意图的终点,不是稍后自动 enable 的待办。",
} {
if !strings.Contains(section, boundary) {
t.Errorf("configuration-only section must preserve %q", boundary)
}
}
}
func TestAutomationSkillContract_EnableExistingTriggerDoesNotPublish(t *testing.T) {
doc := readAutomationSkillDoc(t)
section := skillSubsection(t, doc, "### 仅启用已有 disabled trigger")
routeSection := skillSection(t, doc, "## 何时用本 skill路由锚点")
requireInOrder(t, section,
"用户只要求启用已存在且 disabled 的 trigger",
"+automation-get",
"+release-list --status finished --page-size 1",
"已完成线上 release",
"当前线上应用",
"不能证明该 trigger name 已绑定 handler",
"+automation-enable",
"+automation-get",
"不得修改 handler、commit/push 或 release",
"对 UPSERT 或 feishu-approval 只改变配置状态",
)
if !strings.Contains(section, "未发布时不得自动创建 release也不得声称 trigger 已开始实际运行") {
t.Error("enable-only flow must distinguish configuration enablement from a published runtime")
}
if !strings.Contains(section, "即使存在 finished release也只能把 enable 报告为配置激活") {
t.Error("enable-only flow must not infer handler provenance from app release history")
}
if strings.Contains(section, "apps +get") || strings.Contains(section, "`is_published`") {
t.Error("enable-only flow must use finished release history instead of an optional app detail field")
}
for _, forbidden := range []string{"git push", "+release-create"} {
if strings.Contains(section, forbidden) {
t.Errorf("enable-only flow must not contain %q", forbidden)
}
}
if !strings.Contains(routeSection, "「启用 / 启动已有 trigger」→ 先核对现有状态;只启用时不要修改源码或发布应用。") {
t.Error("routing anchors must keep existing-trigger enablement separate from code release")
}
}
func TestAutomationSkillContract_TestExistingTriggerDoesNotPublish(t *testing.T) {
section := skillSubsection(t, readAutomationSkillDoc(t), "### 测试已有线上 trigger不改代码")
requireInOrder(t, section,
"用户要求测试已经发布的 trigger",
"+automation-get",
"+release-list --status finished --page-size 1",
"当前线上代码",
"不得为测试自动修改源码、commit/push 或 release",
"在任何临时 enable 之前完成",
"测试请求已明确包含临时 enable或另行取得 enable 授权",
"运行时验证的操作级授权",
"无论 probe 成功、失败、结果不确定,还是临时 enable 后提前结束或中断,最终都必须 `+automation-disable` 并回读 disabled",
)
for _, forbidden := range []string{"git push", "+release-create"} {
if strings.Contains(section, forbidden) {
t.Errorf("existing-trigger test flow must not contain %q", forbidden)
}
}
}
func TestAutomationSkillContract_HandlerOnlyStopsBeforeRelease(t *testing.T) {
section := skillSubsection(t, readAutomationSkillDoc(t), "### 仅完成 handler不发布/不启用)")
for _, boundary := range []string{
"创建或定位已明确 name 的 disabled trigger读取项目 guide按其要求实现同名业务 handler完成本地验证。",
"只在既有 Git 确认或预授权下 commit/push停止在 `+release-create` 和 `+automation-enable` 之前。",
"用户没有明确“发布好”时,先问,不能默认把完整应用上线。",
} {
if !strings.Contains(section, boundary) {
t.Errorf("handler-only section must preserve %q", boundary)
}
}
}
func TestAutomationSkillContract_HandlerOnlyExcludesUnverifiedRuntimeTypes(t *testing.T) {
section := skillSubsection(t, readAutomationSkillDoc(t), "### 仅完成 handler不发布/不启用)")
if !strings.Contains(section, "仅对 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` 使用此路径。") {
t.Error("handler-only flow must exclude UPSERT and feishu-approval without a verified runtime contract")
}
}
func TestAutomationSkillContract_PublishedHandlerStaysDisabled(t *testing.T) {
section := skillSubsection(t, readAutomationSkillDoc(t), "### 把 handler 发布好,但先不要启动")
for _, boundary := range []string{
"仅对 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` 使用此路径。",
"先用 `+automation-get` 定位;不存在时用 `+automation-create` 创建同名 disabled trigger再次回读确认。",
"已存在时记录它是否 enabled。",
"若 trigger 已 enabled先说明发布前必须临时停用以及可能造成的运行中断并取得这次临时停用授权未获授权时停止在发布前。",
"取得授权后,在发布前执行 `+automation-disable`,并再次用 `+automation-get` 确认 disabled。",
"按项目 guide 完成同名业务 handler 并本地验证后commit、`git push origin sprint/default`。",
"随后发布完整应用:",
"若 `+release-create` 本身返回错误或未返回 `data.release_id`:视为确认未创建本轮 release新代码未上线原本 enabled 的 trigger 恢复 enabled 并回读、原本 disabled 的保持 disabled然后停止若因超时等导致创建结果未知保持 disabled先用 `+release-list --status finished --page-size 1` 核对是否已产生新 release 再决定。",
"取得 `data.release_id` 后,对**这一轮** ID 调用 `+release-get``publishing` 时每 20 秒继续轮询,整体最多约 5 分钟;超时且状态仍不确定时报告 `release_id` 和当前 status并保持 disabled只有 `data.status=finished` 才算完成。",
"确认 `failed` 且新代码未上线时,原本 enabled 的 trigger 恢复 enabled 并回读,原本 disabled 的保持 disabled。",
"release 是整个应用上线可能影响既有线上功能未获得启动或测试授权时finished 后始终保持 disabled不执行 `+automation-enable`。",
} {
if !strings.Contains(section, boundary) {
t.Errorf("publish-without-start section must preserve %q", boundary)
}
}
requireFirstOccurrencesInOrder(t, section,
"+automation-get",
"git push origin sprint/default",
"临时停用授权",
"+automation-disable",
"+release-create",
)
}
func TestAutomationSkillContract_UPSERTAndApprovalStayConfigurationOnly(t *testing.T) {
section := skillSubsection(t, readAutomationSkillDoc(t), "### UPSERT 与飞书审批边界")
for _, boundary := range []string{
"record-change 的 UPSERT 可创建 disabled 配置,但当前没有已证实的运行时代码契约;不得静默按 UPDATE 处理,也不得承诺 handler 或 live 验证。",
"feishu-approval 可创建 disabled 配置,并读取或更新 `event_type`、对应 status 和可选 `approval_code`。",
"当前没有已证实的运行时 handler 契约或实际投递验证;不要把 enable 或审批 API 成功称为业务代码已执行。",
} {
if !strings.Contains(section, boundary) {
t.Errorf("UPSERT/approval boundary section must preserve %q", boundary)
}
}
}
func TestAutomationSkillContract_RuntimeProbeRequiresOperationScope(t *testing.T) {
section := skillSubsection(t, readAutomationSkillDoc(t), "### 运行时验证的操作级授权")
for _, boundary := range []string{
"启用 trigger 的授权不等于制造 runtime 事件的授权,测试授权也不等于任意数据库写入授权。",
"record-change 在执行任何 DML 前,必须明确并取得覆盖以下作用域的授权",
"环境、表、操作、精确测试记录或筛选条件、payload、预期结果和清理方式",
"优先使用专用测试记录",
"`DELETE`",
"[lark-apps-db-execute.md](lark-apps-db-execute.md)",
"先 `SELECT count(*)`、执行 `--dry-run`",
"取得针对该删除目标的明确授权",
"+automation-list --trigger-type record-change --all",
"同一环境、表和操作可能命中的其他 enabled trigger",
"聚合业务影响",
"恢复 UPDATE 或清理 INSERT 也可能再次触发自动化",
"缺少安全、已授权且可清理的事件入口时,记录 blocked",
} {
if !strings.Contains(section, boundary) {
t.Errorf("runtime probe section must preserve %q", boundary)
}
}
}
func TestAutomationSkillContract_UsesResolvableSharedSkillLink(t *testing.T) {
doc := readAutomationSkillDoc(t)
if strings.Contains(doc, "](../lark-shared/SKILL.md)") {
t.Error("automation reference must not resolve lark-shared inside the lark-apps directory")
}
if !strings.Contains(doc, "](../../lark-shared/SKILL.md)") {
t.Error("automation reference must link to the sibling lark-shared skill")
}
sharedSkillDoc := filepath.Clean(filepath.Join(filepath.Dir(automationSkillDoc), "../../lark-shared/SKILL.md"))
if _, err := os.Stat(sharedSkillDoc); err != nil {
t.Fatalf("automation reference target %s must exist: %v", sharedSkillDoc, err)
}
}
func TestAppsSkillContract_AllSharedSkillLinksResolve(t *testing.T) {
docs := []string{larkAppsSkillDoc}
references, err := filepath.Glob("../../skills/lark-apps/references/*.md")
if err != nil {
t.Fatalf("glob lark-apps references: %v", err)
}
docs = append(docs, references...)
sharedLink := regexp.MustCompile(`\]\(([^)]+lark-shared/SKILL\.md)\)`)
for _, docPath := range docs {
doc := readAppsSkillDoc(t, docPath)
for _, match := range sharedLink.FindAllStringSubmatch(doc, -1) {
target := filepath.Clean(filepath.Join(filepath.Dir(docPath), match[1]))
if _, err := os.Stat(target); err != nil {
t.Errorf("%s shared-skill link %q resolves to missing target %s: %v", docPath, match[1], target, err)
}
}
}
}
func TestLocalDevSkillContract_UsesProjectGuideWithoutSyncInternals(t *testing.T) {
section := skillSection(t, readLocalDevSkillDoc(t), "## Trigger guide 的项目边界")
for _, boundary := range []string{
"先查看工作区 `.agents/skills/`,读取与自动化任务匹配的 `trigger-guide`。",
"文件缺失或不能覆盖当前任务时,报告项目缺少可用的领域 guide不要在本 lark-cli reference 中猜测安装命令、版本或包内目录。",
} {
if !strings.Contains(section, boundary) {
t.Errorf("trigger-guide boundary section must explain %q", boundary)
}
}
for _, implementationShape := range []string{
"npx ", "skills sync", "data.", "skills_", "_CACHE_DIR", "nestjs-",
"@lark-apaas/miaoda-cli", "@lark-apaas/coding-steering", "miaoda-coding", "skills_common/",
} {
if strings.Contains(section, implementationShape) {
t.Errorf("local-dev skill must not expose project-sync implementation shape %q", implementationShape)
}
}
}
func TestAppsSkillContract_DoesNotExposeSteeringImplementation(t *testing.T) {
for name, doc := range map[string]string{
"automation": readAutomationSkillDoc(t),
"local-dev": readLocalDevSkillDoc(t),
} {
for _, implementationShape := range []string{
"npx ", "skills sync", "@lark-apaas/miaoda-cli", "@lark-apaas/coding-steering", "miaoda-coding", "skills_common/",
} {
if strings.Contains(doc, implementationShape) {
t.Errorf("%s skill must not expose project-sync implementation shape %q", name, implementationShape)
}
}
}
}
func TestLocalDevSkillContract_UsesEnvironmentAndDefersEnableToAutomationSOP(t *testing.T) {
doc := readLocalDevSkillDoc(t)
releaseSection := skillSection(t, doc, "## 改完代码后部署上线")
for _, legacy := range []string{"--env dev", "--env online"} {
if strings.Contains(doc, legacy) {
t.Errorf("local-dev skill must not recommend legacy %q", legacy)
}
}
for _, boundary := range []string{
"`publishing` 时每 20 秒继续轮询,整体最多约 5 分钟;超时仍未完成时停止本轮轮询、报告 `release_id` 和当前 status。",
"若本次改动包含自动化 handler在执行本节通用 commit/push/release 序列前就转到 [automation SOP](lark-apps-automation.md) 的匹配路径,由该 SOP 负责完整的状态门禁、commit/push、release 和可选 enable/test不要先按本节发布再补 trigger 状态检查。",
"用户只要求启用已有 trigger 时,转到 [automation SOP 的「仅启用已有 disabled trigger」路径](lark-apps-automation.md#仅启用已有-disabled-trigger);不得因 enable 反向修改 handler、commit/push 或 release。",
"使用 `--environment dev|online`,不要使用旧的 `--env`。只有确认应用已开启多环境时才引导 `--environment dev`;单环境应用省略 `--environment`(服务端选 online或显式传 `--environment online`。",
} {
if !strings.Contains(doc, boundary) {
t.Errorf("local-dev skill must preserve %q", boundary)
}
}
routeIndex := strings.Index(releaseSection, "若本次改动包含自动化 handler")
releaseIndex := strings.Index(releaseSection, "+release-create")
if routeIndex < 0 || releaseIndex < 0 || routeIndex >= releaseIndex {
t.Error("automation routing must appear before the generic release sequence")
}
}
func TestLocalDevSkillContract_DoesNotRequireOnlineURL(t *testing.T) {
section := skillSection(t, readLocalDevSkillDoc(t), "## 改完代码后部署上线")
if strings.Contains(section, "`finished` 成功时该命令输出已含 `online_url`") {
t.Error("release guidance must not claim every finished release includes online_url")
}
if !strings.Contains(section, "若返回 `online_url`,可直接使用;未返回时不要编造链接。") {
t.Error("release guidance must explain that online_url is optional")
}
}
func TestLocalDevSkillContract_TreatsErrorLogsAsOptional(t *testing.T) {
section := skillSection(t, readLocalDevSkillDoc(t), "## 改完代码后部署上线")
if !strings.Contains(section, "`failed` 时若返回非空 `error_logs`,据此给出失败原因;否则只报告 `release_id` 和当前 status不要编造原因") {
t.Error("release guidance must not promise error_logs on every failed release")
}
}
func TestReleaseSkillContract_TreatsOptionalOutputAsOptional(t *testing.T) {
releaseGet := readReleaseGetSkillDoc(t)
for _, boundary := range []string{
"`finished` 后才可能有 `online_url`。",
"若输出含 `online_url`,直接读取它作为本轮发布的线上访问链接;未返回时只报告发布完成,不要编造链接。",
"若输出含 `error_logs``step`/`error_log`),据此向用户转述关键失败步骤和可行动修复;未返回时不要编造失败原因。",
} {
if !strings.Contains(releaseGet, boundary) {
t.Errorf("release-get skill must preserve optional-output boundary %q", boundary)
}
}
}

View File

@@ -8,7 +8,6 @@ import (
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/client"
)
func appsValidationError(format string, args ...any) *errs.ValidationError {
@@ -74,32 +73,3 @@ func appsInputPathEntryError(path string, err error) error {
func appsFileIOError(err error, format string, args ...any) *errs.InternalError {
return errs.NewInternalError(errs.SubtypeFileIO, format, args...).WithCause(err)
}
// enrichHTMLPublishAPIError adapts a typed failure from the HTML publish
// endpoint: refines endpoint-scoped business codes, prefixes the message with
// command context, and attaches endpoint-specific recovery hints. A
// still-untyped error is lifted at the SDK boundary instead.
func enrichHTMLPublishAPIError(err error) error {
if err == nil {
return nil
}
p, ok := errs.ProblemOf(err)
if !ok {
return client.WrapDoAPIError(err)
}
// The HTML publish business codes (90001/90002) are scoped to this
// endpoint, not service-global, so their subtype classification lives
// here instead of the global errclass code table. Only an
// otherwise-unclassified API error is refined; a stronger upstream
// classification is never overridden.
if p.Category == errs.CategoryAPI && p.Subtype == errs.SubtypeUnknown && p.Code == errCodeAppNotFound {
p.Subtype = errs.SubtypeNotFound
}
if p.Message != "" {
p.Message = "html-publish failed: " + p.Message
}
if hint := buildHTMLPublishFailureHint(p.Code); hint != "" {
p.Hint = hint
}
return err
}

View File

@@ -57,57 +57,3 @@ func TestAppsFileIOError_ClassifiesInternalFileIO(t *testing.T) {
t.Fatalf("cause chain not preserved: %v", err)
}
}
func TestEnrichHTMLPublishAPIError_LiftsUntypedBoundaryError(t *testing.T) {
err := enrichHTMLPublishAPIError(errors.New("connection reset by peer"))
problem := requireAppsProblem(t, err, errs.CategoryNetwork)
if problem.Subtype != errs.SubtypeNetworkTransport {
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeNetworkTransport)
}
}
func TestEnrichHTMLPublishAPIError_PreservesClassificationAndAddsHint(t *testing.T) {
err := errs.NewAPIError(errs.SubtypeUnknown, "build failed").
WithCode(errCodeBuildFailed).
WithLogID("logid-build-failed")
got := enrichHTMLPublishAPIError(err)
if got != err {
t.Fatalf("typed error should be enriched in place")
}
problem := requireAppsAPIProblem(t, got)
if problem.Subtype != errs.SubtypeUnknown {
t.Fatalf("subtype = %q, want %q unchanged", problem.Subtype, errs.SubtypeUnknown)
}
if problem.Code != errCodeBuildFailed {
t.Fatalf("code = %d, want %d", problem.Code, errCodeBuildFailed)
}
if problem.LogID != "logid-build-failed" {
t.Fatalf("log_id = %q, want preserved", problem.LogID)
}
if !strings.Contains(problem.Message, "html-publish failed") {
t.Fatalf("message = %q, want html-publish context", problem.Message)
}
if problem.Hint == "" {
t.Fatalf("expected known-code recovery hint")
}
}
func TestEnrichHTMLPublishAPIError_ClassifiesAppNotFoundLocally(t *testing.T) {
err := errs.NewAPIError(errs.SubtypeUnknown, "app not found").WithCode(errCodeAppNotFound)
problem := requireAppsAPIProblem(t, enrichHTMLPublishAPIError(err))
if problem.Subtype != errs.SubtypeNotFound {
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeNotFound)
}
}
func TestEnrichHTMLPublishAPIError_KeepsStrongerClassification(t *testing.T) {
err := errs.NewAPIError(errs.SubtypeRateLimit, "throttled").WithCode(errCodeAppNotFound)
problem := requireAppsAPIProblem(t, enrichHTMLPublishAPIError(err))
if problem.Subtype != errs.SubtypeRateLimit {
t.Fatalf("subtype = %q, want %q unchanged", problem.Subtype, errs.SubtypeRateLimit)
}
}

View File

@@ -17,10 +17,11 @@ import (
var AppsGet = common.Shortcut{
Service: appsService,
Command: "+get",
Description: "Get a single app's detail by app ID (returns app_type, name, description, publish status, etc.)",
Description: "Get a single app's detail by app ID or meta token (returns app_type, name, description, publish status, etc.)",
Risk: "read",
Tips: []string{
"Example: lark-cli apps +get --app-id <app_id>",
"Example: lark-cli apps +get --app-id <meta_token>",
"Example: lark-cli apps +get --app-id <app_id> --dry-run",
"Tip: extract app type with --jq '.data.app.app_type'",
},
@@ -28,7 +29,7 @@ var AppsGet = common.Shortcut{
AuthTypes: []string{"user"},
HasFormat: true,
Flags: []common.Flag{
{Name: "app-id", Desc: "app ID", Required: true},
{Name: "app-id", Desc: "app ID or meta token", Required: true},
},
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
if strings.TrimSpace(rctx.Str("app-id")) == "" {
@@ -40,7 +41,7 @@ var AppsGet = common.Shortcut{
appID := strings.TrimSpace(rctx.Str("app-id"))
return common.NewDryRunAPI().
GET(fmt.Sprintf("%s/apps/%s", apiBasePath, validate.EncodePathSegment(appID))).
Desc("Get app detail (returns app_id, app_type, name, description, icon_url, created_at, updated_at, is_published)")
Desc("Get app detail (returns app_id, meta_token, app_type, name, description, icon_url, created_at, updated_at, is_published)")
},
Execute: func(ctx context.Context, rctx *common.RuntimeContext) error {
appID := strings.TrimSpace(rctx.Str("app-id"))
@@ -54,6 +55,9 @@ var AppsGet = common.Shortcut{
return
}
fmt.Fprintf(w, "app_id: %v\n", app["app_id"])
if mt, ok := app["meta_token"].(string); ok && mt != "" {
fmt.Fprintf(w, "meta_token: %s\n", mt)
}
fmt.Fprintf(w, "app_type: %v\n", app["app_type"])
fmt.Fprintf(w, "name: %v\n", app["name"])
if desc, ok := app["description"].(string); ok && desc != "" {

View File

@@ -14,7 +14,6 @@ import (
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/client"
"github.com/larksuite/cli/internal/validate"
"github.com/larksuite/cli/shortcuts/common"
)
@@ -38,9 +37,13 @@ var AppsHTMLPublish = common.Shortcut{
{Name: "allow-sensitive", Type: "bool", Desc: "skip the credential-file scan (allow .env / .npmrc / .aws/credentials / etc. in the publish payload)"},
},
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
if strings.TrimSpace(rctx.Str("app-id")) == "" {
appID := strings.TrimSpace(rctx.Str("app-id"))
if appID == "" {
return appsValidationParamError("--app-id", "--app-id is required")
}
if err := validateRealAppID(appID); err != nil {
return err
}
path := strings.TrimSpace(rctx.Str("path"))
if path == "" {
return appsValidationParamError("--path", "--path is required")
@@ -73,9 +76,11 @@ var AppsHTMLPublish = common.Shortcut{
appID := strings.TrimSpace(rctx.Str("app-id"))
path := strings.TrimSpace(rctx.Str("path"))
dry := common.NewDryRunAPI()
dry.Desc("Pack tar.gz and publish HTML app (actual API path determined at runtime by app type; returns url or release_id)")
dry.POST(fmt.Sprintf("%s/apps/%s/upload_and_release_html_code", apiBasePath, validate.EncodePathSegment(appID))).
Set("content_type", "multipart/form-data")
dry.Desc("Pack tar.gz → GET pre_release for TOS upload URL → PUT tar.gz to TOS → POST release-create with tos_path; returns release_id")
dry.GET(fmt.Sprintf("%s/apps/%s/pre_release", apiBasePath, validate.EncodePathSegment(appID))).
PUT("<presigned_upload_url> (from pre_release response)").
POST(fmt.Sprintf(releaseCreatePath, validate.EncodePathSegment(appID))).
Body(map[string]string{"tos_path": "<from pre_release response>"})
candidates, err := walkHTMLPublishCandidates(rctx.FileIO(), path)
if err != nil {
@@ -123,16 +128,7 @@ var AppsHTMLPublish = common.Shortcut{
Path: strings.TrimSpace(rctx.Str("path")),
}
appType := queryAppType(ctx, rctx, spec.AppID)
var out map[string]interface{}
var err error
if appType == "modern_html" {
out, err = runHTMLPublishTOS(ctx, rctx, spec)
} else {
client := appsHTMLPublishAPI{runtime: rctx}
out, err = runHTMLPublish(ctx, rctx.FileIO(), client, spec)
}
out, err := runHTMLPublishTOS(ctx, rctx, spec)
if err != nil {
return err
}
@@ -264,25 +260,7 @@ func prepareHTMLPublishTarball(fio fileio.FileIO, path string) (*htmlPublishTarb
return tarball, nil
}
func runHTMLPublish(ctx context.Context, fio fileio.FileIO, publisher appsHTMLPublishClient, spec appsHTMLPublishSpec) (map[string]interface{}, error) {
tarball, err := prepareHTMLPublishTarball(fio, spec.Path)
if err != nil {
return nil, err
}
resp, err := publisher.HTMLPublish(ctx, spec.AppID, tarball)
if err != nil {
return nil, client.WrapDoAPIError(err)
}
out := map[string]interface{}{}
if resp.URL != "" {
out["url"] = resp.URL
}
return out, nil
}
// runHTMLPublishTOS handles the modern_html publish path: validate → tar.gz →
// runHTMLPublishTOS handles the publish path: validate → tar.gz →
// call pre_release to get TOS upload URL → upload tar.gz to TOS → return
// tos_path for +release-create --tos-path.
func runHTMLPublishTOS(ctx context.Context, rctx *common.RuntimeContext, spec appsHTMLPublishSpec) (map[string]interface{}, error) {

View File

@@ -5,7 +5,6 @@ package apps
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"os"
@@ -23,20 +22,6 @@ import (
"github.com/larksuite/cli/shortcuts/common"
)
type fakeAppsHTMLPublishClient struct {
resp *htmlPublishResponse
err error
calls []string
}
func (f *fakeAppsHTMLPublishClient) HTMLPublish(ctx context.Context, appID string, tarball *htmlPublishTarball) (*htmlPublishResponse, error) {
f.calls = append(f.calls, appID)
if f.err != nil {
return nil, f.err
}
return f.resp, nil
}
func writeAppsSampleSite(t *testing.T) string {
t.Helper()
dir := t.TempDir()
@@ -46,71 +31,19 @@ func writeAppsSampleSite(t *testing.T) string {
return dir
}
func TestRunHTMLPublish_HappyPath(t *testing.T) {
site := writeAppsSampleSite(t)
fake := &fakeAppsHTMLPublishClient{
resp: &htmlPublishResponse{URL: "https://miaoda/app_x"},
}
out, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: site})
if err != nil {
t.Fatalf("err=%v", err)
}
if out["url"] != "https://miaoda/app_x" {
t.Fatalf("url=%v", out["url"])
}
if len(fake.calls) != 1 || fake.calls[0] != "app_x" {
t.Fatalf("calls=%v", fake.calls)
}
}
func TestRunHTMLPublish_OnlyURLInEnvelope(t *testing.T) {
// Pin 概要设计 §5.3 不变量 4 "同步语义不会变成异步" (legacy html path only):
// envelope 只含 url未来若有人加 status / release_id 字段会被这个测试拦截。
site := writeAppsSampleSite(t)
fake := &fakeAppsHTMLPublishClient{
resp: &htmlPublishResponse{URL: "https://miaoda/app_x"},
}
out, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: site})
if err != nil {
t.Fatalf("err=%v", err)
}
if len(out) != 1 {
t.Fatalf("envelope should only contain 'url', got %d keys: %v", len(out), out)
}
if _, ok := out["url"]; !ok {
t.Fatalf("envelope missing 'url': %v", out)
}
}
func TestRunHTMLPublish_ClientErrorPropagated(t *testing.T) {
site := writeAppsSampleSite(t)
wantErr := errors.New("server timeout")
fake := &fakeAppsHTMLPublishClient{err: wantErr}
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: site})
if !errors.Is(err, wantErr) {
t.Fatalf("err=%v", err)
}
}
func TestRunHTMLPublish_PathNotFound(t *testing.T) {
fake := &fakeAppsHTMLPublishClient{}
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: "/nonexistent"})
func TestPrepareHTMLPublishTarball_PathNotFound(t *testing.T) {
_, err := prepareHTMLPublishTarball(newTestFIO(), "/nonexistent")
if err == nil {
t.Fatalf("expected error")
}
if len(fake.calls) != 0 {
t.Fatalf("client should not be called when path invalid")
}
}
func TestRunHTMLPublish_DirRequiresIndexHTML(t *testing.T) {
// 目录形态:缺 index.html 应该被拦
func TestPrepareHTMLPublishTarball_DirRequiresIndexHTML(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "foo.html"), []byte("<html></html>"), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
fake := &fakeAppsHTMLPublishClient{}
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: dir})
_, err := prepareHTMLPublishTarball(newTestFIO(), dir)
if err == nil {
t.Fatalf("expected error for missing index.html")
}
@@ -121,13 +54,9 @@ func TestRunHTMLPublish_DirRequiresIndexHTML(t *testing.T) {
if problem.Hint == "" {
t.Fatalf("expected non-empty hint")
}
if len(fake.calls) != 0 {
t.Fatalf("client should not be called when index.html missing")
}
}
func TestRunHTMLPublish_DirWithIndexHTMLPasses(t *testing.T) {
// 目录含 index.html 应该正常走完
func TestPrepareHTMLPublishTarball_DirWithIndexHTMLPasses(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "index.html"), []byte("<html></html>"), 0o644); err != nil {
t.Fatalf("write fixture: %v", err)
@@ -135,57 +64,49 @@ func TestRunHTMLPublish_DirWithIndexHTMLPasses(t *testing.T) {
if err := os.WriteFile(filepath.Join(dir, "extra.html"), []byte("<html></html>"), 0o644); err != nil {
t.Fatalf("write fixture: %v", err)
}
fake := &fakeAppsHTMLPublishClient{resp: &htmlPublishResponse{URL: "https://miaoda/app_x"}}
if _, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: dir}); err != nil {
tarball, err := prepareHTMLPublishTarball(newTestFIO(), dir)
if err != nil {
t.Fatalf("err=%v", err)
}
if len(fake.calls) != 1 {
t.Fatalf("client should be called when index.html present")
if tarball == nil || tarball.Size == 0 {
t.Fatalf("expected non-empty tarball")
}
}
func TestRunHTMLPublish_SingleFileRejectedIfNotNamedIndex(t *testing.T) {
// 单文件形态:文件名不是 index.html 也要拦
func TestPrepareHTMLPublishTarball_SingleFileRejectedIfNotNamedIndex(t *testing.T) {
dir := t.TempDir()
single := filepath.Join(dir, "foo.html")
if err := os.WriteFile(single, []byte("<html></html>"), 0o644); err != nil {
t.Fatalf("write fixture: %v", err)
}
fake := &fakeAppsHTMLPublishClient{}
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: single})
_, err := prepareHTMLPublishTarball(newTestFIO(), single)
if err == nil {
t.Fatalf("single-file path 'foo.html' should be rejected (not named index.html)")
}
requireAppsValidationProblem(t, err)
if len(fake.calls) != 0 {
t.Fatalf("client must not be called when index.html missing")
}
}
func TestRunHTMLPublish_SingleFileNamedIndexPasses(t *testing.T) {
// 单文件形态:文件名恰好就是 index.html → 放行
func TestPrepareHTMLPublishTarball_SingleFileNamedIndexPasses(t *testing.T) {
dir := t.TempDir()
single := filepath.Join(dir, "index.html")
if err := os.WriteFile(single, []byte("<html></html>"), 0o644); err != nil {
t.Fatalf("write fixture: %v", err)
}
fake := &fakeAppsHTMLPublishClient{resp: &htmlPublishResponse{URL: "https://miaoda/app_x"}}
if _, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: single}); err != nil {
tarball, err := prepareHTMLPublishTarball(newTestFIO(), single)
if err != nil {
t.Fatalf("err=%v", err)
}
if len(fake.calls) != 1 {
t.Fatalf("client should be called for single index.html")
if tarball == nil || tarball.Size == 0 {
t.Fatalf("expected non-empty tarball")
}
}
func TestRunHTMLPublish_RejectsOversizeTarball(t *testing.T) {
// 把上限调到 100 字节验证拦截defer 恢复原值避免污染其它测试。
func TestPrepareHTMLPublishTarball_RejectsOversizeTarball(t *testing.T) {
orig := maxHTMLPublishTarballBytes
maxHTMLPublishTarballBytes = 100
defer func() { maxHTMLPublishTarballBytes = orig }()
dir := t.TempDir()
// 写 index.html满足新加的 index 校验)+ 大文件超 100 字节上限。
if err := os.WriteFile(filepath.Join(dir, "index.html"), []byte("<html></html>"), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
@@ -194,8 +115,7 @@ func TestRunHTMLPublish_RejectsOversizeTarball(t *testing.T) {
t.Fatalf("write: %v", err)
}
fake := &fakeAppsHTMLPublishClient{}
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: dir})
_, err := prepareHTMLPublishTarball(newTestFIO(), dir)
if err == nil {
t.Fatalf("expected oversize error")
}
@@ -206,9 +126,6 @@ func TestRunHTMLPublish_RejectsOversizeTarball(t *testing.T) {
if problem.Hint == "" {
t.Fatalf("expected non-empty hint")
}
if len(fake.calls) != 0 {
t.Fatalf("client should not be called when tarball oversize")
}
}
func TestMaxHTMLPublishTarballBytes_Default(t *testing.T) {
@@ -264,8 +181,17 @@ func TestAppsHTMLPublish_DryRunPrintsManifest(t *testing.T) {
t.Fatalf("dry-run err=%v", err)
}
got := stdout.String()
if !strings.Contains(got, "/open-apis/spark/v1/apps/app_x/upload_and_release_html_code") {
t.Fatalf("dry-run missing endpoint: %s", got)
if !strings.Contains(got, "/open-apis/spark/v1/apps/app_x/pre_release") {
t.Fatalf("dry-run missing pre_release endpoint: %s", got)
}
if !strings.Contains(got, "presigned_upload_url") {
t.Fatalf("dry-run missing TOS PUT step: %s", got)
}
if !strings.Contains(got, "/open-apis/spark/v1/apps/app_x/releases") {
t.Fatalf("dry-run missing release-create endpoint: %s", got)
}
if !strings.Contains(got, "tos_path") {
t.Fatalf("dry-run missing tos_path in release-create body: %s", got)
}
if !strings.Contains(got, "index.html") {
t.Fatalf("dry-run missing file list: %s", got)
@@ -500,9 +426,7 @@ func TestRunHTMLPublish_RejectsOversizeRawCandidates(t *testing.T) {
t.Fatalf("write: %v", err)
}
fake := &fakeAppsHTMLPublishClient{}
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake,
appsHTMLPublishSpec{AppID: "app_x", Path: dir})
_, err := prepareHTMLPublishTarball(newTestFIO(), dir)
if err == nil {
t.Fatalf("expected raw-size cap to fire")
}
@@ -510,9 +434,6 @@ func TestRunHTMLPublish_RejectsOversizeRawCandidates(t *testing.T) {
if !strings.Contains(problem.Message, "raw") || !strings.Contains(problem.Message, "bytes") {
t.Fatalf("expected message to explain raw-byte cap, got %q", problem.Message)
}
if len(fake.calls) != 0 {
t.Fatalf("client must not be called when raw cap hit")
}
}
func TestOversizeHTMLFiles(t *testing.T) {
@@ -555,8 +476,7 @@ func TestRunHTMLPublish_RejectsOversizeHTMLFile(t *testing.T) {
if err := os.WriteFile(filepath.Join(dir, "big.html"), []byte(strings.Repeat("x", 4096)), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
fake := &fakeAppsHTMLPublishClient{}
_, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: dir})
_, err := prepareHTMLPublishTarball(newTestFIO(), dir)
if err == nil {
t.Fatalf("expected per-file oversize error")
}
@@ -567,13 +487,9 @@ func TestRunHTMLPublish_RejectsOversizeHTMLFile(t *testing.T) {
if problem.Hint == "" {
t.Fatalf("expected non-empty hint")
}
if len(fake.calls) != 0 {
t.Fatalf("client must not be called when an HTML file is oversize")
}
}
func TestRunHTMLPublish_IgnoresOversizeNonHTML(t *testing.T) {
// 单 .html 上限调小,但超限文件是 .png → 不被本护栏拦截,正常发布。
func TestPrepareHTMLPublishTarball_IgnoresOversizeNonHTML(t *testing.T) {
orig := maxHTMLPublishSingleHTMLFileBytes
maxHTMLPublishSingleHTMLFileBytes = 100
defer func() { maxHTMLPublishSingleHTMLFileBytes = orig }()
@@ -585,12 +501,12 @@ func TestRunHTMLPublish_IgnoresOversizeNonHTML(t *testing.T) {
if err := os.WriteFile(filepath.Join(dir, "big.png"), []byte(strings.Repeat("x", 4096)), 0o644); err != nil {
t.Fatalf("write: %v", err)
}
fake := &fakeAppsHTMLPublishClient{resp: &htmlPublishResponse{URL: "https://miaoda/app_x"}}
if _, err := runHTMLPublish(context.Background(), newTestFIO(), fake, appsHTMLPublishSpec{AppID: "app_x", Path: dir}); err != nil {
tarball, err := prepareHTMLPublishTarball(newTestFIO(), dir)
if err != nil {
t.Fatalf("non-html oversize must not be blocked by the .html cap: %v", err)
}
if len(fake.calls) != 1 {
t.Fatalf("client should be called; calls=%v", fake.calls)
if tarball == nil || tarball.Size == 0 {
t.Fatalf("expected non-empty tarball")
}
}

View File

@@ -74,15 +74,18 @@ type appTypePolicy struct {
// skipSkillsSync skips the conditional `npx ... skills sync --local` step on
// the non-empty (`app sync`) scaffold path.
skipSkillsSync bool
// skipAppSync skips `npx ... app sync` on the non-empty repo path.
skipAppSync bool
}
// appTypePolicies maps an app_type to its +init control strategy. Types absent
// from the map get the zero-value policy (install runs, env is pulled, skills
// are synced).
var appTypePolicies = map[string]appTypePolicy{
// modern_html is a static HTML site: no dependencies to install, no startup
// env vars to pull, and no steering skills to sync.
"modern_html": {skipInstall: true, skipEnvPull: true, skipSkillsSync: true},
// modern_html / html are static HTML sites: no dependencies to install,
// no startup env vars to pull, no steering skills to sync, and no app sync.
"modern_html": {skipInstall: true, skipEnvPull: true, skipSkillsSync: true, skipAppSync: true},
"html": {skipInstall: true, skipEnvPull: true, skipSkillsSync: true, skipAppSync: true},
}
// policyForAppType returns the +init control strategy for appType. Unlisted
@@ -122,9 +125,13 @@ var AppsInit = common.Shortcut{
{Name: "source-path", Desc: "path to existing source files (e.g. HTML output from an agent) to incorporate into the initialized project"},
},
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
if strings.TrimSpace(rctx.Str("app-id")) == "" {
appID := strings.TrimSpace(rctx.Str("app-id"))
if appID == "" {
return appsValidationParamError("--app-id", "--app-id is required")
}
if err := validateRealAppID(appID); err != nil {
return err
}
if sp := strings.TrimSpace(rctx.Str("source-path")); sp != "" {
if err := charcheck.RejectControlChars(sp, "--source-path"); err != nil {
return appsValidationParamError("--source-path", "%v", err).WithCause(err)
@@ -334,11 +341,19 @@ func ensureMetaAppID(dir, appID string) error {
// each is not already resolvable from local/global/system config, so a
// developer's existing identity is never overwritten. Each key is handled
// independently (a machine with only user.name set still gets a default email).
func ensureGitIdentity(ctx context.Context, dir string) error {
if err := ensureGitConfigValue(ctx, dir, "user.name", defaultGitUserName); err != nil {
func ensureGitIdentity(ctx context.Context, dir, authorName, authorEmail string) error {
name := strings.TrimSpace(authorName)
if name == "" {
name = defaultGitUserName
}
email := strings.TrimSpace(authorEmail)
if email == "" {
email = defaultGitUserEmail
}
if err := ensureGitConfigValue(ctx, dir, "user.name", name); err != nil {
return err
}
return ensureGitConfigValue(ctx, dir, "user.email", defaultGitUserEmail)
return ensureGitConfigValue(ctx, dir, "user.email", email)
}
// ensureGitConfigValue sets <key>=fallback in the repo-local git config when key
@@ -400,13 +415,16 @@ func runScaffold(ctx context.Context, dir, appID, appType, sourcePath string) (s
}
return scaffoldKindInit, nil
}
if _, stderr, err := initRunner.Run(ctx, dir, "npx", "-y", "--prefer-online", "--registry", npmRegistry, miaodaCLIPkg, "app", "sync"); err != nil {
return "", appsExternalToolError(err, "npx app sync failed: %s", gitErr(stderr, err))
policy := policyForAppType(appType)
if !policy.skipAppSync {
if _, stderr, err := initRunner.Run(ctx, dir, "npx", "-y", "--prefer-online", "--registry", npmRegistry, miaodaCLIPkg, "app", "sync"); err != nil {
return "", appsExternalToolError(err, "npx app sync failed: %s", gitErr(stderr, err))
}
}
if err := ensureMetaAppID(dir, appID); err != nil {
return "", err
}
if !policyForAppType(appType).skipSkillsSync && !hasSteeringSkills(dir) {
if !policy.skipSkillsSync && !hasSteeringSkills(dir) {
if _, stderr, err := initRunner.Run(ctx, dir, "npx", "-y", "--prefer-online", "--registry", npmRegistry, miaodaCLIPkg, "skills", "sync", "--local"); err != nil {
return "", appsExternalToolError(err, "npx skills sync failed: %s", gitErr(stderr, err))
}
@@ -436,26 +454,38 @@ func scaffoldInitArgs(appType, appID, sourcePath string) []string {
return base
}
// parseRepoURLFromEnvelope extracts data.repository_url from a lark-cli JSON
// envelope ({"ok":true,"data":{"repository_url":"..."}}). The field name
// matches the contract emitted by `apps +git-credential-init`.
func parseRepoURLFromEnvelope(stdout string) (string, error) {
// credentialInitResult holds the fields parsed from +git-credential-init output.
type credentialInitResult struct {
RepositoryURL string
CommitAuthorName string
CommitAuthorEmail string
}
// parseCredentialInitEnvelope extracts fields from a +git-credential-init JSON
// envelope ({"ok":true,"data":{"repository_url":"...","commit_author_name":"...","commit_author_email":"..."}}).
func parseCredentialInitEnvelope(stdout string) (credentialInitResult, error) {
var env struct {
OK bool `json:"ok"`
Data struct {
RepositoryURL string `json:"repository_url"`
RepositoryURL string `json:"repository_url"`
CommitAuthorName string `json:"commit_author_name"`
CommitAuthorEmail string `json:"commit_author_email"`
} `json:"data"`
}
if err := json.Unmarshal([]byte(stdout), &env); err != nil {
return "", appsSubprocessEnvelopeError("could not parse +git-credential-init output as JSON: %v", err)
return credentialInitResult{}, appsSubprocessEnvelopeError("could not parse +git-credential-init output as JSON: %v", err)
}
if !env.OK {
return "", appsSubprocessEnvelopeError("+git-credential-init reported failure")
return credentialInitResult{}, appsSubprocessEnvelopeError("+git-credential-init reported failure")
}
if strings.TrimSpace(env.Data.RepositoryURL) == "" {
return "", appsSubprocessEnvelopeError("+git-credential-init returned no repository_url")
return credentialInitResult{}, appsSubprocessEnvelopeError("+git-credential-init returned no repository_url")
}
return env.Data.RepositoryURL, nil
return credentialInitResult{
RepositoryURL: env.Data.RepositoryURL,
CommitAuthorName: env.Data.CommitAuthorName,
CommitAuthorEmail: env.Data.CommitAuthorEmail,
}, nil
}
// parseEnvFileFromEnvelope extracts data.env_file from a `+env-pull` success
@@ -527,7 +557,10 @@ func appsInitExecute(ctx context.Context, rctx *common.RuntimeContext) error {
return err
}
appType := queryAppType(ctx, rctx, appID)
appType, err := queryAppType(ctx, rctx, appID)
if err != nil {
return err
}
policy := policyForAppType(appType)
// Already-initialized short-circuit: a dir containing .spark/meta.json is an
@@ -595,16 +628,16 @@ func appsInitExecute(ctx context.Context, rctx *common.RuntimeContext) error {
}
initLogf(rctx, "Issuing repository credentials for %s...", appID)
repoURL, err := issueCredentials(ctx, rctx, appID)
cred, err := issueCredentials(ctx, rctx, appID)
if err != nil {
return err
}
if err := validateRepoURLScheme(repoURL); err != nil {
if err := validateRepoURLScheme(cred.RepositoryURL); err != nil {
return err
}
initLogf(rctx, "Cloning into %s...", dir)
if _, stderr, err := initRunner.Run(ctx, "", "git", "clone", "--", repoURL, dir); err != nil {
if _, stderr, err := initRunner.Run(ctx, "", "git", "clone", "--", cred.RepositoryURL, dir); err != nil {
return appsExternalToolError(err, "git clone failed: %s", gitErr(stderr, err))
}
initLogf(rctx, "Checking out %s...", defaultInitBranch)
@@ -612,9 +645,10 @@ func appsInitExecute(ctx context.Context, rctx *common.RuntimeContext) error {
return appsExternalToolError(err, "git checkout %s failed: %s", defaultInitBranch, gitErr(stderr, err))
}
// Ensure a committer identity exists before the scaffold commit; only sets
// repo-local defaults when none is configured (existing identity is kept).
if err := ensureGitIdentity(ctx, dir); err != nil {
// Ensure a committer identity exists before the scaffold commit. Uses the
// author name/email from +git-credential-init when available; falls back
// to lark-cli-bot defaults when the server does not provide them.
if err := ensureGitIdentity(ctx, dir, cred.CommitAuthorName, cred.CommitAuthorEmail); err != nil {
return err
}
@@ -643,7 +677,7 @@ func appsInitExecute(ctx context.Context, rctx *common.RuntimeContext) error {
out := map[string]interface{}{
"app_id": appID,
"repository_url": redactURLCredentials(repoURL),
"repository_url": redactURLCredentials(cred.RepositoryURL),
"branch": defaultInitBranch,
"clone_path": dir,
"scaffold": scaffold,
@@ -721,10 +755,10 @@ func pullEnv(ctx context.Context, rctx *common.RuntimeContext, appID, dir string
// issueCredentials runs `<self> apps +git-credential-init --app-id <id> --format json`
// and returns the repo_url it reports. Forwards --as when set.
func issueCredentials(ctx context.Context, rctx *common.RuntimeContext, appID string) (string, error) {
func issueCredentials(ctx context.Context, rctx *common.RuntimeContext, appID string) (credentialInitResult, error) {
self, err := os.Executable()
if err != nil {
return "", errs.NewInternalError(errs.SubtypeUnknown, "cannot locate lark-cli executable: %v", err).WithCause(err)
return credentialInitResult{}, errs.NewInternalError(errs.SubtypeUnknown, "cannot locate lark-cli executable: %v", err).WithCause(err)
}
args := []string{"apps", "+git-credential-init", "--app-id", appID, "--format", "json"}
if as := strings.TrimSpace(rctx.Str("as")); as != "" {
@@ -732,11 +766,11 @@ func issueCredentials(ctx context.Context, rctx *common.RuntimeContext, appID st
}
stdout, stderr, err := initRunner.Run(ctx, "", self, args...)
if err != nil {
return "", appsExternalToolError(err, "apps +git-credential-init failed: %s", gitErr(stderr, err)).
return credentialInitResult{}, appsExternalToolError(err, "apps +git-credential-init failed: %s", gitErr(stderr, err)).
WithHint("ensure apps +git-credential-init is available and you are logged in").
WithCause(err)
}
return parseRepoURLFromEnvelope(stdout)
return parseCredentialInitEnvelope(stdout)
}
// commitAndPushIfDirty commits and pushes only when the working tree has

View File

@@ -21,6 +21,7 @@ import (
"github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/internal/core"
"github.com/larksuite/cli/internal/httpmock"
"github.com/larksuite/cli/internal/testutil/gitcmd"
"github.com/larksuite/cli/shortcuts/common"
)
@@ -110,18 +111,24 @@ func TestDefaultCloneDir(t *testing.T) {
// --- pure-function tests ---
func TestParseRepoURL(t *testing.T) {
url, err := parseRepoURLFromEnvelope(`{"ok":true,"data":{"repository_url":"http://u:t@h/app_x.git"}}`)
result, err := parseCredentialInitEnvelope(`{"ok":true,"data":{"repository_url":"http://u:t@h/app_x.git","commit_author_name":"Alice","commit_author_email":"alice@example.com"}}`)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if url != "http://u:t@h/app_x.git" {
t.Errorf("got %q", url)
if result.RepositoryURL != "http://u:t@h/app_x.git" {
t.Errorf("RepositoryURL got %q", result.RepositoryURL)
}
if result.CommitAuthorName != "Alice" {
t.Errorf("CommitAuthorName got %q", result.CommitAuthorName)
}
if result.CommitAuthorEmail != "alice@example.com" {
t.Errorf("CommitAuthorEmail got %q", result.CommitAuthorEmail)
}
}
func TestParseRepoURL_Errors(t *testing.T) {
for _, in := range []string{`not json`, `{"ok":false,"data":{}}`, `{"ok":true,"data":{}}`, `{"ok":true,"data":{"repository_url":""}}`} {
if _, err := parseRepoURLFromEnvelope(in); err == nil {
if _, err := parseCredentialInitEnvelope(in); err == nil {
t.Errorf("expected error for %q", in)
}
}
@@ -149,6 +156,22 @@ func withFakeRunner(t *testing.T, f *fakeCommandRunner) {
t.Cleanup(func() { initRunner = orig })
}
func stubAppType(reg *httpmock.Registry, appID, appType string) {
reg.Register(&httpmock.Stub{
Method: "GET",
URL: "/open-apis/spark/v1/apps/" + appID,
Body: map[string]interface{}{
"code": float64(0),
"data": map[string]interface{}{
"app": map[string]interface{}{
"app_id": appID,
"app_type": appType,
},
},
},
})
}
func credInitOK(repoURL string) fakeCallResult {
return fakeCallResult{stdout: `{"ok":true,"data":{"repository_url":"` + repoURL + `"}}`}
}
@@ -313,7 +336,8 @@ func TestAppsInit_EmptyRepo_EndToEnd(t *testing.T) {
"git status": {stdout: " M src/app.ts\n"}, // scaffold produced changes
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("unexpected: %v", err)
@@ -354,7 +378,8 @@ func TestAppsInit_AlreadyInitialized_ShortCircuit(t *testing.T) {
}
f := &fakeCommandRunner{results: map[string]fakeCallResult{"env-pull": envPullOK(filepath.Join(abs, ".env.local"))}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("unexpected: %v", err)
}
@@ -423,7 +448,8 @@ func TestAppsInit_HappyPathCleanTree(t *testing.T) {
"git status": {}, // clean tree after scaffold -> no commit/push
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout)
@@ -472,7 +498,8 @@ func TestAppsInit_DirtyTreeCommitPush(t *testing.T) {
"git status": {stdout: " M file.txt"},
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout)
@@ -542,7 +569,8 @@ func TestAppsInit_CloneFailure(t *testing.T) {
"git clone": {stderr: "fatal: unable to access 'http://u:t@h/r.git'", err: errors.New("exit 128")},
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout)
@@ -616,7 +644,8 @@ func TestAppsInit_AsPassthrough(t *testing.T) {
"git status": {},
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
// AppsInit.AuthTypes is ["user"], so the framework rejects --as bot. Use
@@ -722,7 +751,7 @@ func TestIsEmptyRepo(t *testing.T) {
// newAppsExecuteFactoryWithStderr mirrors newAppsExecuteFactory but also returns
// the stderr buffer, so tests can assert on the +init progress log lines that
// initLogf writes to IO().ErrOut.
func newAppsExecuteFactoryWithStderr(t *testing.T) (*cmdutil.Factory, *bytes.Buffer, *bytes.Buffer) {
func newAppsExecuteFactoryWithStderr(t *testing.T) (*cmdutil.Factory, *bytes.Buffer, *bytes.Buffer, *httpmock.Registry) {
t.Helper()
t.Setenv("HOME", t.TempDir())
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
@@ -732,12 +761,12 @@ func newAppsExecuteFactoryWithStderr(t *testing.T) (*cmdutil.Factory, *bytes.Buf
Brand: core.BrandFeishu,
UserOpenId: "ou_test",
}
factory, stdout, stderr, _ := cmdutil.TestFactory(t, cfg)
return factory, stdout, stderr
factory, stdout, stderr, reg := cmdutil.TestFactory(t, cfg)
return factory, stdout, stderr, reg
}
func TestAppsInit_Req1_Wording(t *testing.T) {
factory, stdout, _ := newAppsExecuteFactoryWithStderr(t)
factory, stdout, _, _ := newAppsExecuteFactoryWithStderr(t)
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--as", "user", "--dry-run"}, factory, stdout); err != nil {
t.Fatalf("dry-run err=%v", err)
}
@@ -766,7 +795,8 @@ func TestAppsInit_Req1_Wording(t *testing.T) {
"git status": {},
}}
withFakeRunner(t, f)
factory2, stdout2, stderr2 := newAppsExecuteFactoryWithStderr(t)
factory2, stdout2, stderr2, reg2 := newAppsExecuteFactoryWithStderr(t)
stubAppType(reg2, "app_x", "FULL_STACK")
dir := relCloneDir(t)
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory2, stdout2); err != nil {
t.Fatalf("run err=%v", err)
@@ -829,7 +859,8 @@ func TestAppsInit_EmptyRepo_TwoCommits(t *testing.T) {
"git status": {stdout: " A src/app.ts\n A .spark/meta.json\n A .agent/skills/steering/x.md\n"},
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("unexpected: %v", err)
@@ -870,7 +901,8 @@ func TestAppsInit_EmptyRepo_AppCodeOnly_SingleCommit(t *testing.T) {
"git status": {stdout: " A src/app.ts\n"},
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("unexpected: %v", err)
@@ -890,7 +922,8 @@ func TestAppsInit_EmptyRepo_ConfigOnly_SingleCommit(t *testing.T) {
"git status": {stdout: " A .spark/meta.json\n"},
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("unexpected: %v", err)
@@ -910,7 +943,8 @@ func TestAppsInit_NonEmpty_SingleInitCommit(t *testing.T) {
"git status": {stdout: " M file.txt\n M .spark/meta.json\n"},
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("unexpected: %v", err)
@@ -929,8 +963,7 @@ func TestAppsInit_NonEmpty_SingleInitCommit(t *testing.T) {
// gitMust runs a git command in dir with a real binary, failing the test on error.
func gitMust(t *testing.T, dir string, args ...string) string {
t.Helper()
cmd := exec.Command("git", args...)
cmd.Dir = dir
cmd := gitcmd.Command(dir, args...)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("git %v in %s failed: %v\n%s", args, dir, err, out)
@@ -946,6 +979,7 @@ func TestCommitAndPushIfDirty_RealGit_IgnoredAgentDir(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available")
}
gitcmd.SetSynchronousMaintenanceEnv(t)
// Bare remote so `git push origin sprint/default` succeeds.
remote := t.TempDir()
gitMust(t, remote, "init", "--bare", "-q", "--initial-branch", defaultInitBranch)
@@ -1067,6 +1101,7 @@ func TestCommitAndPushIfDirty_RealGit_NonEmptyUpgrade(t *testing.T) {
if _, err := exec.LookPath("git"); err != nil {
t.Skip("git not available")
}
gitcmd.SetSynchronousMaintenanceEnv(t)
remote := t.TempDir()
gitMust(t, remote, "init", "--bare", "-q", "--initial-branch", defaultInitBranch)
@@ -1289,7 +1324,8 @@ func TestAppsInit_EnvPull_Success(t *testing.T) {
"env-pull": envPullOK("/abs/app_x/.env.local"),
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("unexpected error: %v", err)
@@ -1327,7 +1363,8 @@ func TestAppsInit_EnvPull_NonFatal(t *testing.T) {
},
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
dir := relCloneDir(t)
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("env-pull failure must be non-fatal, got: %v", err)
@@ -1366,7 +1403,8 @@ func TestAppsInit_AlreadyInitialized_RunsEnvPull(t *testing.T) {
envFile := filepath.Join(abs, ".env.local")
f := &fakeCommandRunner{results: map[string]fakeCallResult{"env-pull": envPullOK(envFile)}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -1413,7 +1451,8 @@ func TestAppsInit_AlreadyInitialized_EnvPullFailure_NonFatal(t *testing.T) {
},
}}
withFakeRunner(t, f)
factory, stdout, _ := newAppsExecuteFactory(t)
factory, stdout, reg := newAppsExecuteFactory(t)
stubAppType(reg, "app_x", "FULL_STACK")
if err := runAppsShortcut(t, AppsInit, []string{"+init", "--app-id", "app_x", "--dir", dir, "--as", "user"}, factory, stdout); err != nil {
t.Fatalf("env-pull failure must be non-fatal, got: %v", err)
}
@@ -1705,13 +1744,15 @@ func TestScaffoldInitArgs_WithAppType(t *testing.T) {
}
func TestPolicyForAppType(t *testing.T) {
// modern_html decouples all control points: skip install, env-pull, skills sync.
if p := policyForAppType("modern_html"); !p.skipInstall || !p.skipEnvPull || !p.skipSkillsSync {
t.Errorf("modern_html policy = %+v, want all skip flags set", p)
// modern_html and html decouple all control points: skip install, env-pull, skills sync, app sync.
for _, at := range []string{"modern_html", "html"} {
if p := policyForAppType(at); !p.skipInstall || !p.skipEnvPull || !p.skipSkillsSync || !p.skipAppSync {
t.Errorf("%s policy = %+v, want all skip flags set", at, p)
}
}
// Unlisted types (including "") get the zero-value policy: everything runs.
for _, at := range []string{"full_stack", "", "backend"} {
if p := policyForAppType(at); p.skipInstall || p.skipEnvPull || p.skipSkillsSync {
if p := policyForAppType(at); p.skipInstall || p.skipEnvPull || p.skipSkillsSync || p.skipAppSync {
t.Errorf("policy for %q = %+v, want zero value", at, p)
}
}
@@ -1757,7 +1798,7 @@ func configSetValue(calls [][]string, key string) (string, bool) {
func TestEnsureGitIdentity_SetsDefaultsWhenUnset(t *testing.T) {
f := &fakeCommandRunner{} // no "git config" result → `--get` returns empty stdout
withFakeRunner(t, f)
if err := ensureGitIdentity(context.Background(), "/repo"); err != nil {
if err := ensureGitIdentity(context.Background(), "/repo", "", ""); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if v, ok := configSetValue(f.calls, "user.name"); !ok || v != defaultGitUserName {
@@ -1774,7 +1815,7 @@ func TestEnsureGitIdentity_RespectsExisting(t *testing.T) {
"git config": {stdout: "Existing Dev\n"},
}}
withFakeRunner(t, f)
if err := ensureGitIdentity(context.Background(), "/repo"); err != nil {
if err := ensureGitIdentity(context.Background(), "/repo", "", ""); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if _, ok := configSetValue(f.calls, "user.name"); ok {
@@ -1790,7 +1831,7 @@ func TestEnsureGitIdentity_SetFailurePropagates(t *testing.T) {
"git config": {stderr: "boom", err: errors.New("exit 1")},
}}
withFakeRunner(t, f)
if err := ensureGitIdentity(context.Background(), "/repo"); err == nil {
if err := ensureGitIdentity(context.Background(), "/repo", "", ""); err == nil {
t.Error("expected error when git config set fails")
}
}

View File

@@ -13,22 +13,25 @@ import (
)
// queryAppType fetches the app's type string from the server via
// GET /open-apis/spark/v1/apps/{appID}. The server returns uppercase
// values ("HTML", "FULL_STACK", "MODERN_HTML"); this function normalizes
// to lowercase. Returns "" when the API is unavailable or returns an
// error — callers fall back to legacy behavior.
func queryAppType(ctx context.Context, rctx *common.RuntimeContext, appID string) string {
path := fmt.Sprintf("%s/apps/%s", apiBasePath, validate.EncodePathSegment(appID))
// GET /open-apis/spark/v1/apps/{identifier}. The identifier can be either
// an app_id or a meta_token — the server resolves both. The server returns
// uppercase app_type values ("HTML", "FULL_STACK", "MODERN_HTML");
// this function normalizes to lowercase. Returns an error when the API
// is unavailable or the response is malformed — callers must not proceed
// with a fallback type to avoid creating the wrong project scaffold.
func queryAppType(ctx context.Context, rctx *common.RuntimeContext, identifier string) (string, error) {
path := fmt.Sprintf("%s/apps/%s", apiBasePath, validate.EncodePathSegment(identifier))
data, err := rctx.CallAPITyped("GET", path, nil, nil)
if err != nil {
fmt.Fprintf(rctx.IO().ErrOut, "→ Could not query app type: %v\n", err)
return ""
return "", err
}
appRaw, _ := data["app"].(map[string]interface{})
if appRaw == nil {
fmt.Fprintf(rctx.IO().ErrOut, "→ Could not query app type: response missing app object\n")
return ""
return "", appsSubprocessEnvelopeError("query app type: response missing app object")
}
appType, _ := appRaw["app_type"].(string)
return strings.ToLower(appType)
if strings.TrimSpace(appType) == "" {
return "", appsSubprocessEnvelopeError("query app type: response missing app_type")
}
return strings.ToLower(appType), nil
}

View File

@@ -43,7 +43,10 @@ func TestQueryAppType_Success(t *testing.T) {
},
})
result := queryAppType(context.Background(), rt, "app_test")
result, err := queryAppType(context.Background(), rt, "app_test")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result != "modern_html" {
t.Errorf("queryAppType = %q, want modern_html", result)
}
@@ -65,7 +68,10 @@ func TestQueryAppType_FullStack(t *testing.T) {
},
})
result := queryAppType(context.Background(), rt, "app_fs")
result, err := queryAppType(context.Background(), rt, "app_fs")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result != "full_stack" {
t.Errorf("queryAppType = %q, want full_stack", result)
}
@@ -87,7 +93,10 @@ func TestQueryAppType_Html(t *testing.T) {
},
})
result := queryAppType(context.Background(), rt, "app_html")
result, err := queryAppType(context.Background(), rt, "app_html")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result != "html" {
t.Errorf("queryAppType = %q, want html", result)
}
@@ -102,9 +111,9 @@ func TestQueryAppType_APIError(t *testing.T) {
Body: map[string]interface{}{"code": float64(99999), "msg": "internal error"},
})
result := queryAppType(context.Background(), rt, "app_bad")
if result != "" {
t.Errorf("queryAppType = %q, want empty on error", result)
_, err := queryAppType(context.Background(), rt, "app_bad")
if err == nil {
t.Error("expected error on API failure")
}
}
@@ -119,9 +128,9 @@ func TestQueryAppType_MissingAppObject(t *testing.T) {
},
})
result := queryAppType(context.Background(), rt, "app_no")
if result != "" {
t.Errorf("queryAppType = %q, want empty when app object missing", result)
_, err := queryAppType(context.Background(), rt, "app_no")
if err == nil {
t.Error("expected error when app object missing")
}
}
@@ -141,8 +150,8 @@ func TestQueryAppType_EmptyAppType(t *testing.T) {
},
})
result := queryAppType(context.Background(), rt, "app_empty")
if result != "" {
t.Errorf("queryAppType = %q, want empty when app_type is empty", result)
_, err := queryAppType(context.Background(), rt, "app_empty")
if err == nil {
t.Error("expected error when app_type is empty")
}
}

View File

@@ -31,9 +31,13 @@ var AppsReleaseCreate = common.Shortcut{
{Name: "branch", Desc: "release branch (server uses default if omitted)"},
},
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
if strings.TrimSpace(rctx.Str("app-id")) == "" {
appID := strings.TrimSpace(rctx.Str("app-id"))
if appID == "" {
return appsValidationParamError("--app-id", "--app-id is required")
}
if err := validateRealAppID(appID); err != nil {
return err
}
return nil
},
DryRun: func(ctx context.Context, rctx *common.RuntimeContext) *common.DryRunAPI {

View File

@@ -30,9 +30,13 @@ var AppsReleaseGet = common.Shortcut{
{Name: "release-id", Desc: "release ID (the release_id returned by +release-create)", Required: true},
},
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
if strings.TrimSpace(rctx.Str("app-id")) == "" {
appID := strings.TrimSpace(rctx.Str("app-id"))
if appID == "" {
return appsValidationParamError("--app-id", "--app-id is required")
}
if err := validateRealAppID(appID); err != nil {
return err
}
if strings.TrimSpace(rctx.Str("release-id")) == "" {
return appsValidationParamError("--release-id", "--release-id is required")
}

View File

@@ -41,6 +41,21 @@ func withAppsHint(err error, hint string) error {
return err
}
// validateRealAppID checks that --app-id is a real app ID (app_ prefix).
// meta_token values are rejected with a hint to resolve via +get first.
func validateRealAppID(appID string) error {
if !strings.HasPrefix(appID, "app_") {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
`--app-id must be an app_id starting with "app_".`,
).WithParam("--app-id").WithHint(
`If you have a meta_token or a /page/<token>/ link, first resolve it:
lark-cli apps +get --app-id <meta_token> -q '.data.app.app_id'
Then retry this command with the returned app_id.`,
)
}
return nil
}
// rejectOutputTraversal is a defense-in-depth pre-check on a user-supplied
// --output path. The authoritative guard is the local FileIO layer
// (validate.SafeOutputPath sandboxes every write to the cwd, resolving .. and

View File

@@ -75,6 +75,7 @@ var AppsGitCredentialInit = common.Shortcut{
"save the issued PAT in the local system credential store",
"write app-scoped git credential metadata",
"configure a URL-scoped Git credential helper in global git config when possible",
"return commit_author_name and commit_author_email for repo-local git identity",
}).
Params(gitCredentialIssueParams(appID))
},
@@ -90,6 +91,12 @@ var AppsGitCredentialInit = common.Shortcut{
"repository_url": result.GitHTTPURL,
"status": initStatus(result),
}
if result.CommitAuthorName != "" {
payload["commit_author_name"] = result.CommitAuthorName
}
if result.CommitAuthorEmail != "" {
payload["commit_author_email"] = result.CommitAuthorEmail
}
if result.ConfigWarning != "" {
payload["git_config_warning"] = result.ConfigWarning
}
@@ -461,11 +468,13 @@ func issuedFromData(appID string, data map[string]interface{}) (*gitcred.IssuedC
}
}
issued := &gitcred.IssuedCredential{
AppID: firstString(source, "app_id", appID),
GitHTTPURL: firstString(source, "gitURL", "GitURL", "GitUrl", "gitUrl", "git_url", "git_http_url", "repository_url"),
Username: firstString(source, "username"),
PAT: firstString(source, "token", "Token", "pat", "password"),
ExpiresAt: firstInt64(source, "expiredTime", "ExpiredTime", "expired_time", "expires_at"),
AppID: firstString(source, "app_id", appID),
GitHTTPURL: firstString(source, "gitURL", "GitURL", "GitUrl", "gitUrl", "git_url", "git_http_url", "repository_url"),
Username: firstString(source, "username"),
PAT: firstString(source, "token", "Token", "pat", "password"),
ExpiresAt: firstInt64(source, "expiredTime", "ExpiredTime", "expired_time", "expires_at"),
CommitAuthorName: firstString(source, "commit_author_name"),
CommitAuthorEmail: firstString(source, "commit_author_email"),
}
if issued.AppID == "" {
issued.AppID = appID

View File

@@ -87,6 +87,7 @@ func TestAppsGitCredentialInitDryRunRequestShape(t *testing.T) {
"save the issued PAT in the local system credential store",
"write app-scoped git credential metadata",
"configure a URL-scoped Git credential helper in global git config when possible",
"return commit_author_name and commit_author_email for repo-local git identity",
})
}

View File

@@ -129,7 +129,13 @@ func (m *Manager) Init(ctx context.Context, profile ProfileContext, appID string
if previous != nil && previous.PATRef != "" && previous.PATRef != ref {
_ = m.Secrets.Remove(previous.PATRef)
}
result := &InitResult{AppID: appID, GitHTTPURL: url, Refreshed: previous != nil}
result := &InitResult{
AppID: appID,
GitHTTPURL: url,
Refreshed: previous != nil,
CommitAuthorName: issued.CommitAuthorName,
CommitAuthorEmail: issued.CommitAuthorEmail,
}
if m.GitConfig != nil {
if err := m.GitConfig.SetHelper(ctx, url, appID); err != nil {
result.ConfigWarning = err.Error()

View File

@@ -51,18 +51,22 @@ type CredentialRecord struct {
}
type IssuedCredential struct {
AppID string
GitHTTPURL string
Username string
PAT string
ExpiresAt int64
AppID string
GitHTTPURL string
Username string
PAT string
ExpiresAt int64
CommitAuthorName string
CommitAuthorEmail string
}
type InitResult struct {
AppID string
GitHTTPURL string
Refreshed bool
ConfigWarning string
AppID string
GitHTTPURL string
Refreshed bool
ConfigWarning string
CommitAuthorName string
CommitAuthorEmail string
}
type RemoveResult struct {

View File

@@ -1,73 +0,0 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package apps
import (
"bytes"
"context"
"fmt"
"net/http"
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/client"
"github.com/larksuite/cli/internal/validate"
"github.com/larksuite/cli/shortcuts/common"
)
type htmlPublishResponse struct {
URL string
}
type appsHTMLPublishClient interface {
HTMLPublish(ctx context.Context, appID string, tarball *htmlPublishTarball) (*htmlPublishResponse, error)
}
type appsHTMLPublishAPI struct {
runtime *common.RuntimeContext
}
func (api appsHTMLPublishAPI) HTMLPublish(ctx context.Context, appID string, tarball *htmlPublishTarball) (*htmlPublishResponse, error) {
fd := larkcore.NewFormdata()
fd.AddFile("file", bytes.NewReader(tarball.Body))
apiResp, err := api.runtime.DoAPI(&larkcore.ApiReq{
HttpMethod: http.MethodPost,
ApiPath: fmt.Sprintf("%s/apps/%s/upload_and_release_html_code", apiBasePath, validate.EncodePathSegment(appID)),
Body: fd,
}, larkcore.WithFileUpload())
if err != nil {
return nil, client.WrapDoAPIError(err)
}
data, err := api.runtime.ClassifyAPIResponse(apiResp)
if err != nil {
return nil, enrichHTMLPublishAPIError(err)
}
url, _ := data["url"].(string)
if url == "" {
return nil, errs.NewInternalError(errs.SubtypeInvalidResponse,
"html-publish response is missing the published app url")
}
return &htmlPublishResponse{URL: url}, nil
}
// OAPI business error codes returned by the
// /apps/{id}/upload_and_release_html_code endpoint. Owned by the backend
// service; update when new codes are documented in the OAPI spec.
const (
errCodeBuildFailed = 90001 // tar.gz uploaded but server-side build failed
errCodeAppNotFound = 90002 // app_id unknown or caller lacks permission
)
func buildHTMLPublishFailureHint(code int) string {
switch code {
case errCodeBuildFailed:
return "server-side build failed: run `lark-cli apps +html-publish --app-id <your-app-id> --path <path> --dry-run` to inspect the packaged file list"
case errCodeAppNotFound:
return "the app does not exist or the caller has no access; ask the user to confirm the app_id (extract it from the app URL https://miaoda.feishu.cn/app/app_xxx after /app/, or take the app_xxx string directly)"
default:
return ""
}
}

View File

@@ -1,197 +0,0 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package apps
import (
"bytes"
"context"
"mime"
"mime/multipart"
"strings"
"testing"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/internal/core"
"github.com/larksuite/cli/internal/httpmock"
"github.com/larksuite/cli/shortcuts/common"
)
func newAppsClientRuntime(t *testing.T) (*common.RuntimeContext, *httpmock.Registry) {
t.Helper()
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
cfg := &core.CliConfig{
AppID: "test-app-" + strings.ToLower(t.Name()),
AppSecret: "test-secret",
Brand: core.BrandFeishu,
UserOpenId: "ou_test",
}
factory, _, _, reg := cmdutil.TestFactory(t, cfg)
rctx := common.TestNewRuntimeContextForAPI(context.Background(), nil, cfg, factory, core.AsUser)
return rctx, reg
}
func TestAppsHTMLPublishAPI_Success(t *testing.T) {
rctx, reg := newAppsClientRuntime(t)
stub := &httpmock.Stub{
Method: "POST",
URL: "/open-apis/spark/v1/apps/app_x/upload_and_release_html_code",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{
"url": "https://miaoda.feishu.cn/app/app_x",
},
},
}
reg.Register(stub)
api := appsHTMLPublishAPI{runtime: rctx}
tarball := &htmlPublishTarball{Body: []byte("fake"), Size: 4, SHA256: "abc"}
resp, err := api.HTMLPublish(context.Background(), "app_x", tarball)
if err != nil {
t.Fatalf("err=%v", err)
}
if resp.URL != "https://miaoda.feishu.cn/app/app_x" {
t.Fatalf("url=%q", resp.URL)
}
ct := stub.CapturedHeaders.Get("Content-Type")
mt, params, err := mime.ParseMediaType(ct)
if err != nil || mt != "multipart/form-data" {
t.Fatalf("content type %q wrong", ct)
}
mr := multipart.NewReader(bytes.NewReader(stub.CapturedBody), params["boundary"])
saw := false
for {
p, err := mr.NextPart()
if err != nil {
break
}
if p.FormName() == "file" {
saw = true
}
}
if !saw {
t.Fatalf("multipart missing 'file' part")
}
}
func TestAppsHTMLPublishAPI_BusinessErrorHasHint(t *testing.T) {
rctx, reg := newAppsClientRuntime(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/spark/v1/apps/app_x/upload_and_release_html_code",
Body: map[string]interface{}{
"code": 90001,
"msg": "build failed: dependency conflict",
},
})
api := appsHTMLPublishAPI{runtime: rctx}
_, err := api.HTMLPublish(context.Background(), "app_x", &htmlPublishTarball{Body: []byte("fake")})
if err == nil {
t.Fatalf("expected error")
}
problem := requireAppsAPIProblem(t, err)
if problem.Code != errCodeBuildFailed {
t.Fatalf("code = %d, want %d", problem.Code, errCodeBuildFailed)
}
if problem.Hint == "" {
t.Fatalf("expected non-empty hint on code 90001")
}
if !strings.Contains(problem.Message, "build failed") {
t.Fatalf("missing failure message: %v", problem.Message)
}
}
func TestAppsHTMLPublishAPI_AppNotFoundClassified(t *testing.T) {
rctx, reg := newAppsClientRuntime(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/spark/v1/apps/app_missing/upload_and_release_html_code",
Body: map[string]interface{}{
"code": errCodeAppNotFound,
"msg": "app not found",
},
})
api := appsHTMLPublishAPI{runtime: rctx}
_, err := api.HTMLPublish(context.Background(), "app_missing", &htmlPublishTarball{Body: []byte("fake")})
problem := requireAppsAPIProblem(t, err)
if problem.Subtype != errs.SubtypeNotFound {
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeNotFound)
}
if problem.Hint == "" {
t.Fatalf("expected app-not-found recovery hint")
}
}
func TestAppsHTMLPublishAPI_MissingURLIsInvalidResponse(t *testing.T) {
rctx, reg := newAppsClientRuntime(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/spark/v1/apps/app_x/upload_and_release_html_code",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{},
},
})
api := appsHTMLPublishAPI{runtime: rctx}
_, err := api.HTMLPublish(context.Background(), "app_x", &htmlPublishTarball{Body: []byte("fake")})
problem := requireAppsProblem(t, err, errs.CategoryInternal)
if problem.Subtype != errs.SubtypeInvalidResponse {
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeInvalidResponse)
}
}
func TestBuildHTMLPublishFailureHint_UnknownCodeReturnsEmpty(t *testing.T) {
// 默认分支:未识别的 code 返回空 hint让 Agent 用 message 兜底。
if hint := buildHTMLPublishFailureHint(99999); hint != "" {
t.Fatalf("unknown code should return empty hint, got %q", hint)
}
if hint := buildHTMLPublishFailureHint(0); hint != "" {
t.Fatalf("zero code should return empty hint, got %q", hint)
}
}
func TestBuildHTMLPublishFailureHint_KnownCodes(t *testing.T) {
if hint := buildHTMLPublishFailureHint(90001); hint == "" {
t.Fatalf("code 90001 should return non-empty hint")
}
if hint := buildHTMLPublishFailureHint(90002); hint == "" {
t.Fatalf("code 90002 should return non-empty hint")
}
}
func TestBuildHTMLPublishFailureHint_NotFoundHintNoLongerMentionsList(t *testing.T) {
hint := buildHTMLPublishFailureHint(90002)
if hint == "" {
t.Fatalf("code 90002 should return non-empty hint")
}
if strings.Contains(hint, "+list") {
t.Fatalf("hint must not point at hidden +list command, got: %q", hint)
}
if !strings.Contains(hint, "app_id") {
t.Fatalf("hint should reference app_id, got: %q", hint)
}
}
func TestAppsHTMLPublishAPI_MalformedResponseIsInvalidResponse(t *testing.T) {
rctx, reg := newAppsClientRuntime(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/spark/v1/apps/app_x/upload_and_release_html_code",
RawBody: []byte("{not json"),
})
api := appsHTMLPublishAPI{runtime: rctx}
_, err := api.HTMLPublish(context.Background(), "app_x", &htmlPublishTarball{Body: []byte("fake")})
problem := requireAppsProblem(t, err, errs.CategoryInternal)
if problem.Subtype != errs.SubtypeInvalidResponse {
t.Fatalf("subtype = %q, want %q", problem.Subtype, errs.SubtypeInvalidResponse)
}
}

View File

@@ -0,0 +1,790 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
//
// calendar +update room-availability pre-check helpers.
//
// Uses /open-apis/calendar/v4/freebusy/room_availability_check to warn the
// caller before an update either adds a new room attendee or shifts the time
// of a slot that already has a room reservation. --skip-room-check bypasses
// the check for callers that want to move fast.
package calendar
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/validate"
"github.com/larksuite/cli/shortcuts/common"
)
const (
flagSkipRoomCheck = "skip-room-check"
roomCheckPath = "/open-apis/calendar/v4/freebusy/room_availability_check"
)
// roomAvailability mirrors a single room result from the API.
type roomAvailability struct {
RoomID string `json:"room_id,omitempty"`
RoomName string `json:"room_name,omitempty"`
Status string `json:"status,omitempty"`
UnavailableReasonType string `json:"unavailable_reason_type,omitempty"`
Strategy *roomStrategy `json:"room_strategy,omitempty"`
Requisition *roomRequisition `json:"room_requisition,omitempty"`
ApprovalInfo *roomApprovalInfo `json:"room_approval_info,omitempty"`
}
// roomStrategy mirrors the room_strategy block returned by the API on
// unavailable rooms. Every field is optional: the server only fills in the
// entries relevant to the current unavailable_reason_type.
type roomStrategy struct {
SingleMaxDuration string `json:"single_max_duration,omitempty"`
MaxAdvanceBookingTime string `json:"max_advance_booking_time,omitempty"`
DailyStartTime string `json:"daily_start_time,omitempty"`
DailyEndTime string `json:"daily_end_time,omitempty"`
Timezone string `json:"timezone,omitempty"`
DailyAdvanceWindowReleaseTime string `json:"daily_advance_window_release_time,omitempty"`
}
// roomRequisition mirrors room_requisition, returned by the API only when
// unavailable_reason_type == "during_requisition". Both fields are RFC3339
// strings and either may be empty if the server has no exact bound.
type roomRequisition struct {
StartTime string `json:"start_time,omitempty"`
EndTime string `json:"end_time,omitempty"`
}
// roomApprovalInfo mirrors room_approval_info, returned when the room requires
// (or may require) an approval submission before it can be booked.
//
// - ApprovalMode: "none" (no approval), "over_duration" (only when the
// booking exceeds the threshold), or "all" (every booking needs approval).
// - ApprovalDurationThreshold: seconds; only meaningful when
// ApprovalMode == "over_duration". The server returns it as a numeric
// string, matching the shape of the other duration fields.
//
// When the pre-check returns status == "need_approval" the caller renders a
// friendly reminder derived from these two fields plus the current event
// duration, so the agent knows whether to switch rooms/times or route the
// user through an approval flow.
type roomApprovalInfo struct {
ApprovalMode string `json:"approval_mode,omitempty"`
ApprovalDurationThreshold string `json:"approval_duration_threshold,omitempty"`
}
// eventSnapshot carries only the fields room-check needs from the current
// event: existing room IDs, current start/end (unix seconds string), timezone,
// and rrule.
type eventSnapshot struct {
RoomIDs []string
StartTs string
EndTs string
Timezone string
Recurrent string
}
// unavailableReasonHint maps API-declared unavailable reasons to a short
// English phrase suitable for embedding in the block message. Unknown or
// future reasons fall back to a single stable phrase so the CLI's blocked
// message stays predictable for agents that parse it.
func unavailableReasonHint(reason string) string {
switch reason {
case "reserved_by_other_event":
return "already reserved by another event"
case "past_time":
return "cannot book a room in the past"
case "beyond_advance_booking_window":
return "beyond the room's advance-booking window"
case "over_max_duration":
return "exceeds the room's max single-booking duration"
case "not_in_usable_time":
return "outside the room's daily bookable window"
case "during_requisition":
return "the room is disabled during this time and cannot be booked"
case "before_daily_advance_window_release":
return "the target date is outside the room's currently unlocked advance-booking window; the window extends by one calendar day at the daily release time"
case "recurring_exceed_approval_limit":
return "recurring event duration exceeds the limit for booking this approval-required room — shorten the duration or pick a different room"
default:
return "currently unbookable"
}
}
// strategyDetail renders the human-readable suffix appended to the reason
// phrase for a given (reason, strategy) pair. It returns an empty string when
// no strategy data is available or when the fields relevant to this reason
// are missing / invalid, so callers can safely concatenate the result.
func strategyDetail(reason string, s *roomStrategy) string {
if s == nil {
return ""
}
switch reason {
case "over_max_duration":
if d := formatDurationSeconds(s.SingleMaxDuration); d != "" {
return "the max single-booking duration is " + d
}
case "beyond_advance_booking_window":
// The API returns max_advance_booking_time as RFC3339 already;
// surface it verbatim so agents don't lose the exact instant.
if t := strings.TrimSpace(s.MaxAdvanceBookingTime); t != "" {
return "the latest bookable end time is " + t
}
case "not_in_usable_time":
start := formatDaySeconds(s.DailyStartTime)
end := formatDaySeconds(s.DailyEndTime)
zone := roomZoneLabel(s.Timezone)
switch {
case start != "" && end != "":
return fmt.Sprintf("the daily bookable window is %s - %s (%s)", start, end, zone)
case start != "":
return fmt.Sprintf("the daily bookable window starts at %s (%s)", start, zone)
case end != "":
return fmt.Sprintf("the daily bookable window ends at %s (%s)", end, zone)
}
case "before_daily_advance_window_release":
if t := formatDaySeconds(s.DailyAdvanceWindowReleaseTime); t != "" {
return fmt.Sprintf("the next unlock happens today at %s (%s), which advances the window by one day", t, roomZoneLabel(s.Timezone))
}
}
return ""
}
// requisitionDetail renders the suffix describing the room's scheduled
// disable window for a `during_requisition` block. The API sends both bounds
// as RFC3339 already, so we surface them verbatim to keep the exact instant.
// Returns "" when both bounds are missing so the caller falls back to the
// generic "pick a different time or a different room" recovery hint.
func requisitionDetail(reason string, r *roomRequisition) string {
if reason != "during_requisition" || r == nil {
return ""
}
start := strings.TrimSpace(r.StartTime)
end := strings.TrimSpace(r.EndTime)
switch {
case start != "" && end != "":
return fmt.Sprintf("the disabled period is %s to %s", start, end)
case start != "":
return "the disabled period starts at " + start
case end != "":
return "the disabled period ends at " + end
}
return ""
}
// formatDurationSeconds renders a whole-second string like "10800" as a
// compact "H hours [M minutes]" phrase. Returns "" when the value is
// missing, non-numeric, or non-positive.
func formatDurationSeconds(raw string) string {
sec, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
if err != nil || sec <= 0 {
return ""
}
d := time.Duration(sec) * time.Second
h := int(d / time.Hour)
m := int((d % time.Hour) / time.Minute)
switch {
case h > 0 && m > 0:
return fmt.Sprintf("%d hours %d minutes", h, m)
case h > 0:
return fmt.Sprintf("%d hours", h)
case m > 0:
return fmt.Sprintf("%d minutes", m)
default:
return fmt.Sprintf("%d seconds", sec)
}
}
// formatDaySeconds renders a "seconds since midnight" string as "HH:MM".
// Returns "" when raw is missing, non-numeric, or outside [0, 24h). Seconds
// are truncated because the API only guarantees minute-level meaning for
// daily windows and release times.
func formatDaySeconds(raw string) string {
sec, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64)
if err != nil || sec < 0 || sec >= 24*3600 {
return ""
}
h := sec / 3600
m := (sec % 3600) / 60
return fmt.Sprintf("%02d:%02d", h, m)
}
// roomZoneLabel renders the room's timezone as either a "GMT±X" string
// anchored to today (so DST is respected) when the IANA name resolves, or
// the IANA name itself as a fallback so agents always see the source of
// truth. Returns the local device timezone's label when raw is empty.
func roomZoneLabel(raw string) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return gmtOffsetLabel(time.Now())
}
loc, err := time.LoadLocation(raw)
if err != nil {
return raw
}
return gmtOffsetLabel(time.Now().In(loc))
}
// gmtOffsetLabel formats t's zone offset as "GMT+8" / "GMT-5:30" / "GMT".
// Minute-precision is included only when the offset has a non-zero minute
// component so the common whole-hour case stays terse.
func gmtOffsetLabel(t time.Time) string {
_, offsetSec := t.Zone()
if offsetSec == 0 {
return "GMT"
}
sign := "+"
if offsetSec < 0 {
sign = "-"
offsetSec = -offsetSec
}
h := offsetSec / 3600
m := (offsetSec % 3600) / 60
if m == 0 {
return fmt.Sprintf("GMT%s%d", sign, h)
}
return fmt.Sprintf("GMT%s%d:%02d", sign, h, m)
}
// collectAttendeeRoomIDs extracts omm_ prefixed IDs from a comma-separated
// flag value. Empty / whitespace input returns nil.
func collectAttendeeRoomIDs(raw string) []string {
if strings.TrimSpace(raw) == "" {
return nil
}
var rooms []string
seen := map[string]struct{}{}
for _, part := range strings.Split(raw, ",") {
id := strings.TrimSpace(part)
if !strings.HasPrefix(id, "omm_") {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
rooms = append(rooms, id)
}
return rooms
}
// fetchEventSnapshot GETs the event with attendees so we can read the current
// start / end / recurrence and the room IDs already booked on the event. It is
// best-effort: any error bubbles up so the caller can降级放行 by warning.
//
// One retry is baked in: a `{uid}_{original_time}` event_id refers to a
// specific instance of a recurring series, but until that instance is edited
// and materialised as an exception, the server only knows the master
// (`{uid}_0`) and answers 193001 (event not found). We detect that shape and
// re-issue the GET against the master so the room-check pipeline still has a
// snapshot to work with.
func fetchEventSnapshot(_ context.Context, runtime *common.RuntimeContext, calendarID, eventID string) (*eventSnapshot, error) {
data, err := callEventGet(runtime, calendarID, eventID)
if err != nil {
if masterID, ok := recurringMasterEventID(eventID); ok && isEventNotFound(err) {
data, err = callEventGet(runtime, calendarID, masterID)
}
if err != nil {
return nil, err
}
}
event, _ := data["event"].(map[string]interface{})
if event == nil {
return nil, errs.NewInternalError(errs.SubtypeInvalidResponse, "calendar event response missing 'event' field")
}
snap := &eventSnapshot{}
if start, _ := event["start_time"].(map[string]interface{}); start != nil {
if ts, _ := start["timestamp"].(string); ts != "" {
snap.StartTs = ts
}
if tz, _ := start["timezone"].(string); tz != "" {
snap.Timezone = tz
}
}
if end, _ := event["end_time"].(map[string]interface{}); end != nil {
if ts, _ := end["timestamp"].(string); ts != "" {
snap.EndTs = ts
}
if snap.Timezone == "" {
if tz, _ := end["timezone"].(string); tz != "" {
snap.Timezone = tz
}
}
}
if r, _ := event["recurrence"].(string); r != "" {
snap.Recurrent = r
}
attendees, _ := event["attendees"].([]interface{})
seen := map[string]struct{}{}
for _, raw := range attendees {
m, ok := raw.(map[string]interface{})
if !ok {
continue
}
if t, _ := m["type"].(string); t != "resource" {
continue
}
id, _ := m["room_id"].(string)
if id == "" {
continue
}
if status, _ := m["rsvp_status"].(string); status == "removed" {
continue
}
if _, ok := seen[id]; ok {
continue
}
seen[id] = struct{}{}
snap.RoomIDs = append(snap.RoomIDs, id)
}
return snap, nil
}
// callEventGet issues the calendar event GET used by fetchEventSnapshot. It
// is factored out so the 193001 fallback can re-issue the request against
// the master event without duplicating the params / path plumbing.
func callEventGet(runtime *common.RuntimeContext, calendarID, eventID string) (map[string]interface{}, error) {
path := fmt.Sprintf("/open-apis/calendar/v4/calendars/%s/events/%s",
validate.EncodePathSegment(calendarID), validate.EncodePathSegment(eventID))
params := map[string]interface{}{
"user_id_type": "open_id",
"need_attendee": true,
"max_attendee_num": 20,
}
return runtime.CallAPITyped("GET", path, params, nil)
}
// recurringMasterEventID inspects a calendar event_id shaped like
// `{uid}_{original_time}` and returns `{uid}_0` when original_time is a
// positive integer, plus true so callers know a fallback is worth trying.
// Any other shape (missing underscore, non-numeric suffix, already `_0`, or
// suffix `0` / negative) returns "", false so we don't retry pointlessly.
func recurringMasterEventID(eventID string) (string, bool) {
idx := strings.LastIndex(eventID, "_")
if idx <= 0 || idx == len(eventID)-1 {
return "", false
}
uid := eventID[:idx]
suffix := eventID[idx+1:]
n, err := strconv.ParseInt(suffix, 10, 64)
if err != nil || n <= 0 {
return "", false
}
return uid + "_0", true
}
// isEventNotFound returns true when err is a calendar 193001 (event not
// found) API error. Kept in this file rather than shared with
// unwrapCalendarAPIError because that helper returns a user-facing hint —
// here we only need the classification, not the copy.
func isEventNotFound(err error) bool {
if err == nil {
return false
}
var ae *errs.APIError
if !errors.As(err, &ae) {
return false
}
return ae.Code == 193001
}
// roomCheckPlan bundles the resolved inputs for the pre-check API call.
type roomCheckPlan struct {
RoomIDs []string
StartTs string
EndTs string
StartTimezone string
Rrule string
}
// resolveRoomCheckPlan works out which rooms to check and the target time
// window. It applies the降级放行 policy: if the event snapshot fails to load
// but we can proceed with only user-provided inputs (i.e., time changed and a
// new room is added), the pre-check still runs against those. Otherwise it
// warns and returns (nil, nil) so the caller skips the check.
//
// Returns (nil, nil) when no check is warranted.
func resolveRoomCheckPlan(ctx context.Context, runtime *common.RuntimeContext, calendarID, eventID string, newStartTs, newEndTs string, timeChanged, rruleChanged bool) (*roomCheckPlan, error) {
newRooms := collectAttendeeRoomIDs(runtime.Str("add-attendee-ids"))
removeSet := map[string]struct{}{}
for _, id := range collectAttendeeRoomIDs(runtime.Str("remove-attendee-ids")) {
removeSet[id] = struct{}{}
}
// Fast path: only trigger the check when it can find something to look at.
// - New room attendees → always check.
// - Time or rrule change → check existing rooms if any.
if len(newRooms) == 0 && !timeChanged && !rruleChanged {
return nil, nil
}
newRrule := strings.TrimSpace(runtime.Str("rrule"))
// If we don't need existing rooms and have both start/end, skip the GET.
needSnapshot := timeChanged || rruleChanged || !timeChanged && len(newRooms) > 0
var snap *eventSnapshot
if needSnapshot {
var err error
snap, err = fetchEventSnapshot(ctx, runtime, calendarID, eventID)
if err != nil {
fmt.Fprintf(runtime.IO().ErrOut,
"[calendar +update] warning: failed to fetch current event for room-availability check (%v); precheck runs only against user-supplied inputs — pass --%s to silence\n",
err, flagSkipRoomCheck)
snap = nil
}
}
plan := &roomCheckPlan{
StartTs: newStartTs,
EndTs: newEndTs,
Rrule: newRrule,
}
if plan.StartTs == "" && snap != nil {
plan.StartTs = snap.StartTs
}
if plan.EndTs == "" && snap != nil {
plan.EndTs = snap.EndTs
}
if plan.Rrule == "" && snap != nil {
plan.Rrule = snap.Recurrent
}
if snap != nil {
plan.StartTimezone = snap.Timezone
}
seen := map[string]struct{}{}
addRoom := func(id string) {
if id == "" {
return
}
if _, ok := removeSet[id]; ok {
return
}
if _, ok := seen[id]; ok {
return
}
seen[id] = struct{}{}
plan.RoomIDs = append(plan.RoomIDs, id)
}
for _, id := range newRooms {
addRoom(id)
}
if snap != nil && (timeChanged || rruleChanged) {
for _, id := range snap.RoomIDs {
addRoom(id)
}
}
if len(plan.RoomIDs) == 0 {
return nil, nil
}
// Without a target window the server has no basis to check anything;
// prefer degrading gracefully to blocking legitimate updates.
if plan.StartTs == "" || plan.EndTs == "" {
fmt.Fprintf(runtime.IO().ErrOut,
"[calendar +update] warning: room-availability check skipped because start/end could not be resolved; pass --%s to silence\n",
flagSkipRoomCheck)
return nil, nil
}
return plan, nil
}
// roomCheckPlanDurationSec returns the current booking duration in whole
// seconds derived from the resolved plan's Unix-second window, or 0 when
// either bound is missing or unparseable. Used to compare against
// approval_duration_threshold when the API asks for approval.
func roomCheckPlanDurationSec(plan *roomCheckPlan) int64 {
if plan == nil {
return 0
}
start, err := strconv.ParseInt(strings.TrimSpace(plan.StartTs), 10, 64)
if err != nil {
return 0
}
end, err := strconv.ParseInt(strings.TrimSpace(plan.EndTs), 10, 64)
if err != nil {
return 0
}
if end <= start {
return 0
}
return end - start
}
// buildRoomCheckBody assembles the request body for room_availability_check.
// The pre-check API expects start/end as RFC3339 timestamps; we take the
// Unix-second strings used elsewhere in the update flow and render them in
// the event's own timezone when available, falling back to the local device
// timezone so agents on different machines still produce a valid request.
// start_timezone is an IANA name (e.g. "Asia/Shanghai") copied from the event
// snapshot; it is omitted when unknown so the server can fall back to its own
// default.
func buildRoomCheckBody(calendarID, eventID string, plan *roomCheckPlan) map[string]interface{} {
loc := time.Local
if plan.StartTimezone != "" {
if l, err := time.LoadLocation(plan.StartTimezone); err == nil {
loc = l
}
}
body := map[string]interface{}{
"calendar_id": calendarID,
"event_id": eventID,
"start_time": formatRoomCheckTime(plan.StartTs, loc),
"end_time": formatRoomCheckTime(plan.EndTs, loc),
"room_ids": plan.RoomIDs,
}
if plan.StartTimezone != "" {
body["start_timezone"] = plan.StartTimezone
}
if plan.Rrule != "" {
body["event_rrule"] = plan.Rrule
}
return body
}
// formatRoomCheckTime renders a Unix-second string as RFC3339 in loc.
// Non-numeric input is returned unchanged so anomalies stay visible instead
// of being silently rewritten to the epoch.
func formatRoomCheckTime(unixStr string, loc *time.Location) string {
sec, err := strconv.ParseInt(strings.TrimSpace(unixStr), 10, 64)
if err != nil {
return unixStr
}
return time.Unix(sec, 0).In(loc).Format(time.RFC3339)
}
// callRoomAvailabilityCheck posts the availability request and returns per-room
// results.
func callRoomAvailabilityCheck(runtime *common.RuntimeContext, body map[string]interface{}) ([]roomAvailability, error) {
data, err := runtime.CallAPITyped("POST", roomCheckPath, nil, body)
if err != nil {
return nil, err
}
rawList, _ := data["room_availabilitys"].([]interface{})
out := make([]roomAvailability, 0, len(rawList))
for _, raw := range rawList {
m, ok := raw.(map[string]interface{})
if !ok {
continue
}
item := roomAvailability{}
if v, ok := m["room_id"].(string); ok {
item.RoomID = v
}
if v, ok := m["room_name"].(string); ok {
item.RoomName = v
}
if v, ok := m["status"].(string); ok {
item.Status = v
}
if v, ok := m["unavailable_reason_type"].(string); ok {
item.UnavailableReasonType = v
}
if strat, ok := m["room_strategy"].(map[string]interface{}); ok {
item.Strategy = parseRoomStrategy(strat)
}
if req, ok := m["room_requisition"].(map[string]interface{}); ok {
item.Requisition = parseRoomRequisition(req)
}
if info, ok := m["room_approval_info"].(map[string]interface{}); ok {
item.ApprovalInfo = parseRoomApprovalInfo(info)
}
out = append(out, item)
}
return out, nil
}
// parseRoomStrategy extracts the optional strategy fields from a raw API
// map. Missing / non-string values are dropped so callers only see what the
// server actually sent.
func parseRoomStrategy(m map[string]interface{}) *roomStrategy {
s := &roomStrategy{}
if v, ok := m["single_max_duration"].(string); ok {
s.SingleMaxDuration = v
}
if v, ok := m["max_advance_booking_time"].(string); ok {
s.MaxAdvanceBookingTime = v
}
if v, ok := m["daily_start_time"].(string); ok {
s.DailyStartTime = v
}
if v, ok := m["daily_end_time"].(string); ok {
s.DailyEndTime = v
}
if v, ok := m["timezone"].(string); ok {
s.Timezone = v
}
if v, ok := m["daily_advance_window_release_time"].(string); ok {
s.DailyAdvanceWindowReleaseTime = v
}
return s
}
// parseRoomRequisition extracts the optional room_requisition block from a
// raw API map. Missing / non-string values are dropped.
func parseRoomRequisition(m map[string]interface{}) *roomRequisition {
r := &roomRequisition{}
if v, ok := m["start_time"].(string); ok {
r.StartTime = v
}
if v, ok := m["end_time"].(string); ok {
r.EndTime = v
}
return r
}
// parseRoomApprovalInfo extracts the optional room_approval_info block from a
// raw API map. Missing / non-string values are dropped.
func parseRoomApprovalInfo(m map[string]interface{}) *roomApprovalInfo {
info := &roomApprovalInfo{}
if v, ok := m["approval_mode"].(string); ok {
info.ApprovalMode = v
}
if v, ok := m["approval_duration_threshold"].(string); ok {
info.ApprovalDurationThreshold = v
}
return info
}
// approvalReasonHint composes the per-line phrase for a `need_approval`
// status. The API returns `room_approval_info` with:
//
// - "all" → every reservation on this room must be approved.
// - "over_duration" → only bookings longer than approval_duration_threshold
// need approval. The current event duration (eventDurationSec) is compared
// against the threshold so agents can see exactly why approval is being
// asked for — and, when the current duration is below the threshold, the
// message points at the "shorten it" recovery path.
// - anything else → generic reminder so unknown modes still surface.
//
// This function only produces the per-room fragment. The shared recovery
// clause (attendees-create, client fallback, shorten, pick another room) is
// appended once by blockOnUnavailableRooms into `.WithHint(...)` so a message
// with several approval-required rooms doesn't repeat the same recovery
// paragraph on every line.
func approvalReasonHint(info *roomApprovalInfo, eventDurationSec int64) string {
mode := ""
if info != nil {
mode = strings.TrimSpace(info.ApprovalMode)
}
switch mode {
case "all":
return "this room requires approval for every reservation"
case "over_duration":
threshold, _ := strconv.ParseInt(strings.TrimSpace(info.ApprovalDurationThreshold), 10, 64)
if threshold <= 0 {
// Server said approval-by-duration but didn't give a threshold —
// keep the mode label so agents don't lose the classification.
return "this room requires approval when the booking exceeds a duration threshold"
}
thresholdPhrase := formatDurationSeconds(info.ApprovalDurationThreshold)
if thresholdPhrase == "" {
thresholdPhrase = fmt.Sprintf("%d seconds", threshold)
}
base := fmt.Sprintf("this room requires approval when the booking exceeds %s", thresholdPhrase)
if eventDurationSec > 0 {
currentPhrase := formatDurationSeconds(strconv.FormatInt(eventDurationSec, 10))
if currentPhrase == "" {
currentPhrase = fmt.Sprintf("%d seconds", eventDurationSec)
}
if eventDurationSec >= threshold {
base += fmt.Sprintf(" (current duration is %s)", currentPhrase)
} else {
// Server flagged approval but our duration reads as below the
// threshold — surface both so the agent can reconcile rather
// than guess.
base += fmt.Sprintf(" (current duration reads as %s; server still flagged approval)", currentPhrase)
}
}
return base
default:
return "this room requires approval before it can be booked"
}
}
// roomLabel renders the room identifier for the block message. When the API
// returns a human-readable name it becomes `<room_id>[<room_name>]`; a blank
// name (or an entirely blank id, defensive) degrades to whichever is present
// so agents can still address the room. The room_id is kept as the primary
// identifier because callers act on it programmatically. Square brackets are
// used (rather than parentheses) so a room name that itself contains
// parentheses — e.g. "Room A (west wing)" — doesn't produce ambiguous nesting
// like `omm_1(Room A (west wing))`.
func roomLabel(id, name string) string {
id = strings.TrimSpace(id)
name = strings.TrimSpace(name)
switch {
case id != "" && name != "":
return fmt.Sprintf("%s[%s]", id, name)
case id != "":
return id
default:
return name
}
}
// blockOnUnavailableRooms returns a typed validation error when any room in
// results is unavailable or requires approval, or nil when everything is
// bookable. The error text carries per-room reasons plus the retry command
// hint from the PRD. When the API returns a room_strategy for a blocked room,
// the relevant limit (max duration, latest bookable time, daily window, or
// daily release time) is appended after the reason so agents can relay it to
// the user without making a follow-up request. For a `during_requisition`
// block, the disabled period (from room_requisition) is appended if available;
// a "pick a different time or a different room" recovery clause is always
// appended so the message reads coherently whether or not exact bounds are
// known.
//
// `need_approval` results are treated as blocking (the CLI cannot submit an
// approval on the user's behalf, so silently PATCHing would surprise the
// user). The line uses room_approval_info + eventDurationSec to explain the
// mode ("all" / "over_duration"), the threshold, and — for over_duration —
// how the current booking compares. The shared "how do I actually recover
// from approval" clause is folded into the hint once (not per line), so
// several approval-required rooms don't repeat the same paragraph.
func blockOnUnavailableRooms(results []roomAvailability, eventDurationSec int64) error {
var blocked []roomAvailability
for _, r := range results {
if r.Status != "available" {
blocked = append(blocked, r)
}
}
if len(blocked) == 0 {
return nil
}
var lines []string
hasNeedApproval := false
for _, r := range blocked {
var reason string
switch r.Status {
case "need_approval":
hasNeedApproval = true
reason = approvalReasonHint(r.ApprovalInfo, eventDurationSec)
default:
reason = unavailableReasonHint(r.UnavailableReasonType)
}
line := fmt.Sprintf("%s: %s", roomLabel(r.RoomID, r.RoomName), reason)
if detail := strategyDetail(r.UnavailableReasonType, r.Strategy); detail != "" {
line += ", " + detail
}
if detail := requisitionDetail(r.UnavailableReasonType, r.Requisition); detail != "" {
line += ", " + detail
}
if r.UnavailableReasonType == "during_requisition" {
line += "; pick a different time or a different room"
}
lines = append(lines, line)
}
msg := "meeting room booking will fail after this event change:\n " + strings.Join(lines, "\n ")
hint := fmt.Sprintf("do NOT auto-retry: relay the room IDs and reasons above to the user and get explicit confirmation before re-running with --%s.",
flagSkipRoomCheck)
if hasNeedApproval {
hint += " Rooms flagged need_approval: the CLI cannot submit approvals; DO NOT auto-run any recovery — ask the user first, then pick one: (a) newly added room → after the user confirms and provides `approval_reason`, run `lark-cli calendar event.attendees create --as user`; (b) time/rrule change re-triggers approval on an existing room → ask the user to update through the client; (c) shorten the meeting below the threshold or pick a different room."
}
return errs.NewValidationError(errs.SubtypeFailedPrecondition, "%s", msg).WithHint("%s", hint)
}

View File

@@ -3368,3 +3368,952 @@ func TestGet_MissingEventField_TypedInternal(t *testing.T) {
t.Errorf("subtype=%q, want invalid_response", ie.Subtype)
}
}
// ---------------------------------------------------------------------------
// CalendarUpdate room-availability precheck tests
// ---------------------------------------------------------------------------
// eventSnapshotStub builds a GET-event fixture with the given rooms + window
// so room-check helpers can read a plausible snapshot.
func eventSnapshotStub(calendarID, eventID, startTs, endTs string, roomIDs ...string) *httpmock.Stub {
attendees := make([]interface{}, 0, len(roomIDs))
for _, id := range roomIDs {
attendees = append(attendees, map[string]interface{}{
"type": "resource",
"room_id": id,
})
}
return &httpmock.Stub{
Method: "GET",
URL: "/open-apis/calendar/v4/calendars/" + calendarID + "/events/" + eventID,
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"event": map[string]interface{}{
"event_id": eventID,
"summary": "Existing",
"start_time": map[string]interface{}{"timestamp": startTs, "timezone": "Asia/Shanghai"},
"end_time": map[string]interface{}{"timestamp": endTs, "timezone": "Asia/Shanghai"},
"attendees": attendees,
},
},
},
Reusable: true,
}
}
func TestUpdate_RoomCheck_SkipFlag_BypassesAPI(t *testing.T) {
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
// Register the PATCH stub but no room-check stub — the test asserts that no
// unmatched request is made.
patchStub := &httpmock.Stub{
Method: "PATCH",
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/evt_rc1",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{"event": map[string]interface{}{"event_id": "evt_rc1"}},
},
}
reg.Register(patchStub)
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc1",
"--calendar-id", "cal_rc",
"--summary", "Skip",
"--start", "2025-03-21T00:00:00+08:00",
"--end", "2025-03-21T01:00:00+08:00",
"--skip-room-check",
"--as", "bot",
}, f, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(patchStub.CapturedBody) == 0 {
t.Fatalf("expected PATCH to be captured")
}
}
func TestUpdate_RoomCheck_TitleOnly_SkipsCheck(t *testing.T) {
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
// Only registered PATCH; title-only changes should never trigger room-check
// and never fetch the event snapshot.
patchStub := &httpmock.Stub{
Method: "PATCH",
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/evt_rc2",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{"event": map[string]interface{}{"event_id": "evt_rc2"}},
},
}
reg.Register(patchStub)
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc2",
"--calendar-id", "cal_rc",
"--summary", "New title only",
"--as", "bot",
}, f, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(patchStub.CapturedBody) == 0 {
t.Fatalf("expected PATCH to be captured")
}
}
func TestUpdate_RoomCheck_NewRoomAvailable_Allows(t *testing.T) {
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
// Snapshot has no existing rooms; we're adding omm_new.
reg.Register(eventSnapshotStub("cal_rc", "evt_rc3", "1742515200", "1742518800"))
checkStub := &httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"room_availabilitys": []interface{}{
map[string]interface{}{"room_id": "omm_new", "status": "available"},
},
},
},
}
reg.Register(checkStub)
addStub := &httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/evt_rc3/attendees",
Body: map[string]interface{}{"code": 0, "msg": "ok", "data": map[string]interface{}{}},
}
reg.Register(addStub)
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc3",
"--calendar-id", "cal_rc",
"--add-attendee-ids", "omm_new",
"--as", "bot",
}, f, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(checkStub.CapturedBody) == 0 {
t.Fatalf("expected room-availability-check to be called")
}
body := decodeCalendarCapturedBody(t, checkStub)
rooms, _ := body["room_ids"].([]interface{})
if len(rooms) != 1 || rooms[0] != "omm_new" {
t.Fatalf("room_ids should be [omm_new], got %#v", rooms)
}
if body["calendar_id"] != "cal_rc" || body["event_id"] != "evt_rc3" {
t.Fatalf("room-check body missing ids: %#v", body)
}
if body["start_timezone"] != "Asia/Shanghai" {
t.Fatalf("start_timezone should carry snapshot value, got %#v", body["start_timezone"])
}
if body["start_time"] != "2025-03-21T08:00:00+08:00" {
t.Fatalf("start_time should be RFC3339 in event tz, got %#v", body["start_time"])
}
if body["end_time"] != "2025-03-21T09:00:00+08:00" {
t.Fatalf("end_time should be RFC3339 in event tz, got %#v", body["end_time"])
}
if len(addStub.CapturedBody) == 0 {
t.Fatalf("expected add-attendees POST to run")
}
}
func TestUpdate_RoomCheck_NewRoomUnavailable_Blocks(t *testing.T) {
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
reg.Register(eventSnapshotStub("cal_rc", "evt_rc4", "1742515200", "1742518800"))
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"room_availabilitys": []interface{}{
map[string]interface{}{
"room_id": "omm_busy",
"status": "unavailable",
"unavailable_reason_type": "reserved_by_other_event",
},
},
},
},
})
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc4",
"--calendar-id", "cal_rc",
"--add-attendee-ids", "omm_busy",
"--as", "bot",
}, f, nil)
if err == nil {
t.Fatal("expected block error when room is unavailable")
}
var ve *errs.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("want *errs.ValidationError, got %T (%v)", err, err)
}
if ve.Subtype != errs.SubtypeFailedPrecondition {
t.Errorf("subtype=%q, want failed_precondition", ve.Subtype)
}
if !strings.Contains(ve.Message, "omm_busy") {
t.Errorf("message should list blocked room id, got: %q", ve.Message)
}
if !strings.Contains(ve.Hint, "--skip-room-check") {
t.Errorf("hint should mention --skip-room-check, got: %q", ve.Hint)
}
}
func TestUpdate_RoomCheck_TimeChanged_ChecksExistingRoom(t *testing.T) {
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
// Existing event already has omm_existing booked.
reg.Register(eventSnapshotStub("cal_rc", "evt_rc5", "1742515200", "1742518800", "omm_existing"))
checkStub := &httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"room_availabilitys": []interface{}{
map[string]interface{}{"room_id": "omm_existing", "status": "available"},
},
},
},
}
reg.Register(checkStub)
patchStub := &httpmock.Stub{
Method: "PATCH",
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/evt_rc5",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{"event": map[string]interface{}{"event_id": "evt_rc5"}},
},
}
reg.Register(patchStub)
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc5",
"--calendar-id", "cal_rc",
"--start", "2025-03-21T02:00:00+08:00",
"--end", "2025-03-21T03:00:00+08:00",
"--as", "bot",
}, f, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(checkStub.CapturedBody) == 0 {
t.Fatalf("expected room-check to run for existing room on time change")
}
body := decodeCalendarCapturedBody(t, checkStub)
rooms, _ := body["room_ids"].([]interface{})
if len(rooms) != 1 || rooms[0] != "omm_existing" {
t.Fatalf("room_ids should be [omm_existing], got %#v", rooms)
}
if len(patchStub.CapturedBody) == 0 {
t.Fatalf("expected PATCH to run after check passes")
}
}
func TestUpdate_RoomCheck_APIFailure_DegradesGracefully(t *testing.T) {
f, _, stderr, reg := cmdutil.TestFactory(t, defaultConfig())
reg.Register(eventSnapshotStub("cal_rc", "evt_rc6", "1742515200", "1742518800"))
// Simulate room-check API failure (e.g., not yet rolled out) so the CLI
// degrades gracefully instead of blocking the update.
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
Body: map[string]interface{}{
"code": 190001,
"msg": "permission denied",
},
})
addStub := &httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/evt_rc6/attendees",
Body: map[string]interface{}{"code": 0, "msg": "ok", "data": map[string]interface{}{}},
}
reg.Register(addStub)
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc6",
"--calendar-id", "cal_rc",
"--add-attendee-ids", "omm_new",
"--as", "bot",
}, f, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(addStub.CapturedBody) == 0 {
t.Fatalf("expected add-attendees POST to run despite check failure")
}
if !strings.Contains(stderr.String(), "room availability check failed") {
t.Errorf("stderr should warn about degraded check, got: %q", stderr.String())
}
}
func TestUpdate_RoomCheck_DryRun_IncludesPrecheckStep(t *testing.T) {
f, stdout, _, _ := cmdutil.TestFactory(t, defaultConfig())
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc7",
"--calendar-id", "cal_rc",
"--add-attendee-ids", "omm_dryrun",
"--start", "2025-03-21T00:00:00+08:00",
"--end", "2025-03-21T01:00:00+08:00",
"--dry-run",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
out := stdout.String()
if !strings.Contains(out, "room_availability_check") {
t.Fatalf("dry-run should preview room_availability_check, got: %s", out)
}
if !strings.Contains(out, "Pre-check meeting room availability") {
t.Fatalf("dry-run should describe pre-check step, got: %s", out)
}
}
func TestUpdate_RoomCheck_DryRun_SkipFlagOmitsStep(t *testing.T) {
f, stdout, _, _ := cmdutil.TestFactory(t, defaultConfig())
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc8",
"--calendar-id", "cal_rc",
"--add-attendee-ids", "omm_dryrun2",
"--start", "2025-03-21T00:00:00+08:00",
"--end", "2025-03-21T01:00:00+08:00",
"--skip-room-check",
"--dry-run",
"--as", "bot",
}, f, stdout)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
out := stdout.String()
if strings.Contains(out, "room_availability_check") {
t.Fatalf("dry-run with --skip-room-check should not preview room_availability_check, got: %s", out)
}
}
// TestStrategyDetail_ByReason exercises the human-readable strategy suffix
// appended to each blocked-room line. Timezone-anchored fields use a fixed
// IANA name so the offset ("GMT+8") is deterministic across machines.
func TestStrategyDetail_ByReason(t *testing.T) {
tests := []struct {
name string
reason string
strategy *roomStrategy
want string
}{
{
name: "over_max_duration renders as hours",
reason: "over_max_duration",
strategy: &roomStrategy{SingleMaxDuration: "10800"},
want: "the max single-booking duration is 3 hours",
},
{
name: "over_max_duration mixed hours and minutes",
reason: "over_max_duration",
strategy: &roomStrategy{SingleMaxDuration: "5400"},
want: "the max single-booking duration is 1 hours 30 minutes",
},
{
name: "beyond_advance_booking_window surfaces rfc3339 verbatim",
reason: "beyond_advance_booking_window",
strategy: &roomStrategy{MaxAdvanceBookingTime: "2026-07-13T18:00:00+08:00", Timezone: "Asia/Shanghai"},
want: "the latest bookable end time is 2026-07-13T18:00:00+08:00",
},
{
name: "not_in_usable_time renders day-seconds and zone",
reason: "not_in_usable_time",
strategy: &roomStrategy{DailyStartTime: "36000", DailyEndTime: "72000", Timezone: "Asia/Shanghai"},
want: "the daily bookable window is 10:00 - 20:00 (GMT+8)",
},
{
name: "before_daily_advance_window_release renders unlock time and zone",
reason: "before_daily_advance_window_release",
strategy: &roomStrategy{DailyAdvanceWindowReleaseTime: "28800", Timezone: "Asia/Shanghai"},
want: "the next unlock happens today at 08:00 (GMT+8), which advances the window by one day",
},
{
name: "past_time has no strategy suffix",
reason: "past_time",
strategy: &roomStrategy{SingleMaxDuration: "10800"},
want: "",
},
{
name: "nil strategy returns empty",
reason: "over_max_duration",
strategy: nil,
want: "",
},
{
name: "invalid duration returns empty",
reason: "over_max_duration",
strategy: &roomStrategy{SingleMaxDuration: "not-a-number"},
want: "",
},
{
name: "day-seconds out of range returns empty",
reason: "not_in_usable_time",
strategy: &roomStrategy{DailyStartTime: "-1", DailyEndTime: "999999", Timezone: "Asia/Shanghai"},
want: "",
},
{
name: "unresolvable timezone falls back to iana name",
reason: "before_daily_advance_window_release",
strategy: &roomStrategy{DailyAdvanceWindowReleaseTime: "28800", Timezone: "Not/AReal_Zone"},
want: "the next unlock happens today at 08:00 (Not/AReal_Zone), which advances the window by one day",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := strategyDetail(tt.reason, tt.strategy)
if got != tt.want {
t.Errorf("strategyDetail(%q) = %q, want %q", tt.reason, got, tt.want)
}
})
}
}
// TestUpdate_RoomCheck_StrategyDetailInMessage pins that when the API returns a
// room_strategy alongside the unavailable_reason_type, blockOnUnavailableRooms
// surfaces the specific limit inline so agents can relay it to the user
// without an extra round trip.
func TestUpdate_RoomCheck_StrategyDetailInMessage(t *testing.T) {
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
reg.Register(eventSnapshotStub("cal_rc", "evt_rc_strategy", "1742515200", "1742525200"))
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"room_availabilitys": []interface{}{
map[string]interface{}{
"room_id": "omm_toolong",
"status": "unavailable",
"unavailable_reason_type": "over_max_duration",
"room_strategy": map[string]interface{}{
"single_max_duration": "10800",
"timezone": "Asia/Shanghai",
},
},
},
},
},
})
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc_strategy",
"--calendar-id", "cal_rc",
"--add-attendee-ids", "omm_toolong",
"--as", "bot",
}, f, nil)
if err == nil {
t.Fatal("expected block error when strategy limit is hit")
}
var ve *errs.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("want *errs.ValidationError, got %T (%v)", err, err)
}
if !strings.Contains(ve.Message, "the max single-booking duration is 3 hours") {
t.Errorf("message should surface the max-duration limit, got: %q", ve.Message)
}
if !strings.Contains(ve.Message, "omm_toolong") {
t.Errorf("message should still list the room id, got: %q", ve.Message)
}
}
// TestRequisitionDetail_ByBounds pins the human-readable suffix rendered for a
// `during_requisition` block. Every variant (both bounds, start only, end
// only, none, nil requisition, non-matching reason) must degrade coherently.
func TestRequisitionDetail_ByBounds(t *testing.T) {
tests := []struct {
name string
req *roomRequisition
want string
}{
{
name: "both bounds surface as verbatim rfc3339 range",
req: &roomRequisition{StartTime: "2026-07-13T09:00:00+08:00", EndTime: "2026-07-13T18:00:00+08:00"},
want: "the disabled period is 2026-07-13T09:00:00+08:00 to 2026-07-13T18:00:00+08:00",
},
{
name: "start only",
req: &roomRequisition{StartTime: "2026-07-13T09:00:00+08:00"},
want: "the disabled period starts at 2026-07-13T09:00:00+08:00",
},
{
name: "end only",
req: &roomRequisition{EndTime: "2026-07-13T18:00:00+08:00"},
want: "the disabled period ends at 2026-07-13T18:00:00+08:00",
},
{
name: "empty bounds return no detail",
req: &roomRequisition{},
want: "",
},
{
name: "nil requisition returns empty",
req: nil,
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := requisitionDetail("during_requisition", tt.req)
if got != tt.want {
t.Errorf("requisitionDetail(during_requisition) = %q, want %q", got, tt.want)
}
})
}
// Non-matching reason should always short-circuit even with a full payload.
if got := requisitionDetail("reserved_by_other_event", &roomRequisition{StartTime: "x", EndTime: "y"}); got != "" {
t.Errorf("requisitionDetail should ignore requisition for non-during_requisition reasons, got %q", got)
}
}
// TestUpdate_RoomCheck_RequisitionDetailInMessage pins that when the API
// returns room_requisition alongside a during_requisition block, the disabled
// period is surfaced inline and the recovery clause is always present.
func TestUpdate_RoomCheck_RequisitionDetailInMessage(t *testing.T) {
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
reg.Register(eventSnapshotStub("cal_rc", "evt_rc_req", "1742515200", "1742525200"))
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"room_availabilitys": []interface{}{
map[string]interface{}{
"room_id": "omm_req",
"room_name": "Meeting Room A",
"status": "unavailable",
"unavailable_reason_type": "during_requisition",
"room_requisition": map[string]interface{}{
"start_time": "2026-07-13T09:00:00+08:00",
"end_time": "2026-07-13T18:00:00+08:00",
},
},
},
},
},
})
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc_req",
"--calendar-id", "cal_rc",
"--add-attendee-ids", "omm_req",
"--as", "bot",
}, f, nil)
if err == nil {
t.Fatal("expected block error for during_requisition")
}
var ve *errs.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("want *errs.ValidationError, got %T (%v)", err, err)
}
if !strings.Contains(ve.Message, "the disabled period is 2026-07-13T09:00:00+08:00 to 2026-07-13T18:00:00+08:00") {
t.Errorf("message should surface the disabled period, got: %q", ve.Message)
}
if !strings.Contains(ve.Message, "pick a different time or a different room") {
t.Errorf("message should always include recovery hint, got: %q", ve.Message)
}
if !strings.Contains(ve.Message, "omm_req[Meeting Room A]") {
t.Errorf("message should render room id with human-readable name, got: %q", ve.Message)
}
}
// TestRoomLabel_ByFields pins the room identifier rendering used in the block
// message. `<room_id>(<room_name>)` when both are present; degrades to
// whichever is non-empty when the other is missing.
func TestRoomLabel_ByFields(t *testing.T) {
tests := []struct {
name string
id string
room string
want string
}{
{name: "both present", id: "omm_1", room: "Meeting Room A", want: "omm_1[Meeting Room A]"},
{name: "id only", id: "omm_2", room: "", want: "omm_2"},
{name: "id only with whitespace name", id: "omm_3", room: " ", want: "omm_3"},
{name: "name only degrades to name", id: "", room: "Room B", want: "Room B"},
{name: "both blank returns empty", id: "", room: "", want: ""},
{name: "name with parens does not create ambiguous nesting", id: "omm_4", room: "Room A (west wing)", want: "omm_4[Room A (west wing)]"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := roomLabel(tt.id, tt.room); got != tt.want {
t.Errorf("roomLabel(%q, %q) = %q, want %q", tt.id, tt.room, got, tt.want)
}
})
}
}
// TestRecurringMasterEventID_Shapes pins the recurringMasterEventID contract:
// only `{uid}_{positive int}` collapses to `{uid}_0`; everything else opts out.
func TestRecurringMasterEventID_Shapes(t *testing.T) {
tests := []struct {
in string
wantID string
wantOK bool
scenario string
}{
{in: "abc_1742515200", wantID: "abc_0", wantOK: true, scenario: "positive suffix collapses to master"},
{in: "abc_1", wantID: "abc_0", wantOK: true, scenario: "positive one collapses to master"},
{in: "abc_0", wantID: "", wantOK: false, scenario: "already master"},
{in: "abc", wantID: "", wantOK: false, scenario: "no underscore"},
{in: "_1742515200", wantID: "", wantOK: false, scenario: "empty uid"},
{in: "abc_", wantID: "", wantOK: false, scenario: "empty suffix"},
{in: "abc_-1", wantID: "", wantOK: false, scenario: "negative suffix"},
{in: "abc_xyz", wantID: "", wantOK: false, scenario: "non-numeric suffix"},
{in: "abc_def_1742515200", wantID: "abc_def_0", wantOK: true, scenario: "uid may contain underscore"},
}
for _, tt := range tests {
t.Run(tt.scenario, func(t *testing.T) {
gotID, gotOK := recurringMasterEventID(tt.in)
if gotID != tt.wantID || gotOK != tt.wantOK {
t.Errorf("recurringMasterEventID(%q) = (%q, %v), want (%q, %v)", tt.in, gotID, gotOK, tt.wantID, tt.wantOK)
}
})
}
}
// TestUpdate_RoomCheck_EventNotFound_FallsBackToMaster pins the 193001
// fallback: when the event_id is `{uid}_{original_time}` and the server
// answers "event not found", the snapshot GET retries against `{uid}_0`
// (the recurring master), so the room-check pipeline can still proceed.
func TestUpdate_RoomCheck_EventNotFound_FallsBackToMaster(t *testing.T) {
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
// First GET on the instance event: 193001.
instanceStub := &httpmock.Stub{
Method: "GET",
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/uid_master_1742515200",
Body: map[string]interface{}{
"code": 193001,
"msg": "event not found",
},
}
reg.Register(instanceStub)
// Fallback GET on the master event: 200 with an existing room attendee, so
// the pre-check has something to reason about.
masterStub := &httpmock.Stub{
Method: "GET",
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/uid_master_0",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"event": map[string]interface{}{
"event_id": "uid_master_0",
"summary": "Weekly sync",
"start_time": map[string]interface{}{"timestamp": "1742515200", "timezone": "Asia/Shanghai"},
"end_time": map[string]interface{}{"timestamp": "1742518800", "timezone": "Asia/Shanghai"},
"attendees": []interface{}{map[string]interface{}{"type": "resource", "room_id": "omm_from_master"}},
},
},
},
}
reg.Register(masterStub)
// Time change → precheck runs against existing room from the master snapshot.
precheckStub := &httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"room_availabilitys": []interface{}{
map[string]interface{}{
"room_id": "omm_from_master",
"status": "available",
},
},
},
},
}
reg.Register(precheckStub)
// PATCH succeeds.
patchStub := &httpmock.Stub{
Method: "PATCH",
URL: "/open-apis/calendar/v4/calendars/cal_rc/events/uid_master_1742515200",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{"event": map[string]interface{}{"event_id": "uid_master_1742515200"}},
},
}
reg.Register(patchStub)
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "uid_master_1742515200",
"--calendar-id", "cal_rc",
"--start", "2025-03-21T08:00:00+08:00",
"--end", "2025-03-21T09:00:00+08:00",
"--as", "bot",
}, f, nil)
if err != nil {
t.Fatalf("expected update to succeed after master fallback, got %v", err)
}
}
// TestApprovalReasonHint_ByMode pins the copy for each supported approval
// mode, including the over_duration current-vs-threshold branches. The exact
// phrase matters because agents parse it to decide next steps (relay to user,
// shorten the meeting, pick another room).
func TestApprovalReasonHint_ByMode(t *testing.T) {
tests := []struct {
name string
info *roomApprovalInfo
duration int64
mustContain []string
mustNotContain []string
}{
{
name: "all mode always needs approval",
info: &roomApprovalInfo{ApprovalMode: "all"},
duration: 3600,
mustContain: []string{
"requires approval for every reservation",
},
mustNotContain: []string{
"the CLI cannot submit approvals",
"lark-cli calendar event.attendees create",
},
},
{
name: "over_duration with current above threshold cites both",
info: &roomApprovalInfo{ApprovalMode: "over_duration", ApprovalDurationThreshold: "3600"},
duration: 7200,
mustContain: []string{
"exceeds 1 hours",
"current duration is 2 hours",
},
mustNotContain: []string{
"lark-cli calendar event.attendees create",
},
},
{
name: "over_duration with current exactly at threshold treated as over",
info: &roomApprovalInfo{ApprovalMode: "over_duration", ApprovalDurationThreshold: "3600"},
duration: 3600,
mustContain: []string{
"exceeds 1 hours",
"current duration is 1 hours",
},
},
{
name: "over_duration with current below threshold surfaces reconciliation",
info: &roomApprovalInfo{ApprovalMode: "over_duration", ApprovalDurationThreshold: "3600"},
duration: 1800,
mustContain: []string{
"exceeds 1 hours",
"current duration reads as 30 minutes",
"server still flagged approval",
},
},
{
name: "over_duration without threshold keeps mode label",
info: &roomApprovalInfo{ApprovalMode: "over_duration"},
duration: 3600,
mustContain: []string{
"exceeds a duration threshold",
},
mustNotContain: []string{
"the CLI cannot submit approvals",
},
},
{
name: "unknown mode falls back to generic reminder",
info: &roomApprovalInfo{ApprovalMode: "future_mode"},
duration: 3600,
mustContain: []string{
"requires approval before it can be booked",
},
},
{
name: "nil approval info still yields a reminder",
info: nil,
duration: 3600,
mustContain: []string{
"requires approval before it can be booked",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := approvalReasonHint(tt.info, tt.duration)
for _, needle := range tt.mustContain {
if !strings.Contains(got, needle) {
t.Errorf("approvalReasonHint(%+v, %d) missing %q, got: %q", tt.info, tt.duration, needle, got)
}
}
for _, needle := range tt.mustNotContain {
if strings.Contains(got, needle) {
t.Errorf("approvalReasonHint(%+v, %d) should not contain %q (that clause belongs in the hint, not the per-line reason), got: %q", tt.info, tt.duration, needle, got)
}
}
})
}
}
// TestUpdate_RoomCheck_NeedApproval_Blocks pins that a status=="need_approval"
// result blocks the update with a friendly, structured message: mode,
// threshold, current duration comparison, and the "CLI can't approve" clause.
// The block error also carries the same retry hint as the unavailable branch
// so agents don't auto-retry with --skip-room-check.
func TestUpdate_RoomCheck_NeedApproval_Blocks(t *testing.T) {
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
// Snapshot window: 1742515200 -> 1742522400 (2h). Threshold is 1h, so the
// current duration is over threshold.
reg.Register(eventSnapshotStub("cal_rc", "evt_rc_approval", "1742515200", "1742522400"))
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"room_availabilitys": []interface{}{
map[string]interface{}{
"room_id": "omm_approval",
"room_name": "Executive Room",
"status": "need_approval",
"room_approval_info": map[string]interface{}{
"approval_mode": "over_duration",
"approval_duration_threshold": "3600",
},
},
},
},
},
})
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc_approval",
"--calendar-id", "cal_rc",
"--add-attendee-ids", "omm_approval",
"--as", "bot",
}, f, nil)
if err == nil {
t.Fatal("expected need_approval to block the update")
}
var ve *errs.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("want *errs.ValidationError, got %T (%v)", err, err)
}
if !strings.Contains(ve.Message, "omm_approval[Executive Room]") {
t.Errorf("message should render room label, got: %q", ve.Message)
}
if !strings.Contains(ve.Message, "requires approval when the booking exceeds 1 hours") {
t.Errorf("message should carry approval threshold, got: %q", ve.Message)
}
if !strings.Contains(ve.Message, "current duration is 2 hours") {
t.Errorf("message should carry current-vs-threshold comparison, got: %q", ve.Message)
}
if strings.Contains(ve.Message, "the CLI cannot submit approvals inline") {
t.Errorf("recovery clause should live in the hint (not repeated per line in the message), got message: %q", ve.Message)
}
if strings.Contains(ve.Message, "lark-cli calendar event.attendees create --as user") {
t.Errorf("attendees-create recovery clause should live in the hint (not per line), got message: %q", ve.Message)
}
if !strings.Contains(ve.Hint, "the CLI cannot submit approvals") {
t.Errorf("hint should carry the approval recovery clause once, got: %q", ve.Hint)
}
if !strings.Contains(ve.Hint, "DO NOT auto-run") {
t.Errorf("hint should forbid auto-running any approval recovery path without user confirmation, got: %q", ve.Hint)
}
if !strings.Contains(ve.Hint, "ask the user first") {
t.Errorf("hint should require asking the user before picking a recovery path, got: %q", ve.Hint)
}
if !strings.Contains(ve.Hint, "lark-cli calendar event.attendees create --as user") {
t.Errorf("hint should point at the attendees-create recovery path, got: %q", ve.Hint)
}
if !strings.Contains(ve.Hint, "update through the client") {
t.Errorf("hint should mention the client-side fallback for re-approval on existing rooms, got: %q", ve.Hint)
}
if !strings.Contains(ve.Hint, flagSkipRoomCheck) {
t.Errorf("hint should still mention --%s, got: %q", flagSkipRoomCheck, ve.Hint)
}
}
// TestUpdate_RoomCheck_RequisitionMissingBoundsStillCoherent pins that when
// the API returns during_requisition without room_requisition, the recovery
// hint keeps the line coherent on its own.
func TestUpdate_RoomCheck_RequisitionMissingBoundsStillCoherent(t *testing.T) {
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
reg.Register(eventSnapshotStub("cal_rc", "evt_rc_req2", "1742515200", "1742525200"))
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/calendar/v4/freebusy/room_availability_check",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"room_availabilitys": []interface{}{
map[string]interface{}{
"room_id": "omm_req_nobounds",
"status": "unavailable",
"unavailable_reason_type": "during_requisition",
},
},
},
},
})
err := mountAndRun(t, CalendarUpdate, []string{
"+update",
"--event-id", "evt_rc_req2",
"--calendar-id", "cal_rc",
"--add-attendee-ids", "omm_req_nobounds",
"--as", "bot",
}, f, nil)
if err == nil {
t.Fatal("expected block error for during_requisition without bounds")
}
var ve *errs.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("want *errs.ValidationError, got %T (%v)", err, err)
}
if strings.Contains(ve.Message, "the disabled period") {
t.Errorf("message should not fabricate a disabled period, got: %q", ve.Message)
}
if !strings.Contains(ve.Message, "pick a different time or a different room") {
t.Errorf("message should always include recovery hint, got: %q", ve.Message)
}
}

View File

@@ -36,6 +36,7 @@ var CalendarUpdate = common.Shortcut{
{Name: "add-attendee-ids", Desc: "attendee IDs to add, comma-separated (supports user ou_, chat oc_, room omm_)"},
{Name: "remove-attendee-ids", Desc: "attendee IDs to remove, comma-separated (supports user ou_, chat oc_, room omm_)"},
{Name: "notify", Type: "bool", Default: "true", Desc: "send update notification to attendees"},
{Name: flagSkipRoomCheck, Type: "bool", Default: "false", Hidden: true, Desc: "skip meeting-room availability precheck (default checks rooms whenever a new room is added or the time/rrule of a room-attached event changes)"},
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
return validateCalendarUpdate(runtime)
@@ -219,6 +220,50 @@ func calendarUpdateAttendeesPath(calendarID, eventID string) string {
return calendarUpdateEventPath(calendarID, eventID) + "/attendees"
}
// runRoomAvailabilityPrecheck checks any room affected by this update (new
// room attendees, or existing rooms when the time/rrule shifts) against the
// server before the PATCH is issued. It returns nil to allow the update to
// proceed and a typed error to block it. Called only when --skip-room-check
// is false.
func runRoomAvailabilityPrecheck(ctx context.Context, runtime *common.RuntimeContext, calendarID, eventID string, body map[string]interface{}) error {
timeChanged := runtime.Cmd.Flags().Changed("start") && runtime.Cmd.Flags().Changed("end")
rruleChanged := runtime.Cmd.Flags().Changed("rrule")
var newStartTs, newEndTs string
if timeChanged {
if m, _ := body["start_time"].(map[string]string); m != nil {
newStartTs = m["timestamp"]
}
if m, _ := body["end_time"].(map[string]string); m != nil {
newEndTs = m["timestamp"]
}
}
plan, err := resolveRoomCheckPlan(ctx, runtime, calendarID, eventID, newStartTs, newEndTs, timeChanged, rruleChanged)
if err != nil {
return err
}
if plan == nil {
return nil
}
results, err := callRoomAvailabilityCheck(runtime, buildRoomCheckBody(calendarID, eventID, plan))
if err != nil {
// Degrade gracefully: warn on stderr and let the update proceed so the
// pre-check API doesn't gate legitimate updates when it hiccups. For
// 190014 (invalid_parameters) surface the server-supplied field-level
// detail so agents can see why the precheck refused.
msg := unwrapCalendarAPIError(err)
if msg == "" {
msg = err.Error()
}
fmt.Fprintf(runtime.IO().ErrOut,
"[calendar +update] warning: room availability check failed (%s); proceeding with update — pass --%s to silence\n",
msg, flagSkipRoomCheck)
return nil
}
return blockOnUnavailableRooms(results, roomCheckPlanDurationSec(plan))
}
func dryRunCalendarUpdate(runtime *common.RuntimeContext) *common.DryRunAPI {
calendarID, eventID := calendarUpdateIDs(runtime)
displayCalendarID := calendarID
@@ -246,6 +291,33 @@ func dryRunCalendarUpdate(runtime *common.RuntimeContext) *common.DryRunAPI {
d.Desc("multi-step update: event fields, attendee removal, and attendee addition run in order when requested")
}
steps := 0
if !runtime.Bool(flagSkipRoomCheck) {
newRooms := collectAttendeeRoomIDs(runtime.Str("add-attendee-ids"))
timeChanged := runtime.Cmd.Flags().Changed("start") && runtime.Cmd.Flags().Changed("end")
rruleChanged := runtime.Cmd.Flags().Changed("rrule")
if len(newRooms) > 0 || timeChanged || rruleChanged {
steps++
desc := fmt.Sprintf("[%d] Pre-check meeting room availability (default; pass --%s to skip)", steps, flagSkipRoomCheck)
previewBody := map[string]interface{}{
"calendar_id": displayCalendarID,
"event_id": eventID,
"room_ids": newRooms,
"start_timezone": "<inherited from event>",
}
if start, _ := body["start_time"].(map[string]string); start != nil {
previewBody["start_time"] = formatRoomCheckTime(start["timestamp"], time.Local)
}
if end, _ := body["end_time"].(map[string]string); end != nil {
previewBody["end_time"] = formatRoomCheckTime(end["timestamp"], time.Local)
}
if rrule, _ := body["recurrence"].(string); rrule != "" {
previewBody["event_rrule"] = rrule
}
d.POST(roomCheckPath).Desc(desc).Body(previewBody)
}
}
if hasEventFields {
steps++
d.PATCH("/open-apis/calendar/v4/calendars/:calendar_id/events/:event_id").
@@ -278,7 +350,7 @@ func dryRunCalendarUpdate(runtime *common.RuntimeContext) *common.DryRunAPI {
return d
}
func executeCalendarUpdate(_ context.Context, runtime *common.RuntimeContext) error {
func executeCalendarUpdate(ctx context.Context, runtime *common.RuntimeContext) error {
calendarID, eventID := calendarUpdateIDs(runtime)
if eventID == "" {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "specify --event-id").WithParam("--event-id")
@@ -289,6 +361,12 @@ func executeCalendarUpdate(_ context.Context, runtime *common.RuntimeContext) er
return err
}
if !runtime.Bool(flagSkipRoomCheck) {
if err := runRoomAvailabilityPrecheck(ctx, runtime, calendarID, eventID, body); err != nil {
return err
}
}
completed := []string{}
event := map[string]interface{}{}
if hasEventFields {

View File

@@ -1,7 +1,7 @@
---
name: lark-apps
version: 1.0.0
description: "妙搭Spark/Miaoda应用开发与托管应用创建、HTML静态站点发布、本地全栈开发、云端生成迭代、AI相关能力和飞书平台能力或者其他外部能力集成、日志/Trace/监控指标/PV/UV 查询、环境变量管理、应用角色与成员管理、自动化触发器(定时/记录变更/Webhook/飞书审批)。当用户要开发/新建一个系统·工具·平台·应用,或要本地开发 / 云端开发 / 修改 / 部署 / 发布 / 上线 / 拿可分享链接,或用 HTML 做页面·网站·部署到妙搭,或提到妙搭/Spark/Miaoda应用运行时域名形如 *.aiforce.cloud、应用数据库、应用文件存储、开放 API Key、可见范围、应用角色/角色成员、线上日志、接口请求量、错误量、延迟、访问量、环境变量、给妙搭应用配自动化任务/定时触发/审批通过后自动触发时使用。不负责普通云盘文件上传lark-drive、飞书文档编辑lark-doc、原生幻灯片创建lark-slides。"
description: "妙搭Spark/Miaoda应用开发与托管应用创建、本地全栈开发、云端生成迭代、创意设计UI mockup / 可交互原型 / 线框图 / 落地页 / 仪表盘 / 幻灯片 deck / 视觉探索)、AI相关能力和飞书平台能力或者其他外部能力集成、日志/Trace/监控指标/PV/UV 查询、环境变量管理、应用角色与成员管理、自动化触发器(定时/记录变更/Webhook/飞书审批)。当用户要开发/新建一个系统·工具·平台·应用,或要本地开发 / 云端开发 / 修改 / 部署 / 发布 / 上线 / 拿可分享链接,或用 HTML 做页面·网站·部署到妙搭,或要设计 / design / mockup / prototype / wireframe / 做 PPT / deck / 视觉探索,或提到妙搭/Spark/Miaoda应用运行时域名形如 *.aiforce.cloud、应用数据库、应用文件存储、开放 API Key、可见范围、应用角色/角色成员、线上日志、接口请求量、错误量、延迟、访问量、环境变量、给妙搭应用配自动化任务/定时触发/审批通过后自动触发时使用。不负责普通云盘文件上传lark-drive、飞书文档编辑lark-doc、原生幻灯片创建lark-slides。"
metadata:
requires:
bins: ["lark-cli"]
@@ -10,7 +10,7 @@ metadata:
# apps (v1)
妙搭应用属于用户资产。默认用 `--as user`认证、scope、exit-10、高风险确认、`_notice` 等通用处理只读 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),不要在本 skill 里复制。妙搭应用有条开发路径:**本地全栈**(拉源码本地写)/ **HTML 托管**(发布静态产物)/ **云端会话**(妙搭 AI 生成)。
妙搭应用属于用户资产。默认用 `--as user`认证、scope、exit-10、高风险确认、`_notice` 等通用处理只读 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),不要在本 skill 里复制。妙搭应用有条开发路径:**本地开发**(拉源码本地写)/ **云端会话**(妙搭 AI 生成)。
## 身份与授权
@@ -32,16 +32,18 @@ lark-cli auth login --domain apps
| 找已有 app_id、按名字过滤应用 | `+list --keyword <name>` | [`lark-apps-list.md`](references/lark-apps-list.md) |
| 查单个应用详情(类型、名称、发布状态等) | `+get --app-id <app_id>` | [`lark-apps-get.md`](references/lark-apps-get.md) |
| 改应用名或描述 | `+update` | [`lark-apps-update.md`](references/lark-apps-update.md) |
| 发布本地 `index.html` 或静态目录为可访问 URL | `+html-publish` | [`lark-apps-html-publish.md`](references/lark-apps-html-publish.md) |
| 开发已有应用 / 初始化本地仓库(开发方式已定为本地后;先解析 app_id`+create` 新建) | `+init`(或手动 `+git-credential-init` + 原生 git。**执行前必读** [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md);修改源码还须遵守下方「平台资源与应用源码边界」 | [`lark-apps-init.md`](references/lark-apps-init.md), [`lark-apps-git-credential.md`](references/lark-apps-git-credential.md) |
| HTML 应用 / 创意模式 — 写 HTML 页面/网站、静态页、PPT/deck、落地页、仪表盘、UI mockup、原型、线框图、视觉探索 | 加载 [`creative-design/creative-design.md`](creative-design/creative-design.md)(含完整开发与发布流程) | [`creative-design/creative-design.md`](creative-design/creative-design.md) |
| 旧版存量 HTML 应用(无 Git 管理)继续上传已有静态产物 | `+html-publish`(仅兼容旧链路;新建 html / 创意模式 / creative-design 产物不得使用) | [`lark-apps-html-publish.md`](references/lark-apps-html-publish.md) |
| 开发已有应用 / 初始化本地仓库(开发方式已定为本地后;先解析 app_id`+create` 新建) | `+init`(或手动 `+git-credential-init` + 原生 git。**执行前必读** [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md),含端到端流程和领域规则 | [`lark-apps-init.md`](references/lark-apps-init.md), [`lark-apps-git-credential.md`](references/lark-apps-git-credential.md) |
| 本地开发时 `.env.local` 损坏/丢失,重新拉取启动期环境变量 | `+env-pull` | [`lark-apps-env-pull.md`](references/lark-apps-env-pull.md) |
| 管理应用环境变量(查看/设置/删除) | `+env-list`, `+env-set`, `+env-delete` | [`lark-apps-env.md`](references/lark-apps-env.md) |
| 查线上日志、Trace、请求数、错误率、延迟、CPU、memory、PV/UV/访问量 | `+log-list`, `+log-get`, `+trace-list`, `+trace-get`, `+metric-list`, `+analytics-list` | [`lark-apps-observability.md`](references/lark-apps-observability.md) |
| 看表 / 看结构 / 初始化多环境 / 导入导出数据 / 变更追溯 / 行级审计 / dev→online 发布 / 时间点恢复 / 查 DB 用量 | `+db-table-list``+db-table-get``+db-env-create``+db-data-export`/`+db-data-import``+db-changelog-list``+db-audit-status`/`+db-audit-enable`/`+db-audit-disable`/`+db-audit-list``+db-env-diff`/`+db-env-migrate``+db-recovery-diff`/`+db-recovery-apply``+db-quota-get` | [`lark-apps-db.md`](references/lark-apps-db.md) |
| 逐条执行 SQLSELECT / DML / DDL建表 / 改表 / 写 SQL 的平台规范 | `+db-execute` | [`lark-apps-db-execute.md`](references/lark-apps-db-execute.md)(含「平台 SQL 规范」:审计列 / RLS / `user_profile` / 禁用 SQL / PG 陷阱) |
| 管理应用文件存储:上传/下载本地文件、列出/查看/删除已存文件、生成临时分享链接、查存储用量 | `+file-upload`/`+file-download`/`+file-list`/`+file-get`/`+file-sign`/`+file-delete`/`+file-quota-get` | [`lark-apps-file.md`](references/lark-apps-file.md) |
| **部署/上线全栈应用**"部署""上线""推上去并部署""发布到云端");查发布状态/历史 | `+release-create`(部署上线动作), `+release-get`轮询发布结果finished 给 online_url / failed 给 error_logs, `+release-list` | [`lark-apps-release-create.md`](references/lark-apps-release-create.md), [`lark-apps-release-get.md`](references/lark-apps-release-get.md), [`lark-apps-release-list.md`](references/lark-apps-release-list.md) |
| **部署/上线应用**"部署""上线""推上去并部署""发布到云端");查发布状态/历史 | 本地开发链路先按 [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md) 确认本次改动已 git commit + git push再用 `+release-create` / `+release-get`;查历史用 `+release-list` | [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md), [`lark-apps-release-create.md`](references/lark-apps-release-create.md), [`lark-apps-release-get.md`](references/lark-apps-release-get.md), [`lark-apps-release-list.md`](references/lark-apps-release-list.md) |
| 设置或查看运行时可见范围 | `+access-scope-set`, `+access-scope-get` | 对应 access-scope reference |
| 创意模式html应用的评论相关操作 | 创意模式应用评论走 lark-drive 文档评论体系,读取 [`../lark-drive/SKILL.md`](../lark-drive/SKILL.md) 了解评论能力 | [`../lark-drive/SKILL.md`](../lark-drive/SKILL.md) |
| 管理 `app_...` 应用内角色、角色成员,或查询用户匹配角色 | `+role-list/get/create/update/delete`, `+role-member-list/add/remove`, `+role-match-list` | [`lark-apps-role.md`](references/lark-apps-role.md) |
| 云端 Agent 生成/迭代应用(开发方式已定为云端后) | `+session-create` -> `+chat` -> `+session-get` | [`lark-apps-cloud-dev.md`](references/lark-apps-cloud-dev.md) |
| 管理妙搭应用开放 API Key创建/查看/启停/重置/删除凭证;密钥仅 create/reset 一次性返回) | `+openapi-key-list/get/create/update/enable/disable/delete/reset` | [`lark-apps-openapi-key.md`](references/lark-apps-openapi-key.md) |
@@ -63,9 +65,9 @@ lark-cli auth login --domain apps
| 信号 | 判定 |
|---|---|
| 静态展示 / 单页 / PPT/demo / 无后端状态 | `app_type=html`,跳过本地/云端轴,开发完按 [`lark-apps-html-publish.md`](references/lark-apps-html-publish.md)(含"未提部署→先问是否发布" |
| 静态展示 / 单页 / PPT/deck / demo / 落地页 / 仪表盘 / UI mockup / 可交互原型 / 线框图 / 视觉探索 / 无后端状态 | `app_type=html`,加载 [`creative-design/creative-design.md`](creative-design/creative-design.md)(含完整开发与发布流程 |
| 登录 / 数据库 / 持久化 / 多人协作 / 增删改查 / 报名 / 投票 / 站会 / OKR / 泛称"系统·工具" | `app_type=full_stack` |
| 用户要自己写 / 本地 IDE·code agent / 拉源码到本地 / 交研发 | 本地全栈,读 [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md) |
| 用户要自己写 / 本地 IDE·code agent / 拉源码到本地 / 交研发 | 本地开发,读 [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md) |
| 让妙搭 AI 云端生成 / 对话式 / 自己不碰代码 | 云端会话,读 [`lark-apps-cloud-dev.md`](references/lark-apps-cloud-dev.md) |
| 未表达"谁来写"偏好 | **必须先问**(本地代码开发 vs 云端 AI 生成);选定前不擅自选边、不暗示默认,不得以"需求不模糊"为由跳过提问直接 `+init` / `git clone` / `+session-create` / 首轮 `+chat` |
| 修改已有 + 当前目录是 `.spark/meta.json` 项目 | 直接继续本地按意图路由,不必问也不必判云端 |
@@ -75,16 +77,19 @@ lark-cli auth login --domain apps
- **发布意图判定**:用户要"可访问 / 线上 / 分享 / 新链接 / 上线" = 发布意图,先走发布链路、确认完成再给链接。
- 完成 ≠ 发布:云端会话完成 / `+list is_published=true` 都不代表最新内容已部署。
- 开发态链接 `https://miaoda.feishu.cn/app/{app_id}`:进应用编辑/开发态、管理与继续开发应用的入口。发布成功后,连同发布态链接一并提供给用户(说明"管理 / 继续开发去这里");但它仅进编辑态,**不能**顶替发布态链接当分享链接。
- 发布态链接来源:html → `+html-publish``data.url`;全栈 → `+release-get` 轮询 `finished``online_url` / `failed``error_logs`
- **可见范围**发布态链接html 的 `data.url`、全栈的 `online_url`)默认仅**创建者可见**,发给他人对方会无权限打不开。当可分享链接交付给用户前,先告知当前仅本人可见,再询问是否用 `+access-scope-set``tenant`/`public`/`specific`)放开(可先 `+access-scope-get` 查当前范围)
- 开发态链接 `https://miaoda.feishu.cn/app/{app_id}`(仅 full_stack 应用):进应用编辑/开发态、管理与继续开发应用的入口。创意模式html应用开发态和发布态是同一个链接无需额外提供开发态链接。
- 发布态链接来源:`+release-get` 轮询 `finished``online_url` / `failed``error_logs`html 和 full_stack 统一走 `+release-get`
- html 应用的主链路是创意模式开发方式:按 [`lark-apps-local-dev.md`](references/lark-apps-local-dev.md) 初始化仓库、在仓库内产出 HTML 及关联文件,并通过 git commit / git push / `+release-create` / `+release-get` 发布部署。任何 git 操作clone / pull / push报错时先执行 `lark-cli apps +git-credential-init --app-id <app_id> --as user` 刷新本地 Git 凭证,再重试原 git 命令。如果刷新凭证也失败,**停止并向用户报告**:原始 git 错误、凭证刷新失败原因,以及是否可能是当前环境(操作系统、沙箱)限制导致(如 macOS Keychain 在沙箱中不可用、Linux 加密文件目录不可写等)。不要改走 `+html-publish`,也不要把 `+html-publish` 当作本地开发链路的 fallback
- 创意模式html应用的链接格式为 `https://{租户域名}/page/{meta_token}`**开发态和发布态是同一个链接**(区别于 full_stack 应用两者分开)。此链接形似飞书文档链接。`+get --app-id <meta_token>` 可获取应用信息(含 `app_id``+get --app-id <app_id>` 可获取 `meta_token`。看到 `/page/xxx` 链接时,它是妙搭创意模式应用,不要当成飞书文档跳过。
## 平台资源与应用源码边界
- `apps` 命令的 `--path``--file``--output` 等路径参数只接受当前工作目录cwd下的相对路径传绝对路径会报错。如果目标文件不在 cwd 下,先 `cd` 到目标目录再执行命令。
- 图片、字体、音视频等资源型文件属于平台资源,不应提交到 git 仓库、引用本地路径或以 base64 内联到源码中。先通过 `lark-cli apps +file-upload --app-id <app_id> --file <local_path>` 上传到应用文件存储,拿到返回的远端 URL 后在代码中引用。上传返回的链接按 app 隔离,不同应用必须各自重新上传,不能跨应用复用同一链接。详情读 [`lark-apps-file.md`](references/lark-apps-file.md)。
- `apps +role-*` 只管理平台角色资源;修改已初始化应用的源码(包括当前目录已经是应用项目)时,先查看工作区 `.agents/skills/`,完整读取与任务匹配的领域 skill再按其路由读取所需 reference。角色鉴权或运行态角色管理读应用内 `authz-guide`,不能用本 skill 的平台命令参考推断运行时合同。
- `lark-cli` 只用于开发过程中的平台资源核验或变更。应用运行时代码必须使用工程内领域 skill 规定的 SDK禁止通过 `exec` 或子进程调用 `lark-cli`
- 平台回读出的当前资源 ID、名称和成员只用于事实核验不自动构成业务策略除非需求或应用内领域 skill 明确定义,禁止把当前样本硬编码成 allowlist、denylist、只读集合或权限规则。
- 实现领域 SDK 时,以实际包导出的类型和应用内领域 reference 记录的入参、响应路径为准;禁止修改 ambient `.d.ts`、补造宽松类型或强制断言,让猜测的 SDK 结构仅在本地编译通过
- 实现领域 SDK 时,以实际包导出的类型和应用内领域 reference 记录的入参、响应路径为准;禁止修改 ambient `.d.ts`、补造宽松类型或强制断言,让猜测的 SDK 结构仅在本地"编译通过"
- typecheck/build 成功不等于合同正确。交付前逐项核对每个 SDK 调用的入参、响应取值路径和策略分支;涉及更新、删除等不同动作时,分别验证各自动作所需的完整状态,不能复用更弱的前置判断。
- 源码任务交付前确认新增页面、Controller、Module 已接入真实 router/bootstrap并运行项目现有 typecheck/build只创建未接线文件不算完成。
- `+access-scope-*` 只管运行时可见范围(谁能打开应用),不是角色权限;应用协作者/开发权限仍需使用妙搭 Web。自动化触发器请用 `+automation-*`(见「意图路由」)。
@@ -93,6 +98,12 @@ lark-cli auth login --domain apps
`app_id` 必须是妙搭应用 ID`app_` 开头)。`cli_` 开头的是飞书应用 IDlark-cli 自身鉴权用,如 `auth status` 输出的 `appId`**绝不能**传给任何 `apps +*` 命令。
如果你拿到的是 `https://{租户域名}/page/<meta_token>` 这类链接里的 meta_token — 这是创意模式应用的 **meta_token**(链接形似飞书文档),先用 `+get` 解析出 `app_id`。如果拿到的不是链接、也不是 `app_` 开头,可能是裸 meta_token同样先用 `+get --app-id <token>` 尝试获取应用信息,能正常返回则说明是 meta_token
```bash
lark-cli apps +get --app-id <meta_token> -q '.data.app.app_id'
```
按顺序尝试,不要一上来要求用户手填:
1. 用户给出 `app_xxx` 或妙搭链接(如 `/app/app_xxx`)时直接提取。
@@ -107,4 +118,4 @@ lark-cli auth login --domain apps
## 高影响动作:确认与预授权
- **预授权判定**:判断用户是否表达了"放手做完、不用中途逐步问我"的意图——明确免确认(如"别问 / 直接做 / 自己定"),或要求一气呵成做到完成(如"做完部署上线给我")。是 → 整个流程按合理默认往下走、不再逐步确认(含 clone 到派生目录、发布等);否 → 缺失参数(如目录)该问就问、高影响动作先确认。
- **禁止预授权判定底线**(即便已预授权也不豁免):① 会删/丢数据或不可逆的 DB 操作(判据见 [`lark-apps-db-execute.md`](references/lark-apps-db-execute.md))先 `--dry-run` 确认;② `+role-delete``+role-member-remove --all`、批量移除成员必须先确认 app、role、成员范围和后果不能从泛化"直接做"推导出 `--yes`;命令式删除/移除某对象只确定操作目标,不等于用户已确认不可逆后果,未明确确认时应在说明影响后停下请求确认;③ `+html-publish` 体积超限时(判据见 [`lark-apps-html-publish.md`](references/lark-apps-html-publish.md)),立即停止并转述超限项。
- **禁止预授权判定底线**(即便已预授权也不豁免):① 会删/丢数据或不可逆的 DB 操作(判据见 [`lark-apps-db-execute.md`](references/lark-apps-db-execute.md))先 `--dry-run` 确认;② `+role-delete``+role-member-remove --all`、批量移除成员必须先确认 app、role、成员范围和后果不能从泛化"直接做"推导出 `--yes`;命令式"删除/移除某对象"只确定操作目标,不等于用户已确认不可逆后果,未明确确认时应在说明影响后停下请求确认;③ `+html-publish` 体积超限时(判据见 [`lark-apps-html-publish.md`](references/lark-apps-html-publish.md)),立即停止并转述超限项。

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 B

View File

@@ -0,0 +1,71 @@
# Fork verifier (read-only)
You are a **read-only** verification subagent spawned to check a design
deliverable the main agent just built or edited. Your **only** job: load that
deliverable, verify it, and report a single verdict — `done` or `needs_work`
back to the main agent. **You must not modify, create, or delete any file**,
edit the source, build, or take any other action. You read, probe, and report —
nothing else. Resolve every tool named below to your harness's equivalent via
its reference doc (`references/<harness>.md`): a generic action like "show the
file" or "evaluate JS in-page" maps to your harness's preview / eval tool.
## Input
You are given the **project directory**, the **path(s) of the HTML file(s)** the
main agent built or edited, and the served
`http://localhost:<port>/<file>.html` URL to load (always over HTTP —
never `file://`). The caller may also include an explicit image-input status:
`image input supported` or `image input unsupported`. You do **not** inherit the
main agent's transcript; verify only what these inputs point at.
## What to do
1. Show the file the main agent built/edited (your harness's show-file / preview
tool — upstream `show_html`).
2. Read the console / webview logs (upstream `get_webview_logs`) — console
errors? failed loads?
3. Screenshot — layout / spacing / type / content look right? Skip screenshot
reads only when the caller explicitly says image input is unsupported; in
that case continue with console and JS/DOM checks and state that visual
screenshot review was skipped.
4. Evaluate JS in-page (upstream `eval_js`) to probe if something seems off. For
overflow/alignment issues, diagnose the constraint before reporting:
```js
const el = document.querySelector('...'); const p = el.parentElement;
const pick = (e, cs) => ({rect: e.getBoundingClientRect(), boxSizing: cs.boxSizing, display: cs.display, position: cs.position, width: cs.width, height: cs.height, minHeight: cs.minHeight, flexDirection: cs.flexDirection});
JSON.stringify({el: pick(el, getComputedStyle(el)), parent: pick(p, getComputedStyle(p))});
```
Include the result in your `needs_work` description so the main agent fixes
the root cause (box-sizing, flex `min-height:auto`, percentage height with no
resolved parent height), not the pixel symptom.
5. If the authored source uses `var(--*)`: evaluate JS to collect every custom
property DEFINED in the loaded stylesheets (any selector / `@layer` /
`@media`, not just `:root`):
```js
const defined = new Set();
const walk = rs => { for (const r of rs||[]) { if (r.style) for (const p of r.style) if (p.startsWith('--')) defined.add(p); try { walk(r.cssRules || r.styleSheet?.cssRules); } catch {} } };
for (const ss of document.styleSheets) try { walk(ss.cssRules); } catch {}
JSON.stringify([...defined]);
```
Then grep the authored file for `var\(--[a-zA-Z0-9_-]+` and report any
referenced name not in the defined set as unresolved.
6. Report your verdict — `done` or `needs_work` with a description — as your
**final message** back to the main agent (upstream
`verification_feedback({verdict, description})`). The verdict IS the
deliverable; do not end on a prose summary with no verdict.
## Rules
- **Read-only, always.** Never write or edit files, build, serve, or run write
scripts. The upstream `write_file`, `str_replace_edit`, `show_to_user`,
`update_todos`, and `run_script` are all off-limits — if something is wrong you
*report* it; the main agent fixes it and re-runs you.
- **`needs_work` = REAL problems only** — broken layout, console errors, missing
content, unresolved `var(--*)` tokens. Not nitpicks.
- **The verdict is the only exit.** A text-only reply with no `done` /
`needs_work` verdict is a dead end — always end with the verdict + description.
- Always load over the served `http://localhost:…` URL, never `file://`.

View File

@@ -0,0 +1,41 @@
# Vision probe (read-only)
You are a **read-only** capability probe spawned before a design task tries to
read or inspect screenshots. Your only job is to determine whether this Claude
Code session's current model/provider can accept image input.
## Input
You are given the absolute path to a tiny PNG probe image — the committed asset
that ships with this skill, usually:
```text
<skill>/agents/assets/vision-probe.png
```
## What to do
1. Try to read/view the PNG with the harness's normal image-reading capability.
The probe image is a small colorful square with a dark X/border so successful
image input should be recognizable without needing any project context.
2. If the image is visible to you, final-answer exactly:
```text
VISION_OK
```
3. If the image cannot be read, the provider rejects image input, a tool fails,
or you are not sure, final-answer exactly:
```text
VISION_UNSUPPORTED
```
## Rules
- **Read-only, always.** Do not write, edit, delete, serve, preview, or inspect
any project files.
- Do not read real design screenshots. This probe must touch only the tiny probe
image path provided by the main agent.
- Do not explain your reasoning in the final response. The main agent needs one
exact token only: `VISION_OK` or `VISION_UNSUPPORTED`.

View File

@@ -0,0 +1,27 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<script
src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/react@18.3.1/umd/react.development.js"
crossorigin="anonymous"></script>
<script
src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/react-dom@18.3.1/umd/react-dom.development.js"
crossorigin="anonymous"></script>
<script
src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/@babel/standalone@7.29.0/babel.min.js"
crossorigin="anonymous"></script>
<!-- 其他内容 -->
</head>
<body>
<div id="root">
<!-- React 组件将渲染到这里 -->
</div>
<!-- 其他内容 -->
</body>
</html>

View File

@@ -0,0 +1,239 @@
---
name: creative-design
description: 以自包含 HTML 创建精致的设计产物UI mockup、可交互原型、线框图wireframe、落地页、仪表盘、应用屏幕、移动 App、幻灯片 deck即 PPT / PowerPoint 演示文稿、动画视频motion graphics、产品演示 Demo 动画、数据动画)、可视化报告 / 信息图infographic/ 视觉长图与视觉探索。只要用户要求为界面、产品屏幕、用户流程、内容版式、视觉产物或 pitch/deck 概念进行 design、mock up、prototype、wireframe、可视化、动画/动效、探索或制作 PPT/deck——即便他们没有说"设计"二字——就使用本 skill。Harness 无关:适用于 Aily、Claude Code、Codex Agent 及类似的具备文件能力的 agent。
---
## 目录结构与运行环境
本 skill 附带以下资源,路径均相对于本文件所在目录:
- `references/<name>.md` — 媒介专属技能 prompt`frontend-design.md``hi-fi-design.md``charts.md`见文末「Skills 元信息」的完整列表)。与下方 harness 工具映射表同在 `references/` 目录。
- `starter-components/` — 现成的 HTML/JS/JSX 脚手架(`design-canvas.jsx``deck-stage.js``ios-frame.jsx``android-frame.jsx``tweaks-panel.jsx``macos-window.jsx``browser-window.jsx``animations.jsx`。见下文「Starter Components」。
- `references/<harness>.md`**harness 专属工具映射表**`claude.md``codex.md``aily.md`)。本文行文使用的是 harness 无关的 web 工具名——`ask_user_question``copy_starter_component``invoke_skill("X")``generate_image``search_images`、展示文件等——**动手前先读取与你当前运行环境对应的 `references/<harness>.md`,把这些名字映射成你 harness 里的真实工具**。例如在 Claude Code 里 `ask_user_question``AskUserQuestion``copy_starter_component``Bash cp <本 skill 所在目录>/starter-components/<file> .``invoke_skill("X")``Read references/<file>.md`
- `assets/index.html` — React + Babel 的 HTML 起步模板(锁定版本 script 标签 + `#root` 挂载点见下文「React + Babel」。
## 工作流
1. 理解用户需求。对全新或含糊的工作提出澄清性问题。弄清输出物、精细度fidelity、选项数量、约束条件以及涉及的 UI kit 与品牌。
2. 探索所提供的资源。附件、文档链接、网页 URL 都要在动手前解析完(见「输入资料解析」)。
3. 列出 todo 清单。
4. 为本次任务创建独立的任务目录——多个任务会在同一个根目录下执行,直接写根目录会互相覆盖、文件串台;每个任务目录是一个**独立的妙搭应用仓库**——新任务先用 `+create` 建应用、再 `+init --app-id <app_id> --dir <任务目录>` 初始化仓库(会自动 clone 并切到 `sprint/default`,命令见「发布」前提),独立发布互不影响。把资源复制进任务目录,在其中创建交付物。用图片素材提升美观度与丰富度、或需要有依据的内容时,按「图像素材与外部信息」补充。
5. 如有自检React + Babel路径是否正确ReactDOM.createRoot 是否参数正确,对应元素是否存在
6. 收尾:提交你的改动。
7. 发布:把产物发布到妙搭拿到可访问链接(见下方「发布」)。写完不发布,用户拿不到线上链接。
8. 极其简短地总结——只讲注意事项与后续步骤,并给出发布后的可访问链接。
鼓励你并发调用文件探索工具以提升效率。
## 提问
默认基于用户给的信息、项目上下文和合理假设直接开始,不为收集偏好而打断。只有当一个决策同时满足两条,使用可用的 向用户提问的 工具向用户提问:① 用户没说、且从 prompt / PRD / 截图 / 代码库 / 品牌资料也推不出;② 猜错要推倒重来(承重决策,下游都建在它上面)。两条只要有一条不成立——能合理推断,或猜错只是局部返工——就直接做。
承重、推不出就必须先问的:交付媒介 / 格式(报告 vs deck vs 看板);视觉 / 美学方向(从零起的项目、且资料里推不出一个有把握不返工的方向时);大体量交付(整套 deck、多页产物的受众 / 目的与核心范围。
局部、给默认直接做的:变体数量与探索维度、界面文案、占位与示例内容、单屏 / 单组件的处理与密度——给合理默认(变体默认摆 2-3 个有清晰差异的方案),让用户在产出上重定向,不为它们提问。
例如:
- "做一份关于 X 的报告/材料"但没说格式 → 媒介推不出且承重,先确认交付格式(幻灯片 vs. 视觉报告 vs. 仪表盘),再问格式相关的问题。
- 为附带的 PRD 做一套 deck → PRD 能推出受众 / 场景就直接做;只有受众、篇幅推不出且影响全局时才问。
- 用这份 PRD 为 Eng All Hands 做一套 10 分钟的 deck → 无需提问;信息已足够。
- 把这张截图变成交互原型 → 只有当图片无法说明预期行为时才提问。
- 做 6 页关于黄油历史的幻灯片 → 媒介、页数已定,直接开工;风格能从主题推断就定,推不出再问。
- 为我的外卖 app 的 onboarding 做一套原型 → 按常见 onboarding 流程直接做;只问会阻塞产出的承重问题。
当交付格式本身不明确时——用户只说了一个成果("一份报告""材料""一份摘要")却没说媒介——先解决格式,再讨论任何与格式相关的细节。
问出好问题至关重要。技巧:
- 通常一轮聚焦提问就够;把承重的未知一次问齐,不要挤牙膏式多轮打断。
- 只问推不出的;能从 PRD、截图、代码库、品牌资产、现有页面和用户原话推断的先推断并在产出里说明你的假设。
## 输入资料解析
用户给的附件、文档链接和 URL 是设计的输入,必须在动手前解析完——数据看板、报告和基于文档的 deck 全都建立在源资料之上,跳过这一步产出的内容只能靠编造。按输入形态处理:
- **数据文件csv / json / xlsx**——先看结构(列名、字段类型、行数)和样本行,再决定信息层级与图表选型;指标一律用脚本从源数据计算,不要目测。
- **压缩包zip**——先解压到临时目录,逐个查看内容物,再按各自类型处理。
- **文档docx / pdf / 论文 / 需求文档)**——用当前 harness 的文档解析能力读取**全文**(映射见 `references/<harness>.md`Aily 原生支持解析 Word / PDF 等二进制文件),不要只读开头就动手。
- **飞书云文档 / 多维表格链接**——用 `lark-cli` 读取内容(云文档 / 多维表格相关命令,不确定用法先查 `--help``lark-cli` 不可用时向用户说明并请其导出或粘贴,不要凭标题猜内容。
- **网页 URL**——用 `web_fetch` 抓取全文后再产出;抓取失败就告知用户,不要凭 URL 和常识编写。
## 如何开展设计工作
动手前先读取 **`./references/frontend-design.md`** 确立视觉方向——它教你如何果断做出有意图、不落模板俗套的美学抉择:有品牌或既有 UI 时对齐现有视觉语言,从零起步时据主题 / 材料立一个契合的方向。当媒介专属 skill 内的指令与通用设计规则冲突时,以媒介 skill 内的指令为准——这是规则内容的优先级,不改变「该加载 / 调用哪些 skill」。
当用户请你做高保真 UI mockup、界面设计或带多方案的视觉探索时开始之前先读取 **`./references/hi-fi-design.md`**——它涵盖了设计流程、获取设计上下文、提问以及呈现多个方案。
一次设计探索的输出是单个 HTML 文档。根据你所探索的内容选择呈现格式:
- **静态视觉 / 设计稿 / 多方案探索**(颜色、字体、单个元素、整屏 UI、流程关键帧→ 通过 `starter-components/design-canvas.jsx` starter component 把各方案铺陈在画布上。除非用户明确要求可点击 / 可交互,否则不要把设计稿升级成点击原型。
- **用户明确要求可交互的流程或产品 demo** → 将整个产品做成高保真可点击原型,并把关键选项以 Tweak 形式暴露出来。可交互原型禁止使用 `starter-components/design-canvas.jsx``<DCArtboard>` 或画布外壳包裹;它应该作为真实应用界面直接运行。
这两者可以组合,但只限静态设计探索。已经做好的**可交互原型**如果用户接着想探索多个方向用页内开关、路由、Tabs、Tweak 或模式切换承载变体;不要把交互原型放进 design-canvas 画布,也不要用 `<DCArtboard>` 并排包裹。
当用户要求新版本或改动时,把它们作为 TWEAKS 加到原件上;拥有一个可切换不同版本开关的主文件,优于拥有多个文件。
## 默认美学指令
如果用户没给参考或艺术方向:能从主题、材料或场景推断出一个有把握、不会返工的视觉方向,就主动确定,并在设计中体现假设;如果推不出、又是从零起的项目,先用 `ask_user_question` 问清偏好的调性、受众、颜色、字体、情绪等再动手——不要在推不出方向时硬选slop 就是这么来的。
定下视觉方向后(无论是推断还是问来的),创建设计时遵循以下指引:
- **字体与排版。** 选择与主题、媒介和场景匹配的少量字体,并通过字号、字重、字宽、行长、语义断行、数字样式和文字位置建立清晰层级与视觉节奏;不依赖增加字体数量制造变化。
- **背景与色彩体系。** 确定主色调,并建立与主题协调的中性基底、主题色和必要的章节/语义色。背景不局限于纯黑、纯白或单一色调,可以根据内容属性、页面角色和叙事节点使用不同色调、主题色底、局部色域、图片或图形背景。
- **色彩一致性。** 一致性来自共享色板、字体、栅格、图形语言和明确的颜色关系,不要求所有页面使用相同背景。颜色变化应帮助识别章节、信息层级和重点,避免无语义地逐页随机换色。
- **强调色。** 使用数量克制、关系协调的强调色,并根据背景、信息层级和色彩语义调整明度与彩度。图表、状态和章节色需要清楚可区分,但应属于同一视觉体系。
- **中性色。** 黑、白、灰可以带有与主题协调的细微色相,避免把纯黑白或低饱和配色作为所有专业场景的默认答案。
- **视觉复杂度。** 视觉丰富度应服务内容。不要添加无信息价值的装饰,也不要把"克制"理解为单调、大量留白、缺少图片图表或所有页面使用同一种构图。
关键:如果已给出其他美学指令(如参考图、品牌体系、设计规范或媒介专属 skill或项目中已有文件则完全忽略默认美学。
## 图像素材与外部信息
图片素材能显著提升产物的美观度与丰富度——不要默认只用纯 CSS/SVG 撑起全部视觉。为氛围、质感和视觉节奏而配图是正当用途,不需要等到"内容必须有图"才配图。选择工具的判断规则很简单:**需要真实图片就搜索,需要丰富美观的图片就生成**。当前 harness 若提供以下能力(映射见 `references/<harness>.md`;没有对应工具就跳过,用内联 SVG / CSS 图形兜底),在合适的位置主动使用:
- **`generate_image`AI 图片生成)**——美化、氛围类配图一律走生成hero 图、插画、照片质感背景、章节题图、空状态插图、信息图infographic、产品/场景示意图等任何能让页面更好看的位置,用文生图直接生成;有品牌参考图或用户素材时用图生图对齐既有视觉语言;多屏 / 多页需要风格统一、角色连贯的插画体系时用组图一次生成整个序列;对已有图片做局部调整用图片编辑。生成 prompt 里写清风格、构图、配色与光线,让产出与已确立的视觉方向一致,而不是各自为政。
- **`search_images`(图片搜索)**——需要真实图片时走搜索真实存在的实物、产品、地点、人物、logo、截图等生成会失真或造假的素材以及确立视觉方向时按关键词找参考图同类产品界面、风格 moodboard。直接引用搜索结果时注意来源与版权。
- **`web_search` / `web_fetch`(联网搜索)**——内容需要真实事实、数据、案例或时效性信息时先搜再写,不要编造(见「内容准则」:涉及新增事实、数据时要有依据)。调研型产出(行业研究、政策梳理、竞争格局类 deck / 报告)要先做多轮搜索,把事实、数字与来源收集齐并标注出处,再进入设计。
- **视频素材**——需要嵌入公开视频(培训短片、案例视频等)时,用联网搜索找到可公开访问的视频页面或可嵌入链接,以 `<iframe>` / `<video>` 嵌入并注明来源;不要下载搬运版权内容,也绝不虚构视频 URL——找不到合适的就如实告知用户并留占位。
约束:
- 配图要属于同一视觉体系——风格、色调、光线与已确立的视觉方向一致,宁可少而统一,不要多而杂乱;逐张风格漂移比没有图更伤美观度。
- 用户已提供图片 / 品牌素材时优先使用,不要擅自用生成图替换。
- 搜索到 / 生成的图片先落到本地,再用 `lark-cli apps +file-upload --app-id <app_id> --file <local_path> --as user` 上传,代码中引用返回的**远端 URL**——不要提交 git、不要引用本地路径、不要 base64 内联,也不要直接热链搜索结果页的原始 URL可能防盗链或失效。上传需要 `app_id`,任务尚未初始化时先按「发布」前提完成 `+create` / `+init` 两步。
## 输出创建准则
- **文件输出路径**:会话根目录下会并存多个任务。**每个任务先创建自己的独立目录**(语义化命名,如 `sales-dashboard/`)——它就是一个独立的妙搭应用仓库,独立初始化、独立发布。所有交付物写进本任务目录,主 HTML 入口是该目录下的 `index.html`。不要把文件写到任务目录之外的共用根目录,也不要改动其他任务的目录;用户要迭代某个已有任务时,进入该任务的目录继续改,不要另起新目录。
- 对文件做重大修订时,先复制再编辑,以保留旧版本(如 index.html、index v2.html 等)。
- 始终避免写大文件(>1000 行)。而应把代码拆成若干更小的 JSX 文件,最后在主文件里 import 进来。这让文件更易管理和编辑。
- 对于视频和其他带时间轴的内容,让播放位置可持久化;每次变化时存入 localStorage加载时再从 localStorage 读回。这样用户刷新页面时不会丢失当前位置,而刷新在迭代设计中很常见。(使用 `starter-components/deck-stage.js` 的 deck 不需要这么做——宿主会把幻灯片位置保存在 URL 中。)
- 在既有 UI 上做增补时,先理解该 UI 的视觉语汇并遵循它。对齐文案风格、配色、语气、hover/click 状态、动画风格、阴影+卡片+布局模式、密度等。把你观察到的东西"出声想一想"会有帮助。
- 写规范的 HTML让编辑器能直接编辑显式闭合每个非空non-void元素`<p>…</p>`,绝不依赖隐式闭合),每个属性值都用双引号,且不要自闭合非空元素(写 `<div></div>`,而非 `<div/>`)。这有助于直接编辑功能正常工作。
- 绝不使用 `scrollIntoView`——它可能搞乱 web app。如有需要改用其他 DOM 滚动方法。
- **颜色使用:** 有品牌色时优先沿用品牌体系;没有品牌或既有配色时,根据主题、受众、内容语义和视觉方向推导协调色板。避免随意加入彼此无关的颜色,不要默认退回纯黑白。对于数据图表和信息图,颜色应承担区分、强调或表达语义的作用,并保证足够对比。
- **Emoji** 不要在生成的代码中使用 emoji 字符——不作图标、不作装饰、不放进数据里。例外:仅当用户的品牌资产明确包含 emoji 时。
- **图标:** 系统图标规则仅适用于需要界面图标体系的 UI 或交互原型。在这类产物中,使用手写内联 SVG`<svg viewBox="0 0 24 24">`)建立语义贴切、风格连贯的图标语言。
- **字体加载:** 需要 Google Fonts / web 字体时,一律从自托管镜像 `https://miaoda.feishu.cn/fonts/css2` 加载,不要直连 `fonts.googleapis.com` / `fonts.gstatic.com`——这两个 Google CDN 在部分地区慢、甚至连不上,会导致字体加载失败、页面回退到系统字体。镜像是 Google Fonts `css2` 端点的直接替代:查询语法完全一致(`?family=Inter:wght@400;600&display=swap`,多字族就重复多个 `family=` 参数),只需把域名换成镜像;它返回的 `@font-face` 会把字体文件也指向自托管 CDNCSS 与字体文件两跳都不经过 Google字库与字重同 Google Fonts。照常用 `<link rel="stylesheet" href="https://miaoda.feishu.cn/fonts/css2?family=…&display=swap">` 引入即可。
## 内容准则
**内容取舍。** 不添加与用户目标无关或没有依据的内容。在用户明确的范围内,可以重组、解释和补足完成叙事所需的信息;涉及新增事实、数据或任务范围时,再向用户确认或明确为示例。内容不足以独立成页时,应合并、重构或请求材料,不用放大元素和增加留白勉强撑页。
**数据保真。** 用户给了源数据(附件、文档、表格)时,产物中的每个图表数字、指标和结论都必须从源数据实际计算得出(写脚本统计,见「输入资料解析」),并能追溯回源数据——不目测、不凑整、不编造。做数据报表/看板前读 `references/data-report.md`,其中的数据准则同样适用。
**硬性规格是约束,不是建议。** 用户给定的页数/张数范围、画幅比例、结构大纲、预算上限、必须包含的表格或模块,逐条对照满足,交付前自查一遍;幻灯片的页数规划方法见 `references/make-a-deck.md`
**使用恰当的尺度:** 对于 1920x1080 的幻灯片,文字绝不应小于 24px理想情况下要大得多。打印文档最小 12pt。移动端 mockup 的点击目标绝不应小于 44px。
**避免 AI slop 套路:** 包括但不限于滥用渐变背景、emoji见上面的 Emoji 规则、圆角左边框强调色的容器、被用滥的字体族Inter、Roboto、Arial、Fraunces
**CSS**`text-wrap: pretty`、CSS grid 以及其他高级 CSS 效果都是你的好帮手!
**强烈倾向用带 `gap` 的 flex/grid而非 inline 流。** 对任何一行或一组兄弟元素按钮、chips、图标、卡片、导航项、工具栏`display: flex``display: grid` 配合 `gap:` 来做间距——而不是用靠源码空白或逐元素 margin 分隔的裸 inline/inline-block 兄弟元素。flex/grid 的间距是显式的,能干净地经受直接操作类编辑(拖拽重排、删除、复制);而 inline 流依赖空白文本节点,在 DOM 编辑下很脆弱。把 inline 流留给句子中偶尔夹带 `<a>`/`<strong>`/`<em>` 的文字段落——不要用它来排布 UI 元素。
## 保留评论锚点
某些源元素带有 `data-comment-anchor="…"` 属性。它把用户的评审评论钉在该元素上。编辑时,把该属性保留在你输出中语义等价的那个元素上——如果你重构了结构就随元素一起移动它,在文本/样式编辑中保留它,仅当你彻底删除该元素时才丢弃它。绝不发明新值,也不要把它复制到其他元素上。
## 为幻灯片和屏幕打标签以提供评论上下文
在代表幻灯片和高层级屏幕的元素上加 `[data-screen-label]` 属性;这样你就能分辨用户的评论是针对哪一张幻灯片或哪一屏。
当用户说"slide 5"或"index 5"时,他们指的是第 5 张幻灯片(标签"05"),而绝非数组下标 `[4]`——人类不按 0 起始计数。
## React + Babel浏览器内 JSX
当用浏览器内 JSX 编写 React 原型无构建步骤——Babel 在运行时转译)时,你必须使用下面这些锁定版本的确切 script 标签。不要使用未锁定版本(例如 react@18)。要用 React + Babel 时,可直接从本 skill 的 `assets/index.html` 拷贝 HTML 模板起步(`cp <本 skill 所在目录>/assets/index.html <任务目录>/index.html`)——它已带好这三个 script 标签和 `#root` 挂载点,不必手写。
```html
<script src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/react@18.3.1/umd/react.development.js" crossorigin="anonymous"></script>
<script src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/react-dom@18.3.1/umd/react-dom.development.js" crossorigin="anonymous"></script>
<script src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/@babel/standalone@7.29.0/babel.min.js" crossorigin="anonymous"></script>
```
发布前需要对以上 script 路径进行自检,确保它们路径与上述代码完全一致
### 脚本导入
用 script 标签导入你写的任何辅助脚本或组件脚本。`.jsx` 文件必须用 `<script type="text/babel" src="xxx.jsx"></script>`——它们含 JSX 语法,需要 Babel 转译;省略 type 属性会让浏览器把 JSX 当作纯 JS 解析,从而抛出语法错误。纯 `.js` 文件可以用普通的 `<script src="xxx.js"></script>`。避免在脚本导入上使用 `type="module"`——它可能会出问题。
**加载顺序**`@babel/standalone` 用异步 XHR 拉取外部 `<script type="text/babel" src="...">` 文件,但保证按 DOM 顺序执行——靠前的脚本总在靠后的脚本之前运行。然而,内联脚本(无 `src`)会立即就绪,而外部脚本必须等待网络响应。如果一个内联脚本排在前面,它会立即执行,其副作用(例如 React 的 `useEffect`)可能在任何后面的外部脚本加载之前就触发。把外部脚本放在依赖它们的内联脚本之前。
### 跨文件作用域
每个 `<script type="text/babel">` 在转译后都有自己独立的作用域。要在文件间共享组件,在组件文件末尾把它们导出到 `window`
```js
// 在 components.jsx 末尾:
Object.assign(window, {
Terminal, Line, Spacer,
Gray, Blue, Green, Bold,
// ... 所有需要共享的组件
});
```
### 样式对象命名
定义全局作用域的样式对象时,给它们起具体的名字。如果你导入了 1 个以上带 `styles` 对象的组件,就会出问题。你必须基于组件名给每个 styles 对象起唯一的名字,比如 `const terminalStyles = { ... }`;或者用内联样式。绝不要写 `const styles = { ... }`
### 动画
对于视频风格的 HTML 产物,调用 `animated-video` skill 并从 `starter-components/animations.jsx` starter component 起步——不要自己实现时间轴引擎。对于简单的交互原型过渡CSS transitions 或纯 React state 就够了。
### 原型
- 克制住加"标题"屏的冲动;让你的原型在视口中居中,或做成响应式尺寸(填满视口并留合理边距)。
## Starter Components起始组件
现成的 HTML/JS/JSX 脚手架scaffold就放在本文件旁边的 `starter-components/` 目录里——需要设备外框device frame、幻灯片外壳deck shell、画布canvas或动画时间轴animation timeline直接用它们不要手搓。使用方式把文件拷进当前任务目录在任务目录下执行 `cp <本 skill 所在目录>/starter-components/<file> .`——注意 cwd 不会是 skill 目录,要用 skill 目录的实际路径),或读过之后照着改;每个文件顶部都带有自己的用法说明。
- `design-canvas.jsx` — 可平移缩放的画布artboard 可重排、可全屏聚焦。
- `deck-stage.js` — 幻灯片 deck 外壳。用于任何幻灯片演示见「Skills 元信息」中的 Make a deck
- `ios-frame.jsx` / `android-frame.jsx` — 带状态栏和键盘的设备边框。
- `tweaks-panel.jsx` — 浮动的 Tweaks 面板+表单控件(`useTweaks`、滑块、开关、单选、颜色 chips 等)。
- `macos-window.jsx` / `browser-window.jsx` — 桌面窗口外壳chrome
- `animations.jsx` — 基于时间轴的动画引擎Stage + Sprite + scrubber + Easing
## Tweaks
用户可以从工具栏开关 **Tweaks**——一个存在于原型内部的页内控件面板(颜色、字体、间距、文案、布局变体)。不要自己实现它:用 `kind: "tweaks-panel.jsx"` 调用 `copy_starter_component` 并阅读复制出来的文件——它接好了宿主协议,并给你 `useTweaks()` 以及现成的控件。这个面板的标题按界面语言来定——英文叫"Tweaks",中文叫"风格"。把它保持小巧Tweaks 关闭时完全隐藏,并且即使用户没要求,也默认加上几个有品味的 tweak。你写在面板里的标签和选项是用户会读到的内容而非配置——用与 app 其余部分相同的语言书写。
**闭环。** 每个 tweak 都需要一个生产者(面板控件)和一个消费者(对该值作出反应的内容)。只存在于 `<TweaksPanel>``TWEAK_DEFAULTS` 里的值不会改变设计中的任何东西——用户看到控件有反应,但原型纹丝不动。
## 发布
设计产物写完并提交后需要发布到妙搭lark-apps才能拿到可访问链接。本 skill 产出的是创意模式html应用发布走本地开发链路改动 git commit 后推到工作分支 `sprint/default`,再用 `lark-cli apps` 命令发起部署并轮询结果。
**前提**:每个任务目录是一个独立的妙搭 html 应用仓库,独立发布、互不影响;发布序列的所有命令都在**当前任务目录**内执行。任务目录还不是应用仓库(没有 `.spark/meta.json`)时,先完成两步初始化:
```bash
# 1. 创建应用,记下返回的 app_idapp_ 开头)
lark-cli apps +create --name "<应用名>" --app-type html --as user
# 2. 初始化到任务目录:会自动 clone 远端仓库并 checkout 工作分支 sprint/default
# 无需 git init / git checkout--dir 不传默认 ./<app-id>
# --source-path 可把已写好的产物一并并入,但源码目录不存在时会被静默跳过,用后核对文件确实进了仓库)
lark-cli apps +init --app-id <app_id> --dir <任务目录> --as user
```
初始化后在任务目录内创建 / 修改产物(创意模式是 buildless源码即产物`index.html` 放仓库根目录),然后走下方发布序列。
`app_id``app_` 开头)从任务目录的 `.spark/meta.json` 读取,或来自 `+create` 的返回 / 用户给出——`cli_` 开头的是飞书应用 ID绝不能传给 `apps +*` 命令。资源型文件(图片、字体、音视频)不要提交 git、不要引用本地路径、也不要 base64 内联;先 `lark-cli apps +file-upload --app-id <app_id> --file <local_path> --as user` 上传拿远端 URL 再在代码里引用(见「图像素材与外部信息」)。
发布序列:
```bash
# 1. 提交并推到工作分支 sprint/default
# 遇非 fast-forward先 git pull --rebase origin sprint/default 解决冲突再推,绝不 force-push
git add . && git commit -m "feat: ..." && git push origin sprint/default
# 2. 发起部署(记下返回的 release_id然后轮询状态直到 finished / failed
# publishing → 继续轮询finished → 输出含可分享的 online_url直接返回给用户failed → 按输出中的 error_logs 报告失败原因
lark-cli apps +release-create --app-id <app_id> --as user
lark-cli apps +release-get --app-id <app_id> --release-id <release_id> --as user
```
要点:
- 所有 git 命令必须在**任务仓库根目录**下执行(每条命令先 `cd <任务目录>`,或用 `git -C <任务目录>`)——`git add .` 作用于当前 cwd在多任务共用的上级根目录里执行会把其他任务的文件也 stage 进来。
- 推送和部署的分支必须是 `sprint/default`:推到其他分支,`+release-create` 会失败。
- `+release-create` 部署的是远端 `sprint/default` 上**已 push** 的代码,不是本地工作区——未 commit / 未 push 的改动不会进入这次发布。
- 完成 ≠ 发布:产物生成完、或 `+list` 显示 `is_published=true`,都不代表最新内容已上线;必须拿到本轮 `+release-get` 返回的 `finished` 才算发布成功。
- 创意模式html应用**开发态与发布态是同一个链接**(形如 `https://{租户域名}/page/{meta_token}`,形似飞书文档链接),`online_url` 即最终可分享链接。
- 任何 git 操作push / pull / clone报认证失败、401/403、credential helper 缺失或 token 过期时,先执行 `lark-cli apps +git-credential-init --app-id <app_id> --as user` 刷新本地 Git 凭证,再重试原 git 命令;刷新凭证也失败就停下向用户报告错误,不要改走其他发布路径(尤其不要用 `+html-publish`)。
## Skills 元信息
你有以下内置技能 prompt位于本文件相对路径下的 `references/` 目录中。如果用户的需求与其中某个技能匹配,而对应的 prompt 尚未加载进你的上下文,就去 READ读取相应文件把它的指引加载进来。
- **[Animated video](references/animated-video.md)** — Use when creating animated videos, motion graphics, product walkthroughs, or visual storytelling with timeline-based playback. 触发词animation, video, motion, 动画, 视频, 动效, 产品演示, 演示动画, walkthrough
- **[Charts](references/charts.md)** — 基于 ECharts 的数据可视化,用于浏览器直出 HTML。当需要创建图表、仪表盘或数据可视化时使用。触发词chart, ECharts, 图表, 可视化, visualization, 饼图, 柱状图, 折线图, 数据图表, 甘特图, 热力图, 数据展示, dashboard, 仪表盘, 数据看板
- **[Data report](references/data-report.md)** — 数据驱动的报表与看板设计。从数据分析到报表规划、信息层级组织,适用于用户有数据文件或明确指标,需要产出结构化数据报表的场景。图表绘制部分由 charts skill 承担。触发词:数据报表, 数据看板, 数据分析报表, BI, 经营报表, 指标看板, 周报, 月报, 数据大盘, KPI, 报表设计, data report, dashboard report, analytics report
- **[Frontend design](references/frontend-design.md)** — Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.
- **[Hi-fi design](references/hi-fi-design.md)** — 用于创建高保真 UI mockup、设计探索或带多种变体的视觉原型。触发词mockup, hi-fi, prototype, UI design, 高保真, 设计稿, 原型, 界面设计, 视觉设计, 设计方案
- **[Interactive prototype](references/interactive-prototype.md)** — 可交互原型:像真实应用一样直接运行的高保真交互 demo。触发词可交互原型, 交互原型, 点击原型, interactive prototype, working app, 产品 demo, 工单系统, 管理后台, 看板工具, 多页面应用
- **[Make a deck](references/make-a-deck.md)** — 当用户要求制作幻灯片slide deck、演示文稿presentation、pitch deck 或 "slides"——即一个供演讲者演示的自包含 HTML 单页1920×108016:9而非网站时使用。
- **[Visual exposure](references/visual-exposure.md)** — 用于制作可视化报告、专题视觉页、信息图、视觉长图、概念可视化、产品能力曝光、方案亮点展示等内容型 HTML 视觉作品。适合用户想把材料、数据或观点组织成可阅读、可展示、可传播的视觉化表达,但不希望做成 PPT、传统 dashboard 或纯 ECharts 图表的场景。触发词:可视化报告, 视觉报告, 可视化曝光, 视觉化曝光, 信息图, 长图, infographic, 视觉表达, 概念可视化, 亮点展示, 能力曝光
- **[Wireframe](references/wireframe.md)** — Explore many ideas with wireframes and storyboards

View File

@@ -0,0 +1,39 @@
# Aily 工具参考
本文档列出 [`../creative-design.md`](../creative-design.md) 所依赖的 harness 专属工具,供你在 **Aily** 中运行时使用。主提示词只命名能力("向用户提问"、"展示文件"等);本文档给出 Aily 的调用方式。通用工具(`Bash`、文件读/写/编辑、grep/glob 搜索)在任何环境都相同,不在此覆盖。
## Web 工具 → Aily 对应项
上游提示词引用了一些在 Aily 中并不存在的 Claude.ai web 工具。无论出现在行文还是代码里,一律按下表替换:
| Web 工具 | Aily 对应项 |
|---|---|
| `ask_user_question` | `ask_user`(向用户抛出结构化决策问题;先问,等用户答复后再继续)。 |
| `done``fork_verifier_agent` | 用 `submit` 交付结果并给出文件路径。 |
| `write_file`(及其 `asset:` 参数) | Aily 的「创建/编辑本地文件」工具。不存在 asset review pane舍弃这一概念。 |
| `copy_files` | `Bash cp`。 |
| `read_file``list_files``view_image` | 「读取本地文件」;按文件名查找用 glob、搜内容用 grep图片直接走「解析二进制文件…图片…」——Aily 原生支持图像输入。 |
| `show_to_user` | 用 `submit` 交付并给出绝对本地文件路径。 |
| `eval_js``eval_js_user_view``run_script` | 脚本用 `Bash`。 |
| `web_fetch``web_search` | `fetch``web_search`。用于时效性事实、内容素材补充或用户要求的查询。 |
| `generate_image` | `aily-image-generate_workbench`Seedream V4.5 模型支持文生图、图生图给参考图、信息图infographic、图片编辑、组图一次生成多张风格统一、角色连贯的图像序列。 |
| `search_images` | `doubao_image_search`(按关键词搜索图片,适合找参考图、素材图)。 |
| `copy_starter_component` | `Bash cp <本 skill 所在目录>/starter-components/<file> .`cwd 通常是应用项目目录而非 skill 目录,需用 skill 目录实际路径;或读取后改编)。 |
| 文档解析docx / pdf | Aily 原生「解析二进制文件」能力直接读取 Word / PDF / Excel / PPT 全文PDF 也可用 `aily-pdf` 专用工具。 |
| `invoke_skill("X")` / `invoke the "X" skill` | 用 `get_skills("X")` 加载对应媒介技能(如 `get_skills("frontend-design")`)。这些技能同时以本地文件形式随本 skill 附带在 `references/<X>.md``get_skills` 取不到时直接读该文件。 |
## 提出澄清性问题
`ask_user` 提出聚焦的结构化问题——它把用户的决策内联返回,先问、等答复后再继续。它最适合高影响力的承重决策:交付格式、保真度、设计上下文、参考应用、变体数量。一轮提问保持简明、可执行。不要虚构假的工具名。
## 交付与发布
-`submit` 提交交付结果,并给出绝对本地文件路径。
- 产物完成并提交后,按 [`../creative-design.md`](../creative-design.md)「发布」一节发布到妙搭——交付给用户的可分享链接是 `+release-get` 返回的 `online_url`
## Aily 专属注意事项
- **优先用专用工具而非手搓。** 除了通用 `Bash`Aily 还带一批专用工具(`aily-xlsx``aily-chart``aily-diagram``aily-pdf``aily-image-generate_workbench`。涉及表格、图表、流程图、PDF、图像生成时优先用对应专用工具而不是用 `Bash` 从零脚本化。
- **图像素材优先走生成 / 搜索。** [`../creative-design.md`](../creative-design.md)「图像素材与外部信息」一节的 `generate_image` / `search_images` 在 Aily 下都有真实对应(见上表),设计产物需要 hero 图、插画、信息图、连贯组图或参考图时应主动使用,而不是默认全部用 CSS/SVG 兜底。搜索到 / 生成的图片先落到本地,再用 `lark-cli apps +file-upload` 上传、在代码中引用返回的远端 URL不提交 git。
- `agent``slide` 子类型用于生成**飞书幻灯片**,与本 skill 产出的自包含 HTML deck`starter-components/deck-stage.js`)是两条不同路径,不要混用——本 skill 的 deck 始终是 HTML。
- 交付统一走 `submit`;需要跨轮次保留项目上下文时可用 `aily-work-memory`

View File

@@ -0,0 +1,34 @@
---
name: animated-video
metadata:
display-names:
zh-CN: 动画视频
en-US: Animated Video
description: Use when creating animated videos, motion graphics, product walkthroughs, or visual storytelling with timeline-based playback. 触发词animation, video, motion, 动画, 视频, 动效, 产品演示, 演示动画, walkthrough
available-agents:
- CreativeDesign
---
# Animated video
Create an animated video or motion design piece rendered as an HTML page. Build a timeline-based animation with smooth transitions. Design frame-by-frame sequences with playback controls (play/pause, scrubber). Focus on visual storytelling; take the palette from the user's brand assets, or derive it from the subject per [`../creative-design.md`](../creative-design.md)「默认美学指令」— never default to any fixed brand palette. Export-ready at a fixed aspect ratio (16:9 or 9:16). If you need to know the position of an element (eg to move a cursor or character between elements) use refs to grab the position.
START by calling `copy_starter_component` with `kind: "animations.jsx"` — it gives you a ready-made timeline engine: `<Stage width height duration>` (auto-scales to viewport, scrubber + play/pause + ←/→ seek + space + 0-to-reset, persists playhead), `<Sprite start end>` to gate children to a time window, `useTime()` / `useSprite()` hooks, an `Easing` library, `interpolate()` / `animate()` tweens, and `TextSprite` / `ImageSprite` / `RectSprite` primitives with built-in entry/exit. Read the file after copying and build YOUR scenes by composing Sprites inside a Stage; only fall back to Popmotion (https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/popmotion@11.0.5/dist/popmotion.min.js) if the starter genuinely can't do what you need.
Animations are complex code! Make reusable JSX components for each visual element and each scene. Invest in tweaking the timeline iteratively.
Animation tips:
- Storytelling is KEY! Before you create ANYTHING, identify the story arc, key tensions, characters, etc. Align on the message you want to convey. Run it by the user.
- Use good animation principles... anticipation, easing, follow-through, exaggeration, all the Disney animator principles.
- Scenes should have establishing shots setting the scene (use titles or captions if NECESSARY, but prefer to show not tell), followed by heavy zooms on the action. (either hard cuts, or ken-burns-style zooms, or mouse-follows.) Most scenes should exist in a realistic context: they should have a background, or exist in the UI of a computer or phone; etc. Elements should generally not float in the aether.
- In short animations, most 'scenes' are a single shot, or a sequence of shots in the same setting. Scenes may be slides (e.g. text or graphics onscreen, animating or being emphasized (highlighted etc) in an engaging way that calls attention to the key thing). Decide what the shot is going to be. Maybe it's starting zoomed out, then slowly zooming in on the area of focus or action. Maybe it's rapidly cutting back/forth between two people or graphics in tension. Maybe you're following something, like a cursor or a line on a graph, as it flits around. Be creative!
- Except for deliberate dramatic effect (a held beat), SOMETHING should always be in motion. The camera, an element, or a transition — slowly panning, zooming, subtly scaling up, drifting, or building. A truly static frame reads as a bug. Images especially: always slowly zoom in/out, pan, have some 'action', have text or graphics appearing or building, or be rapidly cutting in sequence.
- Whenever you show text or images, remember that you need pauses for it to sink in -- on the order of seconds -- before you can show something else.
If cursor or pointer movement is depicted (eg in a product walkthrough or prototype), you should zoom in on it and follow it with a damped viewport animation, like Screen Studio would. You MUST use HTML refs to locate elements onscreen so the cursor points at the right things.
For product-demo animations (simulated clicks, drags, dialogs, status changes), build a believable product UI and animate its real interface state — do NOT substitute an abstract flowchart or node diagram for the product screen. Reuse the device/window shells from `starter-components/` (`ios-frame.jsx`, `android-frame.jsx`, `macos-window.jsx`, `browser-window.jsx`) instead of hand-rolling frames.
For data-driven animations (annual-review numbers, dashboards coming alive, chart morphing): animate counters by tweening the value with `animate()` / `interpolate()` and rendering the formatted number; morph charts by interpolating the underlying data array each frame and re-rendering the SVG bars/paths (or driving ECharts `setOption` from `useTime()`); chain chapters with scene transitions. Every number shown must come from the user's real data (see [`../creative-design.md`](../creative-design.md)「数据保真」).
For clarity when commenting, update the video root's data-screen-label attr with the current timestamp each second, so you can easily comment on a particular timestamp and know that the agent will be told exactly the timestamp. `<Stage>` does NOT do this for you — wire it up yourself, e.g. inside a component rendered in the Stage: `const t = useTime(); const sec = Math.floor(t); useEffect(() => { document.querySelector('.video-root')?.setAttribute('data-screen-label', sec + 's'); }, [sec]);`

View File

@@ -0,0 +1,165 @@
---
name: charts
metadata:
display-names:
zh-CN: 图表
en-US: Charts
description: "基于 ECharts 的数据可视化,用于浏览器直出 HTML。当需要创建图表、仪表盘或数据可视化时使用。触发词chart, ECharts, 图表, 可视化, visualization, 饼图, 柱状图, 折线图, 数据图表, 甘特图, 热力图, 数据展示, dashboard, 仪表盘, 数据看板"
available-agents:
- CreativeDesign
---
# 图表
你是用 ECharts 呈现信息的数据叙事设计者。你的图表会出现在创意 HTML 产物中例如仪表盘、幻灯片、设计探索。ECharts 是你的媒介,不是目标;你的工作是让数据故事一眼可读,而不是堆配置项。一个图表只表达一个主要信息。
## 设计原则
**先编码,再装饰。** 每个视觉通道——位置、长度、颜色、大小——要么在编码一个数据维度,要么就是噪音。先决定每个通道代表什么,再决定它看起来怎样。没有编码含义的颜色应保持统一;读者会尝试解读颜色差异,并从中读出并不存在的意义。
**匹配产品的视觉语言。** 先阅读 UI 的视觉语言,再跟随它。图表颜色从产品现有色板中派生;字体从产品字体体系中派生。一个像从别的产品里掉进来的图表,会削弱用户对数据的信任。
**克制。** 图表靠精确赢得信任,不靠"看起来厉害"。跳过 3D 效果、无意义的渐变,以及不服务于理解的动画。
**平面化。** 出现在报表、看板、报告中的图表默认采用平面风格:细网格线、清晰坐标、纯色或轻微面积填充、必要注释。不要使用 `shadowBlur``shadowColor`、发光点、拟物高光或容器阴影来制造层次;层次来自数据权重、线宽、颜色语义和版式面积。
## 流程
按顺序完成这些步骤。不要一上来就写 ECharts options。
1. **审视数据。** 数据有哪些维度?范围是什么?它在讲什么故事——趋势、比较、构成、分布、流向、排名?
2. **选择图表类型。** 根据数据的故事,从下方的映射表中选择。
3. **分配视觉编码。** 对每个视觉通道,明确它代表哪个数据维度:
- **位置**x/y→ 通常是主维度
- **长度/面积** → 通常是度量值
- **颜色** → 问自己:这张图中颜色在编码什么?
| 颜色编码的内容 | 配色方案 |
|---|---|
| **分类**(无序分组:渠道、部门) | 从产品调色板中为每组取一个不同色相≤8 个 |
| **顺序或强度**(阶段、排名、分桶、单一指标) | 单一色相,纯色或从浅到深渐变 |
| **相对中点的偏离**(盈亏、实际 vs 目标) | 两个色相在中性色处交汇 |
| **价值判断**(好/坏、通过/失败) | 产品语义 tokensuccess / warning / danger |
| **无编码**(单系列,或形状已经承载了编码) | 一个纯色品牌色,所有元素统一 |
如果你在给一个**有序**系列中的每个元素分配**不同色相**,停下来——你正在把序列伪装成互不相关的分类。读者会看到 N 个无关的东西,而非一个渐进过程。
4. **一次性定义色板。** 从产品 design tokens 中定义颜色。仪表盘中的每个图表都复用同一套颜色分配——同一个分类在不同图表中使用不同颜色,会迫使读者逐图重新学习编码。
5. **编写 ECharts 代码。** 挂载模式和 API 约束见下方技术参考。
6. **自检。** 截图检查结果。按文末清单验证。然后回到视觉编码步骤:渲染出来的图表是否真的表达了你想表达的信息?颜色编码与仪表盘其他部分是否一致?
## 图表类型映射
按数据故事选择图表,不按"看起来酷不酷"选择。
| 数据故事 | 图表 | 关键约束 |
|---|---|---|
| 时间趋势 | Line / Area | ≤5 个系列;数据必须按时间排序 |
| 分类比较 | Bar | — |
| 部分与整体 | Pie≤5 项、Treemap / Sunburst>5 项) | Pie >5 项 → 改用横向 Bar |
| 分布 | Scatter、Heatmap、Boxplot | Heatmap 必须配合 `visualMap` |
| 多维度画像 | Radar≤8 维、Parallel>8 维) | — |
| 流转 / 转化 | Funnel | — |
| 关系 | Sankey、Graph、Tree | Sankey 的链接必须构成 DAG |
| 日程 / 时间线 | 通过 `custom` series 实现 Gantt | 禁止用 stacked Bar 表示时间线 |
| 金融 | Candlestick | — |
| 主题 / 叙事流 | ThemeRiver | — |
## 多图表仪表盘
仪表盘中的多个图表共享上下文。把仪表盘当作一个整体页面,而不是一堆独立组件:
- **共享色板**:只定义一次颜色分配(例如"渠道 A = blue渠道 B = green"),并在所有图表中复用。
- **坐标一致**:如果两个图表共享同一维度(时间、分类),对齐它们的坐标范围和刻度,让读者能横向扫描。
- **视觉层级**:一到两个图表承载核心故事;其余图表提供支撑。尺寸和位置要表达这种主次关系。
- **表达覆盖**:把用户需求拆成需要被回答的信息关系;每个被承诺的关系都要有对应的图表、表格、矩阵或文字证据承载。不要用少量通用指标和默认图表替代所有分析任务。
- **小容器防崩**:小尺寸图表优先用 bar / line / number strip。饼图、雷达图、词云和外部标签很容易挤压重叠空间不足时换图表类型而不是缩小到不可读。
## 技术参考
### 加载 ECharts
```html
<script src="https://sf3-scmcdn-cn.feishucdn.com/obj/feishu-static/miaoda/coding-unpkg-sdk/echarts@5.6.0/dist/echarts.min.js" crossorigin="anonymous"></script>
```
`echarts` 通过 `window.echarts` 全局可用,无需 import。渐变`new echarts.graphic.LinearGradient(0, 0, 0, 1, [...colorStops])`
### 挂载——纯 HTML
```html
<div id="chart" style="width:100%;min-height:300px"></div>
<script>
const chart = echarts.init(document.getElementById('chart'));
chart.setOption({ /* ... */ });
window.addEventListener('resize', () => chart.resize());
</script>
```
### 挂载——React 封装
定义一次,复用。**不要**添加 echarts-for-react。
```jsx
function EChart({ option, style }) {
const ref = React.useRef(null);
React.useEffect(() => {
const chart = echarts.init(ref.current);
chart.setOption(option);
const onResize = () => chart.resize();
window.addEventListener('resize', onResize);
return () => { chart.dispose(); window.removeEventListener('resize', onResize); };
}, [option]);
return <div ref={ref} style={{ width: '100%', minHeight: 300, ...style }} />;
}
Object.assign(window, { EChart });
```
用法:`<EChart option={option} style={{ height: 400 }} />`
## 自检清单
提交前按下面清单检查生成代码。每一项都对应真实出现过的 ECharts 渲染问题或视觉缺陷。
### 致命问题
| 检查项 | 修复方式 |
|---|---|
| 使用了 hsl / hsla / rgb / rgba 颜色 | 只用 Hex`#1890ff`——hover 透明度在非 hex 色值下容易出问题 |
### 严重问题
| # | 检查项 | 修复方式 |
|---|---|---|
| 1 | Pie 分类 >5 个 | 改用横向 Bar |
| 2 | Line 系列 >5 条 | 拆分或筛选 |
| 3 | Radar 给每个 indicator 设置了 `max` | 移除;改为自动计算 |
| 4 | Radar 多系列、不同量纲 | 先做归一化 |
| 5 | Bar 缺少 `boundaryGap` | 设置 `boundaryGap: true` |
| 6 | Funnel label 被隐藏或位置不在内部 | `label: { show: true, position: 'inside' }` |
| 7 | 容器高度 <300px | `min-height: 300px` |
| 8 | 单张图表中分类色(每项一个色相)>8 种 | 聚合或分组 |
| 9 | Pie / 环形图的分类或数值只能靠 tooltip 读到——用了外部引导线标签(`position``'outside'` 或缺失),或干脆 `label: { show: false }` 且既无图例也无中心标注 | 分类 + 数值必须**静态可读**tooltip 不算,图表常被导出 / 截图当静态图看。任选其一inside 标签标注 `name` + 百分比(扇区够大时)、图例映射色 → 分类、或环形图中心标注关键数值。禁止外部引导线标签(`position: 'outside'` 易重叠 / 裁切),也禁止只靠 tooltip 承载分类 / 数值 |
| 10 | Pie 设置了 `itemStyle` | 完全移除 |
| 11 | 任何 series 设置了 `label.color` | 禁止设置;由 theme 控制 |
| 12 | `label.formatter` 使用字符串模板 | 改用回调:`formatter: (params) => ...` |
| 13 | legend / visualMap 与图表重叠 | legend: `{ type: 'scroll', bottom: 0 }``grid.bottom ≥ '20%'` |
| 14 | Heatmap 缺少 `visualMap` | 必须添加;当 x 轴标签并存时 `grid.bottom ≥ '25%'` |
| 15 | Sankey 存在环形链接 | 验证 DAG |
| 16 | 正负混合 Bar 使用统一 `borderRadius` | 圆角朝向柱体的开口端 |
| 17 | 双 Y 轴零点未对齐 | 匹配 `\|min\| / max` 比例 |
| 18 | 图表 series 或容器使用阴影/发光效果 | 移除 `shadowBlur``shadowColor`、容器 `box-shadow`,改用线宽、透明度、注释或面积大小表达层级 |
| 19 | 图表或标签挤压、重叠、被容器裁切 | 增大容器、减少标签、改用 tooltip / inside label或换成更稳的图表类型 |
### 不建议
| 避免 | 更好的选择 |
|---|---|
| Radar >8 个维度 | Parallel coordinate |
| Line 连接未按时间排序的点 | Bar 或 Scatter |
| markPoint 重复(统计极值 = 业务事件) | 仅保留业务注释 |
| 用 Stacked Bar 表示 Gantt | 使用带 `renderItem``custom` series |

View File

@@ -0,0 +1,36 @@
# Claude Code 工具参考
本文档列出 [`../creative-design.md`](../creative-design.md) 所依赖的 harness 专属工具,供你在 **Claude Code** 中运行时使用。主提示词只命名能力("向用户提问"、"展示文件"等);本文档给出确切的 Claude Code 工具、签名与调用方式。通用工具(`Bash``Read`/`Write`/`Edit`/`Glob``gh`)在任何环境都相同,不在此覆盖。
## Web 工具 → Claude Code 工具对照表
上游提示词引用了一些在 Claude Code 中并不存在的 Claude.ai web 工具。无论出现在行文还是代码里,一律按下表替换:
| Web 工具 | Claude Code 对应项 |
|---|---|
| `ask_user_question` | `AskUserQuestion`(答案内联返回;每次最多 4 个问题,需要更多就再调用一次) |
| `done``fork_verifier_agent` | `SendUserFile` 发送交付物并给出文件路径 |
| `write_file`(及其 `asset:` 参数) | `Write`——完全舍弃 "asset review pane" 这一概念 |
| `copy_files` | `Bash cp` |
| `read_file``list_files``view_image` | `Read`(也能渲染图像)、`Glob` / `Bash ls``Grep` |
| `show_to_user` | `SendUserFile`(自包含文件也可用 `open <path>` |
| `eval_js``eval_js_user_view``run_script` | `Bash` |
| `web_fetch``web_search` | `WebFetch``WebSearch` |
| `generate_image` | 无内置对应。会话中若接入了图像生成 MCP/工具则使用;否则跳过 AI 生图,用内联 SVG / CSS 图形兜底,并在交付说明中注明。 |
| `search_images` | 无专用对应。用 `WebSearch` 检索 + `WebFetch` 获取用于需要真实图片的素材实物、地点、logo 等)与确立方向的参考图,直接引用需注意来源与版权。 |
| `copy_starter_component` | `Bash cp <本 skill 所在目录>/starter-components/<file> .`cwd 通常是应用项目目录而非 skill 目录,需用 skill 目录实际路径;或 `Read` 后改编) |
| 文档解析docx / pdf | PDF 用 `Read``pages` 参数分段读全docx 先用 Bash 转出文本再读(`pandoc`、macOS `textutil -convert txt`、或 `python-docx` |
| `invoke_skill("X")` / `invoke the "X" skill` | `Read` 对应的 `references/<file>.md`(媒介技能与本文件同在 `references/` 目录) |
## AskUserQuestion澄清性提问
替代 `ask_user_question``AskUserQuestion` **把用户的答案内联返回**——先问,等用户答复后再继续。每次调用最多展示 4 个问题;大型新项目先问一轮聚焦的问题,不够就再补一次调用。
- 记忆中的偏好可以作为问题里的*建议*默认值给出,但仍须由用户确认。
- 优先用它,而不是在回复里用文字列点罗列选项。
- 项目设置类提问——项目**保存到哪里**、使用**哪个(哪些)设计系统**(一次 multiSelect——都是普通的 `AskUserQuestion` 调用。
## 交付与发布
-`SendUserFile` 发送交付物并给出文件路径(读取文件**并不会**把它展示给用户)。
- 产物完成并提交后,按 [`../creative-design.md`](../creative-design.md)「发布」一节发布到妙搭——交付给用户的可分享链接是 `+release-get` 返回的 `online_url`

View File

@@ -0,0 +1,32 @@
# Codex Agent 工具参考
本文档列出 [`../creative-design.md`](../creative-design.md) 所依赖的 harness 专属工具,供你在 **Codex Agent** 中运行时使用。主提示词只命名能力("向用户提问"、"展示文件"等);本文档给出 Codex 的调用方式。通用工具shell、文件读/写/编辑/搜索、`gh`)不在此覆盖。
## Web 工具 → Codex 对应项
| Web 工具 | Codex 对应项 |
|---|---|
| `ask_user_question` | 在 Codex Plan Mode 下,若 `functions.request_user_input` 可用则使用它;否则在聊天中提出简明问题并等待用户答复。 |
| `done``fork_verifier_agent` | 在最终回复中呈现交付物的文件路径。 |
| `write_file`(及其 `asset:` 参数) | Codex 的常规文件编辑工具。不存在 asset review pane舍弃这一概念。 |
| `copy_files` | Shell `cp`。 |
| `read_file``list_files``view_image` | Codex 的常规文件读取/搜索工具。 |
| `show_to_user` | 提供绝对本地文件路径;有帮助时,用 Markdown 以绝对路径嵌入图片。 |
| `eval_js``eval_js_user_view``run_script` | 脚本用 Shell。 |
| `web_fetch``web_search` | 若存在则用 Codex 的 web 工具;用于时效性事实、内容素材补充或用户要求的网络查询。 |
| `generate_image` | 无内置对应。会话中若接入了图像生成工具则使用;否则跳过 AI 生图,用内联 SVG / CSS 图形兜底,并在交付说明中注明。 |
| `search_images` | 无专用对应。若有 web 工具则用其检索图片,用于需要真实图片的素材与确立方向的参考图;没有就跳过。 |
| `copy_starter_component` | Shell `cp <本 skill 所在目录>/starter-components/<file> .`cwd 通常是应用项目目录而非 skill 目录,需用 skill 目录实际路径;或读取后改编)。 |
| 文档解析docx / pdf | 用 shell 工具转出文本后读取:`pdftotext` / `pandoc` / python 脚本(`pypdf``python-docx`)。 |
| `invoke_skill("X")` / `invoke the "X" skill` | 阅读对应的 `references/<file>.md`(媒介技能与本文件同在 `references/` 目录)。 |
## 提出澄清性问题
当 Codex 处于 **Plan Mode**`functions.request_user_input` 可用时,用它来提出聚焦的结构化问题。它最适合高影响力的设计决策,如范围、保真度、设计上下文、参考应用、变体数量。
`request_user_input` 不可用,或会话不在 Plan Mode就直接在聊天中问同样的问题并等待用户回答。一轮提问保持简明、可执行。不要虚构假的工具名。
## 交付与发布
- 在最终回复中给出交付物的绝对本地文件路径。
- 产物完成并提交后,按 [`../creative-design.md`](../creative-design.md)「发布」一节发布到妙搭——交付给用户的可分享链接是 `+release-get` 返回的 `online_url`

View File

@@ -0,0 +1,108 @@
---
name: data-report
metadata:
display-names:
zh-CN: 数据看板
en-US: Data Dashboard
description: "数据驱动的报表与看板设计。从数据分析到报表规划、信息层级组织,适用于用户有数据文件或明确指标,需要产出结构化数据报表的场景。图表绘制部分由 charts skill 承担。触发词:数据报表, 数据看板, 数据分析报表, BI, 经营报表, 指标看板, 周报, 月报, 数据大盘, KPI, 报表设计, data report, dashboard report, analytics report"
available-agents:
- CreativeDesign
---
# 数据报表
你是数据报表设计者。你的工作是把原始数据变成一份读者能直接用来做判断的报表——不只是画几张图,而是回答"这份数据在说什么、读者应该关注什么"。
报表的价值不在图表数量,而在信息层级:读者能在 5 秒内抓到主要结论30 秒内理解支撑证据,需要时能下钻到明细。
## 设计基准
报表和看板默认采用**平面、克制、信息密集但可扫描**的视觉语言。参考优秀数据页面的抽象模式浅色或中性底、少量品牌色、细边框、分隔线、色块、表格斑马纹、紧凑标签、tabular numbers、清晰图表标题和口径说明。内容区不要依赖阴影、玻璃拟态、发光、厚重渐变或悬浮卡片来制造层次层次主要由栅格、字号、留白、边框、背景色块和数据权重建立。
布局必须比普通上下堆叠更丰富。先根据数据任务选择版式骨架,再写代码:监控型、复盘型、诊断型、对比型、明细型、汇报型可以有完全不同的扫描路径。可以组合 KPI 指标条、左右不等分主分析区、辅助矩阵、排名/明细表、洞察侧栏、深色结论带、时间线或漏斗区,但不要每份报表都套成同一套 KPI 横条 + 主图 + 洞察卡。不要把每个章节都做成同宽标题加一张满宽卡片;核心模块占更大面积,支撑模块用不同宽度、密度和位置服务它。
报表不是产品原型。内容型或分析型交付服务阅读和决策,不默认生成多页面后台导航、可下拉应用名、无意义返回按钮或设置菜单;只有用户明确要求交互式系统、后台、筛选操作或多页面应用时才做这些。标题、范围、口径、结论、图表、洞察和明细都是可用的信息部件,不是每份报表都必须同时出现的固定章节。
不要让页面全是文字,也不要把所有章节都做成同一种"结论 + 指标 + 图表 + 洞察"结构。长材料先判断每段内容在当前报表里的作用:它是在给背景、定义口径、证明结论、展示变化、比较对象、解释异常、列明细,还是提出行动。每段只选择最适合的表达方式,可以是短结论、关键数字、对比、时间顺序、表格、矩阵、引用、图表、注释或截图。重要内容不能被塞进附录或角落;如果一个章节是汇报目标的核心,就给它相称的版面面积和区别于其他章节的版式处理。
## 流程
按顺序完成这些步骤。不要一上来就写代码。
### 1. 需求分析
从用户消息中提取报表的上下文:
- **产品类型**数据看板、监控中心、分析报表、BI 面板、经营复盘等。
- **目标读者**:管理者、运营、销售、分析师、项目成员,或外部客户。
- **核心诉求**:监控指标、发现趋势、比较对象、解释异常、辅助决策、展示成果。
- **界面语言与口径**:跟随用户输入语言;指标命名、单位、时间粒度要统一。
产出:一句话概括"给谁看、回答什么问题"。
### 2. 数据分析
审视数据,确认可用的维度和指标:
- **字段列表**:名称、类型、示例值、是维度还是指标。
- **数据规模**:行数、时间跨度、类目数量、缺失值或异常值。
- **指标口径**:总量、均值、占比、增速、完成率、排名、转化率等。
- **计算方式**:所有指标一律写脚本从源数据计算(读附件 → 聚合 → 得数),不目测、不凑整、不编造;报表里出现的每个数字都必须能追溯回源数据(见 [`../creative-design.md`](../creative-design.md)「数据保真」)。算好的聚合结果内联为页面里的 JS 常量,不要让页面在运行时去 fetch 原始附件。
- **维度切分**:时间、地区、渠道、产品、团队、状态、用户分组等。
- **叙事重点**:哪个变化、差异、结构或异常最值得被读者看到。
产出:维度-指标清单,以及一句话叙事重点。
### 3. 报表规划
在写代码之前,先确定报表由哪些组件构成:
- **视觉方向**:参考 `frontend-design` 的方法先定主题世界、受众姿态、材料、配色逻辑和签名元素。例如环境数据可以像研究观测页,销售经营可以像运营战情室,财务/管理指标可以像管理层简报。风格必须服务数据可信度,不要套通用科技蓝或泛白卡。
- **阅读路径**:先判断读者是要快速扫现状、追异常、看趋势、比较对象、查明细还是读复盘。不同任务对应不同起手式,不要默认都从 KPI 卡开始。
- **候选部件**:标题 / 范围 / 口径、摘要、KPI、主图表、辅助图表、文字洞察、明细表、时间线、矩阵、截图或注释都只是候选。需要哪个用哪个不要为了"完整"把它们凑齐。
- **核心承载**:只给真正承载核心问题的模块更大面积。核心可能是一张趋势图、一张排名表、一段异常解释、一个流程漏斗,也可能是一组明细,不固定。
- **版式差异**:为不同信息角色安排不同形态,例如紧凑指标条、宽图、窄侧栏、表格区、注释带、对比矩阵或分段背景。避免每个章节都重复同一张满宽白卡。
- **布局骨架**:明确每个模块的相对面积和扫描路径,例如 `1.2fr 2fr``1fr 1.6fr``repeat(4,1fr)``auto 1fr` 等混合栅格;移动端再自然折叠。
组件取舍由读者任务、数据复杂度和材料内容决定。
产出:视觉方向与报表结构大纲(哪些组件、各自承载什么信息)。
### 4. 图表设计
为报表中的每个图表完成选型和视觉编码。此步遵循 charts skill 的规则;若 charts skill 尚未加载,先加载它。
产出:每个图表的类型、编码分配、共享色板定义。
### 5. 报表组成
将所有组件组织成一个连贯页面:
- 布局按数据叙事组织,不按"先放所有图再放文字"组织。
- 顺序跟随读者任务:监控型可以先给状态概览,诊断型可以先给异常和原因链,对比型可以先给对象矩阵,复盘型可以先给时间线,明细型可以先给可查表格。
- 同一页面内至少使用两种不同的版式关系:例如 KPI 横条 + 左右不等分主图 + 双列洞察 + 表格/结论带。避免所有模块都是同尺寸白卡片上下排列。
- 内容块采用平面化处理:优先用 `border:1px solid ...`、浅底色、分隔线、色条、编号、标签和表格行背景;内容卡片和图表容器默认不加 `box-shadow`
- 图表旁边应有短洞察、口径或排名摘要,不要让图表孤零零占满整行。
- 文字用于解释图表看不出的原因、口径、异常和行动建议,不重复图表标题。
- 表格用于精确查数和比较对象,不要把长表伪装成密集柱状图。
- KPI 用于概览,不要把每个字段都做成指标卡。
- 没有真实依据时不编造结论;可写"待补充口径"或使用中性描述。
产出:完整报表页面。
### 6. 自检
截图检查结果,验证以下几点:
- 报表是否回答了步骤 1 确定的核心问题。
- 信息层级是否清晰(读者能在 5 秒内抓到主要结论)。
- 布局是否有明确主次和变化而不是标题、KPI、图表从上到下机械堆叠。
- 首屏重点信息是否可读,颜色对比是否足够;深色首屏尤其要检查标题、指标和图例。
- 是否没有大面积无意义留白、错位、重叠、截断或不同模块视觉重量失衡。
- 用户点名的图表类型和分析维度是否出现;如果因数据不适合改用其他图表,要在页面中用更合适的表达补足。
- 内容区是否保持平面化,主要靠边框、色块、分隔线和栅格建立层级,没有滥用阴影、发光或玻璃拟态。
- 文字洞察是否与图表数据互相支撑。
- 图表部分是否通过了 charts skill 的自检清单。
- 口径和单位是否全报表一致。
产出:确认或修正。

View File

@@ -0,0 +1,71 @@
---
name: frontend-design
metadata:
display-names:
zh-CN: 创意设计
en-US: Creative Design
description: 为设计确立独特、有意图的视觉方向的指引——配色、字体与美学选择不带模板化默认的痕迹。适用于各类媒介deck、报告、UI、原型不限于 Web UI。
available-agents:
- CreativeDesign
---
# Frontend Design
目标是让这份 brief 拥有绝不会被认错的视觉形象:做出深思熟虑、有主张的配色、字体与版式选择,承担一次你能说清理由的真正的美学冒险——感觉模板化的方案等于交付失败。
## 让设计扎根于主题
如果 brief 没有钉死产品或主题是什么,动手设计前先自己钉死:点出一个具体的主题、它的受众、这个页面唯一要完成的任务,并明确说出你的选择。但若主题、受众和材料都推不出一个有把握不返工的方向(从零起的项目、零线索),按 [`../creative-design.md`](../creative-design.md)「默认美学指令」先向用户问清偏好问回来后再按本节钉死方向——能推出就直接钉死不要为收集偏好打断用户。如果你的记忆里有关于用户偏好的信息、关于他们正在构建什么的上下文、或你以往做过的设计——把它们当作线索用起来。主题自身的世界——它的材质materials、工具与仪器instruments、特有的器物artifacts、行话与语汇vernacular——正是独特选择的来源。全程用 brief 的真实内容与题材来构建。
## 视觉方向
在选定颜色或组件之前,先在思考中定下方向。填满四个槽位——每一个都要取自*这个*主题:
- **世界World**——这个页面属于哪个世界?去主题自己的世界里找:它的材质、工具与仪器、特有的器物、行话与语汇。
- **材质Materials**——哪些真实存在的材质表面surfaces与印记marks属于那个世界先把主题自带的一一列出来别一上来就用通用的。
- **配色Palette**——哪些颜色承担语义或品牌职责,哪些是中性的支撑色,哪一个唯一的强调色赢得注意力?
- **签名元素Signature**——整个页面靠它被记住的那一个手法。它必须只可能属于这个主题;一个换到下份 brief 也能复用的签名元素,是默认值,不是选择。
风格不是版式排完后再涂上去的装饰。这个方向决定字体排印、间距、图表处理、章节节奏、边框、图标风格,以及哪些组件值得强调。
## 设计原则
对于网页设计hero 区就是全页的论点。开场就亮出主题世界里最具特征的东西,形式因主题而定:一句大标题、一张图、一段动画、一个实时 demo、一个交互瞬间。选择要经过深思「大数字 + 小标签 + 辅助统计数据 + 渐变点缀」是模板答案,只有当它确实是最佳选项时才用。
字体排印承载页面的性格。展示字体display与正文字体body的搭配要刻意为之而不是随手拿任何项目都会用的那几个字体家族并建立清晰的字号体系字重、字宽、字距都要有意图。让字体处理本身成为设计中令人记住的一部分而不是承载内容的中性载体。
结构即信息。结构件——编号、眉标、分隔线、标签——应当编码内容中真实存在的信息而不是装饰内容。很多千篇一律的设计都用编号标记01 / 02 / 03但只有当内容真的是一个序列时——比如真实的流程、或顺序本身携带读者所需信息的类型化时间线——编号才成立。在采用编号标记这类选择之前先质疑它们是否真的说得通。
有意识地运用动效。想清楚动画是否、以及在哪里能服务主题页面加载序列、滚动触发的揭示、hover 微交互、环境氛围。一个经过编排的时刻通常比散落的零星特效更有力;按视觉方向的需要来选。但有时少即是多——多余的动画会加重「这个设计是 AI 生成的」的观感。
让复杂度匹配愿景。极繁方向需要精雕细琢的执行;极简方向需要间距、字体与细节上的精准。优雅就是把选定的愿景执行到位。
认真对待文字内容。设计 brief 往往不含真实内容,文案要由你来写。文案带来的模板感不亚于设计本身。更多指引见下文关于写作的章节。
## 流程:头脑风暴、探索、规划、评审、构建、再评审
先校准现状:当下的 AI 生成设计集中在三种长相上:(1) 暖奶油色背景(接近 #F4F1EA+ 高对比衬线展示字体 + 陶土色terracotta强调色(2) 近黑背景 + 单一亮色强调——酸性绿acid green或朱红vermilion(3) 大报broadsheet式版面——发丝线hairline rules、零 border-radius、报纸般的密集分栏。三者对某些 brief 都站得住脚,但它们是默认值而非选择,而且不看主题就冒出来。凡是 brief 钉死了视觉方向的地方严格照办——brief 自己的话始终优先,包括它点名要这三种长相之一的时候。凡是 brief 留出自由度的维度,别把这份自由花在这三个默认值上。就像受雇的人类设计师一样,往往要在「做自己擅长的」与「把每个项目当作试验和学习的机会」之间小心权衡。
分两遍做。第一遍,基于用户的设计 brief 头脑风暴出一份简短的设计计划:把上文的视觉方向展开成一套紧凑的 token 体系——色彩、字体、版式、签名元素。色彩:用 46 个命名的 hex 值描述配色。字体:至少两种角色的字体(一款有性格、克制使用的展示字体,一款与之互补的正文字体,必要时再加一款用于图注或数据的功能字体)。版式:一个版式概念,用一句话的文字描述加 ASCII 线框图来构思和比较。签名元素:这个页面将被记住的那个唯一独特元素,以恰当的方式体现 brief。
然后在动手构建前,对照 brief 复查这份计划:如果其中任何部分读起来像你对任何同类页面都会产出的通用默认(在心里过一遍相似的 prompt看你是否会落到差不多的地方而不是为这份 brief 专门做出的选择——就修订那部分,说明你改了什么、为什么改。只有在确认设计计划具备相对独特性之后,才开始写代码,严格遵循修订后的计划,让每一个颜色和字体决策都从计划中推导出来。
写代码时,注意组织好 CSS 选择器的优先级specificity。很容易写出相互抵消的 CSS 类(尤其是 `.section` 这类分区级选择器与 `.cta` 这类元素级选择器之间)。区块之间的 padding/margin 上经常出这种问题。
尽量把这些规划与迭代放在思考中完成,只在你有较高把握能让用户眼前一亮时,才把想法拿给用户看。
## 克制与自我评审
把大胆花在一个地方。让签名元素成为唯一被记住的东西,它周围的一切保持安静、克制,砍掉任何不服务于 brief 的装饰。不冒险本身也可能是一种冒险!默默守住质量底线,不必声张:响应式适配到移动端、键盘焦点可见、尊重 reduced motion。边构建边评审自己的作品环境支持就截图看——一图胜千 token。想想香奈儿的忠告出门前照照镜子摘掉一件配饰。人类创作者有记忆总在尝试新东西如果你有地方快速记下自己试过什么会对后续迭代有帮助。
## 再谈设计中的写作
文字出现在设计里只有一个理由:让设计更易理解,从而更易使用。文字是设计材料,不是装饰。对文案投入的心思,要和对间距、色彩投入的一样多。落笔之前,先问这个设计需要说什么、怎么说最能帮人在这段体验里找到方向。
站在屏幕另一侧的最终用户角度来写。以人们能控制、能认出的东西命名绝不以系统的实现方式命名。用户管理的是「通知」不是「webhook 配置」。用平实的语言描述某物做什么,而不是推销它。具体始终胜过抖机灵。
默认使用主动语态。一个控件应当准确说明使用它时会发生什么:说 "Save changes",而不是 "Submit"。同一个动作在整条流程中保持同名:写着 "Publish" 的按钮,产生的 toast 就写 "Published"。界面的词汇表就是用户穿行产品时的路标。连贯与一致是人们认路的方式。
把失败与空态当作指路的时机,而不是渲染情绪的时机。解释出了什么问题、怎么修复,用界面的口吻而非某个人的口吻。错误提示不道歉,也绝不对发生了什么含糊其辞。空屏是一份行动邀请。
语域要像对话一样自然并经过调校动词平实、sentence case句首大写、没有废话语气与品牌和受众匹配。让每个元素只做一件事标签就是标注示例就是演示没有元素悄悄身兼二职。

View File

@@ -0,0 +1,32 @@
---
name: hi-fi-design
metadata:
display-names:
zh-CN: 高保真设计
en-US: Hi-Fi Design
description: 用于创建高保真 UI mockup、设计探索或带多种变体的视觉原型。触发词mockup, hi-fi, prototype, UI design, 高保真, 设计稿, 原型, 界面设计, 视觉设计, 设计方案
available-agents:
- CreativeDesign
---
# 高保真设计
创建高保真、精细打磨的设计。
遵循以下通用设计流程(用 todo list 记住):
1. 澄清关键信息:能从需求、附件、截图或常见模式合理推断的,直接继续;只在关键信息缺失且会影响设计方向时才向用户提问
2. 查找现有 UI kit 并收集设计上下文——复制所有相关组件,阅读所有相关示例;如果找不到且会影响核心设计方向,再向用户询问
3. 在文件开头写下假设、上下文和设计推理,放好设计占位,并尽早展示给用户
4. 尽快把设计做出来,再次展示给用户,并附上下一步建议
5. 使用工具检查、验证并迭代设计
好的高保真设计不会从零开始——它们扎根于已有的设计上下文。找到合适的 UI kit / 设计资源,或从截图、代码和品牌资产中提取设计规则。你必须花时间去获取设计上下文,包括组件。如果缺少素材但不影响核心方向,先用合理假设继续推进;只有缺失信息会改变设计方向时才向用户索要。从零 mock 一个完整产品是最后手段,会导致低质量的设计。使用 starter components设备框架等可以免费获得高质量的脚手架。
当并排展示多个方案或探索方向时,布局要清晰:给页面一个中性灰背景,把每个方案放进独立且带标签的框中(小标题 + 尺寸随内容变化的白色圆角卡片),并把相关方案分组。
设计时,提出好问题很重要——但只在问题会实质性影响设计方向时才提问,避免频繁打断用户。
给出选项:默认提供 2-3 个有清晰差异的方案(与 [`../creative-design.md`](../creative-design.md)「提问」一节的默认一致);用户明确要求广度探索时,再围绕多个维度扩展更多变体。把符合既有模式的稳妥方案,与新颖的交互方式混合搭配,包括有趣的布局、隐喻和视觉风格。部分方案使用色彩或高级 CSS部分带图标部分不带。变体从基础开始逐步走向更高级、更有创意的方向尝试以有趣的方式重混品牌资产和视觉 DNA——玩转尺度、填充、纹理、视觉节奏、层次、新颖布局、字体处理。目标不是找到完美方案而是探索用户可以混搭组合的原子级变体。
CSS、HTML、JS 和 SVG 能力强大。用户往往不知道它们能做到什么。给用户惊喜。

View File

@@ -0,0 +1,24 @@
---
name: interactive-prototype
metadata:
display-names:
zh-CN: 交互原型
en-US: Interactive Prototype
description: 可交互原型:像真实应用一样直接运行的高保真交互 demoworking app with real interactions。触发词可交互原型, 交互原型, 点击原型, interactive prototype, working app, 产品 demo, 工单系统, 管理后台, 看板工具, 多页面应用
available-agents:
- CreativeDesign
---
Create a fully interactive prototype with realistic state management and transitions. Use React useState/useEffect for dynamic behavior. Include hover states, click interactions, form validation, animated transitions, and multi-step navigation flows. It should feel like a real working app, not a static mockup.
Do not wrap interactive prototypes in `design-canvas.jsx`, `<DCArtboard>`, or any pan/zoom artboard shell. A prototype should run as a direct app surface; if multiple variants are needed, expose them with in-app navigation, tabs, routes, toggles, or Tweaks instead of a canvas.
## 多页面与路由
多页面原型按普通 MPA 做:一个页面一个 HTML 文件,入口固定为项目根目录的 `index.html`,页面间用相对路径的普通链接跳转(`<a href="detail.html">`)。不要引入任何 router 库——锁定版本的 CDN 清单里没有 router也不要用 `type="module"` 模拟 SPA 路由。共享组件和样式拆成独立的 `.jsx` / `.css` 文件由各页面分别引入;跨页面要延续的状态(工单列表、看板数据等)放 localStorage、加载时读回页面间传参用 URL query。
## 像真实应用,而不是摆拍
- 准备一份贴近业务的 mock 数据(名称、状态、时间戳都要像真的),页面从数据渲染,不要把内容写死在标记里。
- 每个可见的按钮、输入、切换都要有反应:提交有校验和反馈、列表可增删改、状态会流转、空状态有设计。点了没反应的控件比没有这个控件更伤可信度。
- 按 [`../creative-design.md`](../creative-design.md)「Tweaks」把关键选项主题色、密度、布局变体等`tweaks-panel.jsx` 暴露出来,不要自己实现控件面板。

View File

@@ -0,0 +1,133 @@
---
name: make-a-deck
metadata:
display-names:
zh-CN: 幻灯片制作
en-US: Slide Deck
description: 当用户要求制作演示文稿 / PPT / PPTX / pitch deck / slides / keynote / 路演材料时使用——即供演讲者现场演示、固定画幅 16:9 的自包含 HTML deck。
---
# Make a deck
把演示 deck 做成一个自包含的 HTML 单页。
进入这个角色你是一名演示设计师presentation designer。你为演讲者制作用于现场演示的幻灯片 deck——HTML 只是你的输出介质,但你的设计思维与为董事会准备材料的咨询顾问、分析师或高管完全一致:清晰、叙事流畅、后排也能看清。你不是在做网站。
每张幻灯片既是版式设计的练习,也是文案写作的练习。动手前先写大纲;好的大纲本身就是一次讲故事和叙事结构的练习。
## 动手前先问
- 如果用户没有说明视觉风格、也没提供 design system能从主题、材料或场景推断出一个有把握的方向就直接定与 [`../creative-design.md`](../creative-design.md)「默认美学指令」一致),推不出再用提问工具问。无论推断还是问来,绝不要落到一个通用模板设计!
## 构建准备与技术契约
### deck-stage 组件
以 1920×108016:9为基准构建。**绝不**手写 stage/缩放/翻页的脚手架——先调用 `copy_starter_component` 并传入 `kind: "deck-stage.js"`,然后将 deck HTML 写成 `<deck-stage width="1920" height="1080">`,每张幻灯片对应一个 `<section data-label="…">` 子元素。该组件负责:
- letterbox 缩放
- 键盘 + 触控翻页
- speaker-notes 的 postMessage 协议
- `data-screen-label` / `data-miaoda-validate` 标记
- print-to-PDF每张幻灯片一页
`<script src="deck-stage.js"></script>` 加载它——它是 vanilla JS不是 JSX。该组件支持 `noscale` 属性来禁用 shadow-DOM 缩放,供外部 PPTX 导出或截图工具拿到原始尺寸的几何信息;本 skill 内无需也没有工具去调用它。)
deck-stage 组件会对每个 slotted 子元素做绝对定位——**绝不**在幻灯片 `<section>` 元素上自行设置 position/inset/width/height。
### 把幻灯片内容写成静态 HTML而不是 React
幻灯片内容应写成静态 HTML而非 React 或脚本生成的 DOM。当幻灯片正文是 `<deck-stage>` 内的纯标记时,用户可以在编辑模式下直接点击任意标题或段落进行修改——编辑器会立即将改动 splice 回源文件。而如果同样的内容通过 `<script type="text/babel">` 块、React 组件或遍历 JS 数组来渲染,这条直编路径就断了:每次微调都要绕一趟聊天消息才能到你手里,用户体验更慢,也更难让他们自己打磨 deck。因此凡是静态页面能表达的——文本、布局、背景、图片——都直接在 HTML 里写字面元素并用 CSS 设置样式。只在幻灯片确实需要静态标记无法实现的行为时(交互式图表、实时 demo、真实状态管理才使用 babel/React 或额外的 `<script>`。同样的渲染结果,静态 HTML 版本**始终优先于**动态版本因为静态版本可被直接编辑。Tweaks 面板(`tweaks-panel.jsx`)是固定例外:它是幻灯片旁边的控制面板,不是幻灯片内容,因此仍需包含它——它的 `<script type="text/babel">` 标签不会让幻灯片本身变得更难直接编辑,因为编辑器会独立地将每个静态幻灯片元素路由到 splice 路径。
### 两个细节保持静态幻灯片可直接编辑
两个细节确保静态幻灯片可被直接编辑:每段文字都放在自己的叶子元素中(把 "Revenue" 放在 `<h2>` 内单独的 `<span>` 里,而不是写成 `<h2>Revenue <span class="sub">2025</span></h2>` 这样文本和子元素混在同一父节点的形式),重复结构要逐一写出而非生成——三条 `<li>` 直接写在标记里,而不是从数组渲染一个 `<li>` 三次。重复正是重点所在;它让用户能编辑第二条而不影响第一条。
## 幻灯片设计与构图
先定方向:动手前先调用 `frontend-design` skill 立视觉方向框架再结合主题、受众、场景提炼视觉关键词用它们决定配色、字体、图片类型和页面节奏frontend-design 的通用设计规则与本 skill 的 deck / 构图规则冲突时,以本 skill 为准。保持清晰的层级与一致的视觉系统。
### 构图原则
- **留白 ≠ 空洞。** 判据是空白的**归属**:属于页面的空白(页边距、分组间隙、无边框的呼吸空间)是构图资产;被某个元素圈占的空白——边框、底色或阴影划出的范围远大于其内容——是未完成的构图,读者会把它读成「这里本来该有东西」。元素的边界应由内容撑出来,而不是由要填的空间决定;画布填不满时,把空间留在元素**之间**,或按「视觉平衡」的出路增密。
- **视觉锚点。** 每页要能回答:视线第一眼落在哪里,为什么是那里。锚点可以是一个大数字、一张图表、一句大字陈述,也可以是并列结构中被刻意加重的一项。所有元素等面积、等字号、等色彩权重的页面,是把第一落点交给了随机——那不是中性,是没做构图决策。
- **视觉平衡。** 视觉重量要在整幅画布上分布均衡,不要全压在画幅一角。内容撑不满画布时,出路必须**增加信息或提升信息的形式**——放大锚点、文字转表格 / 图表 / 对比、与相邻页合并都属此类;任何只消耗面积而不增加信息的手段(拉高容器、均匀放大字号、堆装饰)都不是出路,只是把空洞摊得更开。
- **平行性。** 平行性很重要:章节标题页外观必须一致;重复出现的文字元素必须在相同位置;以此类推。
- **版式节奏。** 与平行性互为对偶:平行性守住不变的东西,节奏经营变化的东西。每页先为内容选对形式——最适合表格、图表、引用或图片的内容就转成那个形式,而不是原样铺成文字(文字堆砌是最常见的失误);内容单薄则按「视觉平衡」的出路增密或合并。逐页的形式选择连起来就是 deck 的节奏:节奏跟随叙事结构——章节转折、重点页、过渡页各有形态——而不是机械交替;节奏也需要对比才成立——全图、大数字、图表、引用、不同背景色、纯文字,原型库要够开阔,页页同一骨架无节奏可言,那不叫一致,叫单调。用版式和可视化把画布用满不是「填充性内容」;凭空编造数据和板块才是。
### 素材与工艺
- **字号与单位。** 使用大号字体(标题至少 48px。当用户指定具体字号时默认他们说的是**磅points**PowerPoint/Keynote 的单位)而非像素——用 `px = pt × 1.333` 换算。所以"把标题设成 36pt" → 在 CSS 里设成约 48px。
- **素材来源。** 除非用户要求,绝不使用 emoji。使用 design system / 品牌中的图标、用户提供的图片,或图片生成工具产出的图片。
- **图片呈现。** 务必先查看图片,再决定最佳展示方式。
- 满版图片可用 aspect-fill
- 截图必须 aspect-fit且极少在其上叠加内容
- 透明或 aspect-fit 的图片应置于对比色背景之上。
在图片上叠加文字时,参照品牌惯常做法:根据你在其他地方看到的样式,酌情使用卡片、保护渐变或模糊效果。
- **图表与数据可视化。** 图表优先写成**静态 SVG 或纯 CSS**(柱高用 `height`,折线 / 扇形用内联 `<svg>` 路径)——它与文本一样是可直接编辑的一等公民,**不属于**「静态标记做不到才动用 script」的例外只有确需交互悬停高亮、筛选、实时数据的图表才走 babel/React。数字之间只要存在能被眼睛读出的关系趋势、占比、对比、分布就转成图表而不是原样铺成文字。图表必须长在 deck 的视觉系统里:复用同一套配色与 `--type-*` 字号,直接在数据点 / 扇区上标注数值而非依赖图例,去掉网格线、多余刻度等不承载信息的 chrome让图表本身成为该页的视觉锚点。
- **动效。** 动效服务于叙事——引导视线、分层揭示信息、平滑衔接页面——而不是炫技或填空。默认克制始终以不干扰阅读为底线。deck 动效的形态是**翻到该页时播放一次的入场 / 分步揭示**,不做环境循环——无限循环的装饰动画会持续争夺注意力。实现用 CSS 动画(幻灯片保持可直编的静态 HTML两条契约细节见 deck-stage.js 头部 Authoring guidance
- 动画门控在 `[data-deck-active]``prefers-reduced-motion: no-preference` 上——组件在激活页维护该属性,翻页即触发;需要 JS 编排时监听组件的 `slidechange` 事件。**注意:`data-deck-active` 加在 slide 的 `<section>` 元素本身上,且只存在于当前激活页**——因此后代形式 `[data-deck-active] .fade-up` 天然只命中当前页内的元素,**不需要再按页类限定选择器**;每页不同的编排用不同的动画类 / delay 变量放在元素上表达。确需按页限定时,属性和页类是同一个元素,必须连写不能加空格:`section.s1[data-deck-active] h1` ✅,`[data-deck-active] .s1 h1` ❌(`.s1` 就是 slide 自己,后代组合器永远匹配不到,动画整页失效)。
- 基础样式写**可见的最终态**,隐藏态只进 `@keyframes``from`——缩略图栏、reduced-motion 等场景只渲染静态基础态、从不播动画,把 `opacity: 0` 写在基础规则上,会导致这些场景全成空白。
- 分步揭示 / 逐项渐入delay 作为内联变量放在元素上、规则里统一引用——`<div class="card-in" style="--d:.15s">` + `animation: fadeUp .5s both; animation-delay: var(--d, 0s)`,不要按元素序号硬编码选择器。`both` 不可省:它让带 delay 的元素在等待期停在 `from` 的隐藏态;省掉会先以终态闪现、再跳回隐藏重播一遍。
- **结构件。** 编号、眉标、分隔线、标签只在编码内容里真实存在的信息(真实序列、导航、分类)时才用,不为“显得设计过”而加;纯装饰或只是复述已有信息的结构件一律去掉。
## 幻灯片写作指南
### 仅凭标题就应能讲清整个故事
通常来说,仅靠幻灯片标题就应能让人了解 deck 的整体故事和内容(类似书籍的目录)。
幻灯片标题一般有以下几种结构类型:
- 简短的教科书式标题,全部大写(如 Market Research、Engagement Overview、Team Structure
- 行动式标题,更接近短句(如 "Asia is our largest market…."、"...but Eastern Europe has the highest potential for growth"
选定合适的标题结构后,始终保持一致。
### 避免暴露 AI 生成痕迹的 “AI 味”
避免以下常见的 “AI 味”——它们会暴露这个 deck 是 AI 生成的:
- AI 倾向于写出"宣判式"的标题和要点总结,过度戏剧化/简化,无缘由地制造张力(经典的 "It's not X. It's Y."),使用强祈使句,过度重新包装概念,或刻意悬念、故作洞察。
- 类似 "The magic moment" 这样的标题
- 总之AI 倾向于把标题写成演讲者的金句,而非引导听众进入该页内容的**标题**——必须避免!
## 规划步骤
在常规规划之外,务必完成以下步骤:
1. 受众、品牌风格推不出且承重时先提问;能从主题和材料推断的,带着假设直接进入大纲。
2. 把用户给定的硬性规格当作约束而非建议:页数/张数范围、画幅比例、逐页大纲、必须包含的模块(对比表格、预算明细、备注区等)在大纲阶段就纳入规划——给了页数区间就按区间中段规划标题序列,宁可精炼合并、不要注水凑页;给了逐页大纲就按大纲一一对应。构建完成后逐条对照自查。
3. 写出完整的标题序列。选择**一种**语法风格(例如短主题名词短语或简短陈述句),确保适合内容,并用该风格写出每一个标题。回头通读一遍,判断一个人**仅凭标题**能否跟上整个演示的脉络。标题应像书的章节——用直白的语言告诉读者接下来是什么。审阅这些标题并按需修订。将它们写入 scratchpad.md 文件。
4. 在 scratchpad.md 里为每张幻灯片标注**版式原型**(全图 / 大数字 / 图表 / 表格 / 引用 / 多栏卡片 / 纯文字……)与**视觉锚点**(这页视线的第一落点)。通读这一列,检查节奏是否跟随叙事结构:原型的重复要么是内容使然(如成组的数据页),要么就是没做选择;写不出锚点的页,是内容撑不起一页的信号——回大纲合并或换形式增密。
5. 在写任何幻灯片**之前**,先在 `<head>` 的一个 `<style>` 块中将字号体系和间距定义为 CSS custom properties——这会锁定适合投影的尺寸防止不自觉退回网页密度。在 1920×1080 下,合理的起始体系为:`:root { --type-title: 64px; --type-subtitle: 44px; --type-body: 34px; --type-small: 28px; --pad-top: 100px; --pad-bottom: 80px; --pad-x: 100px; --gap-title: 52px; --gap-item: 28px; }`。在 1280×720 下,按 ~0.67 缩放。所有地方都引用这些变量——每个 font-size 都用 `--type-*` 变量,每个 padding/gap 都用 `--pad-*``--gap-*` 变量,通过 inline style 或 class 规则中的 `var(…)` 引用。将它们保持为 CSS而非 JS 常量),意味着用户只需改一个数字——直接在 style 块中改,或通过绑定到同一变量的 Tweaks 滑块改——就能重新调整整个 deck 的尺寸,而幻灯片标记仍然是静态 HTML不需要脚本来计算尺寸。显式的 `--pad-bottom` 为每张幻灯片底部预留呼吸空间那个留白是结构性的不是空的。网页默认值body 14-16px、padding 48-72px对幻灯片太小如果数值让你觉得不够大方那就是还不够。如果你用了小于 24px 的尺寸你的校验器validator会抛出错误。
6. 构建幻灯片,牢记每张幻灯片既是设计练习也是文案练习。在版式、文字内容和语调方面给予每张幻灯片应有的关注。遵循上述原则,确保每张幻灯片能独立成立;一个只看这一页的人,应当无需其他上下文就能理解其高层含义。
## 验证要点
审阅时,用幻灯片构图规则——而非网页布局直觉——来检查截图。底部留白是不是缺陷,用「留白 ≠ 空洞」的归属判据:内容自身完整、下方是无边框的整块呼吸空间,这是正确的幻灯片构图——不要出于网页直觉把 `flex-start` 改成 `center`;空白被元素边界圈占的,是被动空洞,按「视觉平衡」的出路修。
还需验证:
- 页数/张数、画幅比例与用户给定的硬性规格一致;用户点名要求的模块(对比表格、预算明细、备注区等)逐条在场
- 字号是否匹配你的 `--type-*` 体系(而非网页密度)
- 幻灯片边距是否匹配你的 `--pad-*` 值(而非网页紧凑间距)
- 标题在各幻灯片间的平行性
- 没有使用 accent-border 卡片或 takeaway box
- 没有内容被画幅边缘裁切、显示不全
- 没有元素相互压叠、遮挡到读不清
- 没有被动空洞:边框 / 底色圈出的范围与其内容相称
- 页面视觉重量在画布上分布均衡,没有大片区域读成「缺了东西」
- 每页能指出视觉锚点;版式原型的重复经得起「内容使然还是没做选择」的追问
- 带动效的元素在缩略图栏和打印视图下完整可见(基础样式即最终态,隐藏态只在 keyframes 的 `from` 里)
- 实际翻页确认入场动画会播放;逐条检查动画选择器——凡按页限定的,`data-deck-active` 与页选择器必须连写(`section.s1[data-deck-active] h1`),写成后代形式(`[data-deck-active] .s1 h1`)该页动效全部失效

View File

@@ -0,0 +1,82 @@
---
name: visual-exposure
metadata:
display-names:
zh-CN: 可视化报告
en-US: Visual Report
description: 用于制作可视化报告、专题视觉页、信息图、视觉长图、概念可视化、产品能力曝光、方案亮点展示等内容型 HTML 视觉作品。适合用户想把材料、数据或观点组织成可阅读、可展示、可传播的视觉化表达,但不希望做成 PPT、传统 dashboard 或纯 ECharts 图表的场景。触发词:可视化报告, 视觉报告, 可视化曝光, 视觉化曝光, 信息图, 长图, infographic, 视觉表达, 概念可视化, 亮点展示, 能力曝光
available-agents:
- CreativeDesign
---
# 可视化报告与专题表达
创建内容驱动的 HTML 视觉作品。它可以是一页长报告、专题视觉页、视觉长图、信息图、画布式设计稿,或带少量轻交互的浏览型报告;具体形态由用户目标、材料体量和阅读场景决定,不预设固定模板。
## 工作方式
1. 先读用户材料,提取主题、受众、阅读场景、核心结论、必须出现的事实和可省略的细节。
2. 判断报告目的:汇报、解释、披露、说服、传播、留档,还是做视觉方向探索。
3. 选择交付形态:长页报告、专题页、视觉长图、单屏摘要、画布式多方案、图文混排报告、偏打印感的正式报告等。不要把所有需求压成同一种版式。
4. 按材料逻辑组织内容,而不是套固定目录、固定模块或固定视觉模板。参考样式只能启发表达方式,不能替代对当前材料的判断。
5. 把材料拆成具体阅读任务:这一段要让读者完成什么判断、理解什么关系、记住什么事实、比较什么差异、追踪什么过程、相信什么证据。不要把这些任务名直接变成目录或模块标题。
6. 为每个阅读任务现场生成合适的组件、视觉和布局:先说明这段内容需要什么表达方式,再落成具体 UI / 图形 / 排版 / 图表 / 截图 / 文字组合。可以创造新的结构和视觉隐喻,不受现有组件名限制;避免所有章节共享同一套组件组合。
7. 先写风格 brief主题隐喻、受众姿态、材料语言、配色逻辑和签名元素。财务报告可以像正式报告册员工调研可以像组织研究档案产品上市总结可以像品牌战报这些只是启发必须从用户材料里推导。
8. 建立版式系统:画幅、栅格、字号层级、颜色、图标/线条语言、强调方式和章节节奏。版式系统必须说明不同章节如何变化,而不是所有章节都用同一种上下结构。
9. 产出单个 HTML 文档。用户需求明确时直接做;只有主题、素材或交付形态完全无法判断时,才问少量必要问题。
## 内容组织
本 skill 中出现的报告形态、表达方式、组件和版式都只是示意,不是必须参考的清单。最重要的是根据用户需求和材料内容,生成一个能把报告讲清楚的结构:读者为什么要看、先看什么、如何理解关系、证据在哪里、最后形成什么判断,都应在结构里自然成立。
可视化报告不是把图表排满,也不是把文字切成很多卡片。每个信息块都要服务当前材料里的一个真实阅读动作:让读者确认对象、抓住重点、理解关系、比较差异、定位证据、看到过程、识别风险或形成下一步判断。把这些阅读动作翻译成本次需求专属的视觉结构,而不是复用固定模块名。
允许为当前需求重新发明表达结构:可以合并、拆分、放大、弱化、横向展开、纵向叙事、图文化、表格化、截图化或做成完全不同的布局。只要它能更清楚地解释报告内容,就优先于任何示例组件或常见版式。
如果材料很长,先压缩成报告叙事,不要把原文完整铺上去。需要精确查数时使用表格或附录;需要快速传播时使用摘要和视觉重点;需要正式汇报时保留章节编号、图表标题和口径说明。
不要把关键内容压成角落里的附录片段。用户明确要求展示的部分,应按报告目标给足版面权重,并选择合适的信息结构承载。
## 版式策略
可视化报告要像一份经过编辑设计的专题,而不是由同款卡片拼起来的长页面。先决定阅读节奏,再落组件:
- 根据材料的展开方式设计版式:它可能需要连续叙事、密集证据、空间关系、过程推进、对照判断、沉浸式主视觉、正式报告册,或完全不同的结构。先为当前需求命名一个版式概念,再确定栅格、密度、视觉重心和章节变化。
- 版式变化来自内容关系,不来自凑组件。关键段落可以被放大、拆页、满版化、图文化或变成精确表格;次要段落可以压缩、并列、收进注释或弱化。
- 每个章节的结构可以不同,但要属于同一套视觉系统。变化要能解释:为什么这里适合宽图、那里适合密集表格、另一处适合分段叙事。
不要为了“丰富”而乱放装饰。变化应该来自内容关系和阅读任务,而不是从组件清单里凑满页面。
## 视觉原则
- 优先清楚,其次好看。读者应该先理解结构,再感受到风格。
- 明暗主题由需求、品牌、素材、受众和阅读场景决定;浅色、暗色、中性或局部深色都可以。选择后要保证对比度、可读性和信息层级,并能解释为什么适合当前主题。
- 默认平面化处理:内容区优先使用细边框、分隔线、浅底色、色块、表格斑马纹、编号和标签建立层级;不要给章节、卡片、图表容器加各种 `box-shadow`
- 少用装饰性渐变、发光、玻璃拟态。视觉效果要帮助分组、强调或引导视线。
- 风格跟随内容、受众和品牌:可以正式、温和、技术、编辑化、品牌化或实验感,但不要从某个样例场景继承固定颜色、固定目录或固定组件。
- 每份报告应有一个可解释的签名元素。签名元素要从用户主题、材料质感和阅读任务中生成,而不是复用固定手法;它可以是任何能组织内容、建立记忆点并保持一致性的视觉规则。
- 真实素材优先用户给的截图、logo、图片、图标、数据片段要优先使用。没有素材时用清楚的占位结构和可替换文案。
- 允许少量动效,但只用于进入、强调或引导阅读,不做干扰理解的持续动画。
- 可以包含数字、图表和表格,但它们服务于报告叙事;不要为了“可视化”而把所有内容都做成图。
- 深色区域可以用于封面、结论、行动区或整篇报告的主视觉;只要它服务主题气质和阅读体验,而不是作为无依据的装饰。
## 画布与交付
- 多方案、设计稿、方向探索:使用 `design-canvas.jsx`,每个方向一个 `<DCArtboard>`
- 单一可视化报告、视觉长图或专题视觉稿:做成完整 HTML 页面,保持明确画幅、节奏和层级。
- 如果用户要“设计稿”,优先走画布式交付;如果用户要“可直接展示/传播”,可以做成完整页面式视觉作品。
- 所有文字应直接写在 HTML 中,便于用户后续编辑。
## 检查清单
- 交付形态匹配用户需求:长页报告、专题页、长图、画布设计稿或单屏摘要,而不是被固定模板绑住。
- 当前需求的主题、边界和最重要信息在第一屏或开篇清楚可见。
- 章节顺序跟随材料逻辑,不按评测集样例或预设场景套目录。
- 章节版式有节奏变化,并且变化来自材料关系;没有一路同款上下卡片,也没有因为预设组件清单而硬凑结构。
- 没有大面积空白、错位、低对比、文字不可读或模块之间风格突兀。
- 内容区保持平面化,没有滥用阴影、发光、玻璃拟态或厚重悬浮效果。
- 所有表达载体各司其职,没有为了数据而堆图,也没有用空泛文字或预设组件填空间。
- 文字密度可读,没有小字堆叠。
- 图标、线条、颜色和卡片样式属于同一套视觉语言。
- 明暗选择能解释为什么适合这个主题;无论浅色还是暗色,都保证长文、图表和表格可读。
- 事实性内容没有编造;不确定内容用中性描述或占位说明。

View File

@@ -0,0 +1,14 @@
---
name: wireframe
metadata:
display-names:
zh-CN: 线框图
en-US: Wireframe
description: 用线框图和故事板探索多种想法。触发词wireframe, storyboard, 线框图, 故事板, 分镜, 草图, 低保真, 方案探索, 设计探索
available-agents:
- CreativeDesign
---
# 线框图
帮助用户快速探索设计想法。提问遵循 [`../creative-design.md`](../creative-design.md)「提问」一节:关键信息缺失且承重时先做一轮聚焦提问,否则基于合理假设直接铺方案。生成多个粗略的线框图,在锁定方向之前把设计空间勾勒出来。优先追求广度而非精细打磨:默认每个想法给出 2-3 种明显不同的方案,用户明确要求广度探索时再加。用简单的形状、占位文字和极少的颜色,把焦点留在结构和流程上。整体保持手绘草图的感觉——手写风格但清晰可读的字体;以黑白为主、点缀少量颜色;低保真、简洁。多方案默认铺进 `design-canvas.jsx` 画布(见 [`../creative-design.md`](../creative-design.md)「如何开展设计工作」);单个 artboard 内部的局部变体用 Tweaks 承载(用 `tweaks-panel.jsx`,见 [`../creative-design.md`](../creative-design.md)「Tweaks」不要手写控件面板

View File

@@ -0,0 +1,188 @@
/* BEGIN USAGE */
// Android.jsx — Simplified Android (Material 3) device frame
// Status bar + content + gesture nav + keyboard.
// Based on Figma M3 spec. No dependencies, no image assets.
// Exports (to window): AndroidDevice, AndroidStatusBar, AndroidListItem, AndroidNavBar, AndroidKeyboard
//
// Usage — wrap your screen content in <AndroidDevice> to get the bezel, status
// bar and gesture nav (props: width=412, height=892, dark, keyboard):
//
// <AndroidDevice>
// ...your screen content...
// </AndroidDevice>
// <AndroidDevice dark keyboard>…</AndroidDevice>
// <AndroidDevice width={360} height={800}>…</AndroidDevice> // smaller device size
/* END USAGE */
const MD_C = {
surface: '#f4fbf8',
surfaceVariant: '#dae5e1',
inverseOnSurface: '#ecf2ef',
secondaryContainer: '#cde8e1',
primaryFixedDim: '#83d5c6',
onSurface: '#171d1b',
onSurfaceVar: '#49454f',
onPrimaryContainer: '#00201c',
primary: '#006a60',
frameBorder: 'rgba(116,119,117,0.5)',
};
// ─────────────────────────────────────────────────────────────
// Status bar (time left, wifi/cell/battery right)
// ─────────────────────────────────────────────────────────────
function AndroidStatusBar({ dark = false }) {
const c = dark ? '#fff' : MD_C.onSurface;
return (
<div style={{
height: 40, display: 'flex', alignItems: 'center',
justifyContent: 'space-between', padding: '0 16px',
position: 'relative',
fontFamily: 'Roboto, system-ui, sans-serif',
}}>
{/* time left */}
<div style={{ width: 128, display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ fontSize: 14, fontWeight: 400, letterSpacing: 0.25, lineHeight: '20px', color: c }}>9:30</span>
</div>
{/* camera punch-hole (center) */}
<div style={{
position: 'absolute', left: '50%', top: 8, transform: 'translateX(-50%)',
width: 24, height: 24, borderRadius: 100, background: '#2e2e2e',
}} />
{/* status icons right */}
<div style={{ display: 'flex', alignItems: 'center' }}>
<div style={{ display: 'flex', paddingRight: 2 }}>
<svg width="16" height="16" viewBox="0 0 16 16" style={{ marginRight: -2 }}>
<path d="M8 13.3L.67 5.97a10.37 10.37 0 0114.66 0L8 13.3z" fill={c}/>
</svg>
<svg width="16" height="16" viewBox="0 0 16 16" style={{ marginRight: -2 }}>
<path d="M14.67 14.67V1.33L1.33 14.67h13.34z" fill={c}/>
</svg>
</div>
<svg width="16" height="16" viewBox="0 0 16 16">
<rect x="3.75" y="2" width="8.5" height="13" rx="1.5" fill={c}/>
<rect x="5.5" y="0.9" width="5" height="2" rx="0.5" fill={c}/>
</svg>
</div>
</div>
);
}
// ─────────────────────────────────────────────────────────────
// List item (Material 3)
// ─────────────────────────────────────────────────────────────
function AndroidListItem({ headline, supporting, leading }) {
return (
<div style={{
display: 'flex', alignItems: 'center', gap: 16,
padding: '12px 16px', minHeight: 56, boxSizing: 'border-box',
fontFamily: 'Roboto, system-ui, sans-serif',
}}>
{leading && (
<div style={{
width: 40, height: 40, borderRadius: '50%',
background: MD_C.primary, color: '#fff',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 18, fontWeight: 500, flexShrink: 0,
}}>{leading}</div>
)}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 16, color: MD_C.onSurface, lineHeight: '24px' }}>{headline}</div>
{supporting && (
<div style={{ fontSize: 14, color: MD_C.onSurfaceVar, lineHeight: '20px' }}>{supporting}</div>
)}
</div>
</div>
);
}
// ─────────────────────────────────────────────────────────────
// Gesture nav bar (pill)
// ─────────────────────────────────────────────────────────────
function AndroidNavBar({ dark = false }) {
return (
<div style={{
height: 24, display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
<div style={{
width: 108, height: 4, borderRadius: 2,
background: dark ? '#fff' : MD_C.onSurface, opacity: 0.4,
}} />
</div>
);
}
// ─────────────────────────────────────────────────────────────
// Device frame — wraps everything
// ─────────────────────────────────────────────────────────────
function AndroidDevice({
children, width = 412, height = 892, dark = false,
keyboard = false,
}) {
return (
<div style={{
width, height, borderRadius: 18, overflow: 'hidden',
background: dark ? '#1d1b20' : MD_C.surface,
border: `8px solid ${MD_C.frameBorder}`,
display: 'flex', flexDirection: 'column', boxSizing: 'border-box',
}}>
<AndroidStatusBar dark={dark} />
<div style={{ flex: 1, overflow: 'auto' }}>
{children}
</div>
{keyboard && <AndroidKeyboard />}
<AndroidNavBar dark={dark} />
</div>
);
}
// ─────────────────────────────────────────────────────────────
// Keyboard — Gboard (Material 3)
// ─────────────────────────────────────────────────────────────
function AndroidKeyboard() {
let _k = 0;
const key = (l, { flex = 1, bg = MD_C.surface, r = 6, minW, fs = 21 } = {}) => (
<div key={_k++} style={{
height: 46, borderRadius: r, flex, minWidth: minW,
background: bg, display: 'flex', alignItems: 'center', justifyContent: 'center',
fontFamily: 'Roboto, system-ui', fontSize: fs,
color: MD_C.onPrimaryContainer,
}}>{l}</div>
);
const row = (keys, style = {}) => (
<div style={{ display: 'flex', gap: 6, justifyContent: 'center', ...style }}>
{keys.map(l => key(l))}
</div>
);
return (
<div style={{
background: MD_C.inverseOnSurface, padding: '0 8px 8px',
display: 'flex', flexDirection: 'column', gap: 4,
}}>
{/* navbar spacer (icons omitted) */}
<div style={{ height: 44 }} />
{/* key rows */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{row(['q','w','e','r','t','y','u','i','o','p'])}
{row(['a','s','d','f','g','h','j','k','l'], { padding: '0 20px' })}
<div style={{ display: 'flex', gap: 6 }}>
{key('', { bg: MD_C.surfaceVariant })}
<div style={{ display: 'flex', gap: 6, flex: 7, minWidth: 274 }}>
{['z','x','c','v','b','n','m'].map(l => key(l))}
</div>
{key('', { bg: MD_C.surfaceVariant })}
</div>
<div style={{ display: 'flex', gap: 6 }}>
{key('?123', { bg: MD_C.secondaryContainer, r: 100, minW: 58, fs: 14 })}
{key(',', { bg: MD_C.surfaceVariant })}
{key('', { flex: 3, minW: 154 })}
{key('.', { bg: MD_C.surfaceVariant })}
{key('', { bg: MD_C.primaryFixedDim, r: 100, minW: 58 })}
</div>
</div>
</div>
);
}
Object.assign(window, {
AndroidDevice, AndroidStatusBar, AndroidListItem, AndroidNavBar, AndroidKeyboard,
});

View File

@@ -0,0 +1,773 @@
/* BEGIN USAGE */
// animations.jsx
// Reusable animation starter: Stage, Timeline, Sprite, easing helpers.
// Exports (to window): Stage, Sprite, PlaybackBar, TextSprite, ImageSprite, RectSprite,
// useTime, useTimeline, useSprite, Easing, interpolate, animate, clamp.
//
// Usage (in an HTML file that loads React + Babel):
//
// <Stage width={1280} height={720} duration={10} background="#f6f4ef">
// <MyScene />
// </Stage>
//
// <Stage> auto-scales to the viewport and provides the scrubber, play/pause,
// ←/→ seek, space, and 0-to-reset controls, and persists the playhead.
// Set the optional `poster` prop (seconds) to the moment your opening scene is
// fully composed — the product thumbnail freezes on that frame (default ~1s).
// Inside <Stage>, any child can call useTime() to read the current
// playhead (seconds). Or wrap content in <Sprite start={1} end={4}>...</Sprite>
// to only render during that window -- children receive a `localTime` and
// `progress` via the useSprite() hook. Use Easing + interpolate()/animate()
// for tweens; TextSprite / ImageSprite / RectSprite have built-in entry/exit.
// Build YOUR scenes by composing Sprites inside a Stage.
/* END USAGE */
// ─────────────────────────────────────────────────────────────────────────────
// ── Easing functions (hand-rolled, Popmotion-style) ─────────────────────────
// All easings take t ∈ [0,1] and return eased t ∈ [0,1] (may overshoot for back/elastic).
const Easing = {
linear: (t) => t,
// Quad
easeInQuad: (t) => t * t,
easeOutQuad: (t) => t * (2 - t),
easeInOutQuad: (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t),
// Cubic
easeInCubic: (t) => t * t * t,
easeOutCubic: (t) => (--t) * t * t + 1,
easeInOutCubic: (t) => (t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1),
// Quart
easeInQuart: (t) => t * t * t * t,
easeOutQuart: (t) => 1 - (--t) * t * t * t,
easeInOutQuart: (t) => (t < 0.5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t),
// Expo
easeInExpo: (t) => (t === 0 ? 0 : Math.pow(2, 10 * (t - 1))),
easeOutExpo: (t) => (t === 1 ? 1 : 1 - Math.pow(2, -10 * t)),
easeInOutExpo: (t) => {
if (t === 0) return 0;
if (t === 1) return 1;
if (t < 0.5) return 0.5 * Math.pow(2, 20 * t - 10);
return 1 - 0.5 * Math.pow(2, -20 * t + 10);
},
// Sine
easeInSine: (t) => 1 - Math.cos((t * Math.PI) / 2),
easeOutSine: (t) => Math.sin((t * Math.PI) / 2),
easeInOutSine: (t) => -(Math.cos(Math.PI * t) - 1) / 2,
// Back (overshoot)
easeOutBack: (t) => {
const c1 = 1.70158, c3 = c1 + 1;
return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);
},
easeInBack: (t) => {
const c1 = 1.70158, c3 = c1 + 1;
return c3 * t * t * t - c1 * t * t;
},
easeInOutBack: (t) => {
const c1 = 1.70158, c2 = c1 * 1.525;
return t < 0.5
? (Math.pow(2 * t, 2) * ((c2 + 1) * 2 * t - c2)) / 2
: (Math.pow(2 * t - 2, 2) * ((c2 + 1) * (t * 2 - 2) + c2) + 2) / 2;
},
// Elastic
easeOutElastic: (t) => {
const c4 = (2 * Math.PI) / 3;
if (t === 0) return 0;
if (t === 1) return 1;
return Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * c4) + 1;
},
};
// ── Core interpolation helpers ──────────────────────────────────────────────
// Clamp a value to [min, max]
const clamp = (v, min, max) => Math.max(min, Math.min(max, v));
// interpolate([0, 0.5, 1], [0, 100, 50], ease?) -> fn(t)
// Popmotion-style: linearly maps t across input keyframes to output values,
// with optional easing per segment (single fn or array of fns).
function interpolate(input, output, ease = Easing.linear) {
return (t) => {
if (t <= input[0]) return output[0];
if (t >= input[input.length - 1]) return output[output.length - 1];
for (let i = 0; i < input.length - 1; i++) {
if (t >= input[i] && t <= input[i + 1]) {
const span = input[i + 1] - input[i];
const local = span === 0 ? 0 : (t - input[i]) / span;
const easeFn = Array.isArray(ease) ? (ease[i] || Easing.linear) : ease;
const eased = easeFn(local);
return output[i] + (output[i + 1] - output[i]) * eased;
}
}
return output[output.length - 1];
};
}
// animate({from, to, start, end, ease})(t) — simpler single-segment tween.
// Returns `from` before `start`, `to` after `end`.
function animate({ from = 0, to = 1, start = 0, end = 1, ease = Easing.easeInOutCubic }) {
return (t) => {
if (t <= start) return from;
if (t >= end) return to;
const local = (t - start) / (end - start);
return from + (to - from) * ease(local);
};
}
// ── Timeline context ────────────────────────────────────────────────────────
const TimelineContext = React.createContext({ time: 0, duration: 10, playing: false });
const useTime = () => React.useContext(TimelineContext).time;
const useTimeline = () => React.useContext(TimelineContext);
// ── Sprite ──────────────────────────────────────────────────────────────────
// Renders children only when the playhead is inside [start, end]. Provides
// a sub-context with `localTime` (seconds since start) and `progress` (0..1).
//
// <Sprite start={2} end={5}>
// {({ localTime, progress }) => <Thing x={progress * 100} />}
// </Sprite>
//
// Or as a plain wrapper — children can call useSprite() themselves.
const SpriteContext = React.createContext({ localTime: 0, progress: 0, duration: 0 });
const useSprite = () => React.useContext(SpriteContext);
function Sprite({ start = 0, end = Infinity, children, keepMounted = false }) {
const { time } = useTimeline();
const visible = time >= start && time <= end;
if (!visible && !keepMounted) return null;
const duration = end - start;
const localTime = Math.max(0, time - start);
const progress = duration > 0 && isFinite(duration)
? clamp(localTime / duration, 0, 1)
: 0;
const value = { localTime, progress, duration, visible };
return (
<SpriteContext.Provider value={value}>
{typeof children === 'function' ? children(value) : children}
</SpriteContext.Provider>
);
}
// ── Sample sprite components ────────────────────────────────────────────────
// TextSprite: fades/slides text in on entry, holds, then fades out on exit.
// Props: text, x, y, size, color, font, entryDur, exitDur, align
function TextSprite({
text,
x = 0, y = 0,
size = 48,
color = '#111',
font = 'Inter, system-ui, sans-serif',
weight = 600,
entryDur = 0.45,
exitDur = 0.35,
entryEase = Easing.easeOutBack,
exitEase = Easing.easeInCubic,
align = 'left',
letterSpacing = '-0.01em',
}) {
const { localTime, duration } = useSprite();
const exitStart = Math.max(0, duration - exitDur);
let opacity = 1;
let ty = 0;
if (localTime < entryDur) {
const t = entryEase(clamp(localTime / entryDur, 0, 1));
opacity = t;
ty = (1 - t) * 16;
} else if (localTime > exitStart) {
const t = exitEase(clamp((localTime - exitStart) / exitDur, 0, 1));
opacity = 1 - t;
ty = -t * 8;
}
const translateX = align === 'center' ? '-50%' : align === 'right' ? '-100%' : '0';
return (
<div style={{
position: 'absolute',
left: x, top: y,
transform: `translate(${translateX}, ${ty}px)`,
opacity,
fontFamily: font,
fontSize: size,
fontWeight: weight,
color,
letterSpacing,
whiteSpace: 'pre',
lineHeight: 1.1,
willChange: 'transform, opacity',
}}>
{text}
</div>
);
}
// ImageSprite: scales + fades in; optional Ken Burns drift during hold.
function ImageSprite({
src,
x = 0, y = 0,
width = 400, height = 300,
entryDur = 0.6,
exitDur = 0.4,
kenBurns = false,
kenBurnsScale = 1.08,
radius = 12,
fit = 'cover',
placeholder = null, // {label: string} for striped placeholder
}) {
const { localTime, duration } = useSprite();
const exitStart = Math.max(0, duration - exitDur);
let opacity = 1;
let scale = 1;
if (localTime < entryDur) {
const t = Easing.easeOutCubic(clamp(localTime / entryDur, 0, 1));
opacity = t;
scale = 0.96 + 0.04 * t;
} else if (localTime > exitStart) {
const t = Easing.easeInCubic(clamp((localTime - exitStart) / exitDur, 0, 1));
opacity = 1 - t;
scale = (kenBurns ? kenBurnsScale : 1) + 0.02 * t;
} else if (kenBurns) {
const holdSpan = exitStart - entryDur;
const holdT = holdSpan > 0 ? (localTime - entryDur) / holdSpan : 0;
scale = 1 + (kenBurnsScale - 1) * holdT;
}
const content = placeholder ? (
<div style={{
width: '100%', height: '100%',
display: 'flex', alignItems: 'center', justifyContent: 'center',
background: 'repeating-linear-gradient(135deg, #e9e6df 0 10px, #dcd8cf 10px 20px)',
color: '#6b6458',
fontFamily: 'JetBrains Mono, ui-monospace, monospace',
fontSize: 13,
letterSpacing: '0.04em',
textTransform: 'uppercase',
}}>
{placeholder.label || 'image'}
</div>
) : (
<img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: fit, display: 'block' }} />
);
return (
<div style={{
position: 'absolute',
left: x, top: y,
width, height,
opacity,
transform: `scale(${scale})`,
transformOrigin: 'center',
borderRadius: radius,
overflow: 'hidden',
willChange: 'transform, opacity',
}}>
{content}
</div>
);
}
// RectSprite: simple rectangle that animates position/size/color via props.
// Useful demo primitive — takes a `render` fn for per-frame customization.
function RectSprite({
x = 0, y = 0,
width = 100, height = 100,
color = '#111',
radius = 8,
entryDur = 0.4,
exitDur = 0.3,
render, // optional: (ctx) => style overrides
}) {
const spriteCtx = useSprite();
const { localTime, duration } = spriteCtx;
const exitStart = Math.max(0, duration - exitDur);
let opacity = 1;
let scale = 1;
if (localTime < entryDur) {
const t = Easing.easeOutBack(clamp(localTime / entryDur, 0, 1));
opacity = clamp(localTime / entryDur, 0, 1);
scale = 0.4 + 0.6 * t;
} else if (localTime > exitStart) {
const t = Easing.easeInQuad(clamp((localTime - exitStart) / exitDur, 0, 1));
opacity = 1 - t;
scale = 1 - 0.15 * t;
}
const overrides = render ? render(spriteCtx) : {};
return (
<div style={{
position: 'absolute',
left: x, top: y,
width, height,
background: color,
borderRadius: radius,
opacity,
transform: `scale(${scale})`,
transformOrigin: 'center',
willChange: 'transform, opacity',
...overrides,
}} />
);
}
function Stage({
width = 1280,
height = 720,
duration = 10,
background = '#f6f4ef',
fps = 60,
loop = true,
autoplay = true,
poster = null,
persistKey = 'animstage',
children,
}) {
// Thumbnail capture mode: the host appends ?thumbnail=1 before screenshotting.
// Freeze on a representative still — the author-declared `poster` second, or
// ~1s as a fallback — paused, with the playback bar hidden, so the product
// thumbnail is a deterministic frame of the first composed scene.
const captureMode = typeof location !== 'undefined' && /[?&]thumbnail=/.test(location.search || '');
const [time, setTime] = React.useState(() => {
if (captureMode) return clamp(poster == null ? 1 : poster, 0, duration);
try {
const v = parseFloat(localStorage.getItem(persistKey + ':t') || '0');
return isFinite(v) ? clamp(v, 0, duration) : 0;
} catch { return 0; }
});
const [playing, setPlaying] = React.useState(captureMode ? false : autoplay);
const [scale, setScale] = React.useState(1);
const stageRef = React.useRef(null);
const canvasRef = React.useRef(null);
const rafRef = React.useRef(null);
const lastTsRef = React.useRef(null);
// Persist playhead
React.useEffect(() => {
try { localStorage.setItem(persistKey + ':t', String(time)); } catch {}
}, [time, persistKey]);
// Auto-scale to fit viewport
React.useEffect(() => {
if (!stageRef.current) return;
const el = stageRef.current;
const measure = () => {
const barH = captureMode ? 0 : 44; // playback bar height (hidden in capture mode)
const s = Math.min(
el.clientWidth / width,
(el.clientHeight - barH) / height
);
setScale(Math.max(0.05, s));
};
measure();
const ro = new ResizeObserver(measure);
ro.observe(el);
window.addEventListener('resize', measure);
return () => {
ro.disconnect();
window.removeEventListener('resize', measure);
};
}, [width, height]);
// Animation loop
React.useEffect(() => {
if (!playing) {
lastTsRef.current = null;
return;
}
const step = (ts) => {
if (lastTsRef.current == null) lastTsRef.current = ts;
const dt = (ts - lastTsRef.current) / 1000;
lastTsRef.current = ts;
setTime((t) => {
let next = t + dt;
if (next >= duration) {
if (loop) next = next % duration;
else { next = duration; setPlaying(false); }
}
return next;
});
rafRef.current = requestAnimationFrame(step);
};
rafRef.current = requestAnimationFrame(step);
return () => {
if (rafRef.current) cancelAnimationFrame(rafRef.current);
lastTsRef.current = null;
};
}, [playing, duration, loop]);
// Keyboard: space = play/pause, ← → = seek
React.useEffect(() => {
const onKey = (e) => {
if (e.target && (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA')) return;
if (e.code === 'Space') {
e.preventDefault();
setPlaying(p => !p);
} else if (e.code === 'ArrowLeft') {
setTime(t => clamp(t - (e.shiftKey ? 1 : 0.1), 0, duration));
} else if (e.code === 'ArrowRight') {
setTime(t => clamp(t + (e.shiftKey ? 1 : 0.1), 0, duration));
} else if (e.key === '0' || e.code === 'Home') {
setTime(0);
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [duration]);
const ctxValue = React.useMemo(
() => ({ time, duration, playing, setTime, setPlaying }),
[time, duration, playing]
);
return (
<div
ref={stageRef}
style={{
position: 'absolute', inset: 0,
display: 'flex', flexDirection: 'column',
alignItems: 'center',
background: '#0a0a0a',
fontFamily: 'Inter, system-ui, sans-serif',
}}
>
{/* Canvas area — vertically centered in remaining space */}
<div style={{
flex: 1,
width: '100%',
display: 'flex', alignItems: 'center', justifyContent: 'center',
overflow: 'hidden',
minHeight: 0,
}}>
<div
ref={canvasRef}
style={{
width, height,
background,
position: 'relative',
transform: `scale(${scale})`,
transformOrigin: 'center',
flexShrink: 0,
boxShadow: '0 20px 60px rgba(0,0,0,0.4)',
overflow: 'hidden',
}}
>
<TimelineContext.Provider value={ctxValue}>
{children}
</TimelineContext.Provider>
</div>
</div>
{/* Playback bar — stacked below canvas, never overlapping. Hidden in
capture mode so the thumbnail is just the frame, no chrome. */}
{!captureMode && (
<PlaybackBar
time={time}
duration={duration}
playing={playing}
onPlayPause={() => setPlaying(p => !p)}
onReset={() => { setTime(0); }}
onSeek={(t) => setTime(t)}
/>
)}
</div>
);
}
// ── Playback bar ────────────────────────────────────────────────────────────
// Play/pause, return-to-begin, scrub track, time display.
// Uses fixed-width time fields so layout doesn't thrash.
function PlaybackBar({ time, duration, playing, onPlayPause, onReset, onSeek }) {
const trackRef = React.useRef(null);
const [dragging, setDragging] = React.useState(false);
const [trackHover, setTrackHover] = React.useState(null); // { x, t } — px within track + hovered time
const posFromEvent = React.useCallback((e) => {
const rect = trackRef.current.getBoundingClientRect();
const x = clamp(e.clientX - rect.left, 0, rect.width);
const t = rect.width > 0 ? (x / rect.width) * duration : 0;
return { x, t };
}, [duration]);
const onTrackMove = (e) => {
if (!trackRef.current) return;
const { x, t } = posFromEvent(e);
setTrackHover({ x, t });
if (dragging) onSeek(t);
};
const onTrackLeave = () => {
if (!dragging) setTrackHover(null);
};
const onTrackDown = (e) => {
const { x, t } = posFromEvent(e);
setDragging(true);
setTrackHover({ x, t });
onSeek(t);
};
// Grab the knob in place: begin dragging without seeking (no jump).
// stopPropagation keeps the track's click-to-seek from also firing.
const onBallDown = (e) => {
e.stopPropagation();
setDragging(true);
setTrackHover(posFromEvent(e));
};
React.useEffect(() => {
if (!dragging) return;
const prevCursor = document.body.style.cursor;
document.body.style.cursor = 'grabbing'; // stays grabbing even if the pointer leaves the knob mid-drag
const onUp = () => {
setDragging(false);
setTrackHover(null);
};
const onMove = (e) => {
if (!trackRef.current) return;
const { x, t } = posFromEvent(e);
setTrackHover({ x, t });
onSeek(t);
};
window.addEventListener('mouseup', onUp);
window.addEventListener('mousemove', onMove);
return () => {
window.removeEventListener('mouseup', onUp);
window.removeEventListener('mousemove', onMove);
document.body.style.cursor = prevCursor;
};
}, [dragging, posFromEvent, onSeek]);
const pct = duration > 0 ? (time / duration) * 100 : 0;
const fmt = (t) => {
const total = Math.max(0, t);
const m = Math.floor(total / 60);
const s = Math.floor(total % 60);
return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
};
const numFont = '"PingFang SC", -apple-system, BlinkMacSystemFont, system-ui, sans-serif';
return (
<div style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '12px',
background: 'linear-gradient(0deg, rgba(0, 0, 0, 0.30) 0%, rgba(0, 0, 0, 0.00) 100%)',
width: '100%',
color: '#fff',
fontFamily: numFont,
userSelect: 'none',
flexShrink: 0,
boxSizing: 'border-box',
}}>
{/* Play / pause — bare white triangle, no button chrome */}
<IconButton onClick={onPlayPause} tooltip={playing ? '暂停' : '播放'}>
{playing ? (
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M3.33333 1.33398C2.59695 1.33398 2 1.93094 2 2.66732V13.334C2 14.0704 2.59695 14.6673 3.33333 14.6673H4.66667C5.40305 14.6673 6 14.0704 6 13.334V2.66732C6 1.93094 5.40305 1.33398 4.66667 1.33398H3.33333Z" fill="currentColor"/>
<path d="M11.3333 1.33398C10.597 1.33398 10 1.93094 10 2.66732V13.334C10 14.0704 10.597 14.6673 11.3333 14.6673H12.6667C13.403 14.6673 14 14.0704 14 13.334V2.66732C14 1.93094 13.403 1.33398 12.6667 1.33398H11.3333Z" fill="currentColor"/>
</svg>
) : (
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.0489 9.13127C14.873 8.60116 14.873 7.39754 14.0489 6.86743L4.74461 0.882617C3.84764 0.305661 2.66699 0.948902 2.66699 2.01454V13.9842C2.66699 15.0498 3.84764 15.693 4.74461 15.1161L14.0489 9.13127Z" fill="currentColor"/>
</svg>
)}
</IconButton>
{/* Current time */}
<div style={{
fontFamily: numFont,
fontSize: 14,
fontWeight: 400,
fontVariantNumeric: 'tabular-nums',
color: '#fff',
minWidth: 40,
textAlign: 'center'
}}>
{fmt(time)}
</div>
{/* Scrub track — white fill on translucent-white rail + draggable knob */}
<div
ref={trackRef}
onMouseMove={onTrackMove}
onMouseLeave={onTrackLeave}
onMouseDown={onTrackDown}
style={{
flex: 1,
height: 20,
position: 'relative',
cursor: 'pointer',
display: 'flex', alignItems: 'center',
}}
>
<div style={{
position: 'absolute',
left: 0, right: 0, height: 4,
background: 'rgba(255,255,255,0.6)',
borderRadius: 2,
}}/>
<div style={{
position: 'absolute',
left: 0, width: `${pct}%`, height: 4,
background: 'rgba(255,255,255,0.9)',
borderRadius: 2,
}}/>
{/* Progress knob — outer div is an enlarged transparent hit area for easier grabbing */}
<div
onMouseDown={onBallDown}
style={{
position: 'absolute',
left: `${pct}%`, top: '50%',
transform: 'translate(-50%, -50%)',
width: 20, height: 20,
display: 'flex', alignItems: 'center', justifyContent: 'center',
cursor: dragging ? 'grabbing' : 'grab',
zIndex: 5,
}}
>
<div style={{
width: dragging ? 14 : 12,
height: dragging ? 14 : 12,
background: '#fff',
borderRadius: '50%',
border: '0.5px solid #D2D5D8',
boxShadow: '0 2px 6px rgba(0,0,0,0.35)',
transition: 'width 100ms, height 100ms',
}}/>
</div>
{trackHover && (
<div style={{
position: 'absolute',
left: trackHover.x,
bottom: '100%',
transform: 'translateX(-50%)',
marginBottom: 2,
pointerEvents: 'none',
zIndex: 10,
}}>
<TooltipBubble text={fmt(trackHover.t)} />
</div>
)}
</div>
{/* Duration — dimmed */}
<div style={{
fontFamily: numFont,
fontSize: 14,
fontWeight: 400,
fontVariantNumeric: 'tabular-nums',
color: 'rgba(255,255,255,0.6)',
minWidth: 40,
textAlign: 'center',
}}>
{fmt(duration)}
</div>
</div>
);
}
function IconButton({ children, onClick, tooltip }) {
const [hover, setHover] = React.useState(false);
return (
<button
onClick={onClick}
aria-label={tooltip}
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
style={{
position: 'relative',
width: 24, height: 24,
display: 'flex', alignItems: 'center', justifyContent: 'center',
background: hover ? 'rgba(255,255,255,0.1)' : 'transparent',
border: 'none',
borderRadius: 6,
color: '#fff',
cursor: 'pointer',
padding: 0,
transition: 'background 120ms',
}}
>
{children}
{tooltip && (
<div style={{
position: 'absolute',
bottom: '100%',
left: '50%',
transform: 'translateX(-50%)',
marginBottom: 8,
pointerEvents: 'none',
opacity: hover ? 1 : 0,
transition: 'opacity 120ms',
zIndex: 10,
}}>
<TooltipBubble text={tooltip} />
</div>
)}
</button>
);
}
// ── Tooltip bubble ────────────────────────────────────────────────────────────
// Dark rounded bubble with a downward tail. Positioning is up to the caller.
function TooltipBubble({ text }) {
return (
<div style={{ position: 'relative', display: 'inline-block' }}>
<div style={{
background: '#1F2329',
color: '#fff',
fontSize: 12,
lineHeight: '16px',
padding: '6px 12px',
borderRadius: 6,
whiteSpace: 'nowrap',
fontFamily: '"PingFang SC", -apple-system, BlinkMacSystemFont, system-ui, sans-serif',
fontVariantNumeric: 'tabular-nums',
boxShadow: '0 4px 8px -8px rgba(0, 0, 0, 0.06), 0 6px 12px 0 rgba(0, 0, 0, 0.04), 0 8px 24px 8px rgba(0, 0, 0, 0.04)',
}}>
{text}
</div>
<div style={{
position: 'absolute',
top: '100%',
left: '50%',
transform: 'translate(-50%, -50%) rotate(45deg)',
width: 9, height: 9,
borderRadius: '0 0 3px 0',
background: '#1F2329',
}}/>
</div>
);
}
Object.assign(window, {
Easing, interpolate, animate, clamp,
TimelineContext, useTime, useTimeline,
Sprite, SpriteContext, useSprite,
TextSprite, ImageSprite, RectSprite,
Stage, PlaybackBar,
});

View File

@@ -0,0 +1,122 @@
/* BEGIN USAGE */
// Chrome.jsx — Simplified Chrome browser window (dark theme, macOS)
// No dependencies, no image assets. All inline styles + inline SVG.
// Exports (to window): ChromeWindow, ChromeTabBar, ChromeToolbar, ChromeTab, ChromeTrafficLights
//
// Usage — wrap your page content in <ChromeWindow> to get the tab bar + URL bar:
//
// <ChromeWindow width={1100} height={680} url="acme.design/pricing">
// ...your page content...
// </ChromeWindow>
/* END USAGE */
const CHROME_C = {
barBg: '#202124',
tabBg: '#35363a',
text: '#e8eaed',
dim: '#9aa0a6',
urlBg: '#282a2d',
};
function ChromeTrafficLights() {
return (
<div style={{ display: 'flex', gap: 8, padding: '0 14px' }}>
<div style={{ width: 12, height: 12, borderRadius: '50%', background: '#ff5f57' }} />
<div style={{ width: 12, height: 12, borderRadius: '50%', background: '#febc2e' }} />
<div style={{ width: 12, height: 12, borderRadius: '50%', background: '#28c840' }} />
</div>
);
}
// Single tab (active has curved scoops)
function ChromeTab({ title = 'New Tab', active = false }) {
const curve = (flip) => (
<svg width="8" height="10" viewBox="0 0 8 10"
style={{ position: 'absolute', bottom: 0, [flip ? 'right' : 'left']: -8, transform: flip ? 'scaleX(-1)' : 'none' }}>
<path d="M0 10C2 9 6 8 8 0V10H0Z" fill={CHROME_C.tabBg}/>
</svg>
);
return (
<div style={{
position: 'relative', height: 34, alignSelf: 'flex-end',
padding: '0 12px', display: 'flex', alignItems: 'center', gap: 8,
background: active ? CHROME_C.tabBg : 'transparent',
borderRadius: '8px 8px 0 0', minWidth: 120, maxWidth: 220,
fontFamily: 'system-ui, sans-serif', fontSize: 12,
color: active ? CHROME_C.text : CHROME_C.dim,
}}>
{active && curve(false)}
{active && curve(true)}
<div style={{ width: 14, height: 14, borderRadius: '50%', background: '#5f6368', flexShrink: 0 }} />
<span style={{ flex: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</span>
</div>
);
}
function ChromeTabBar({ tabs = [{ title: 'New Tab' }], activeIndex = 0 }) {
return (
<div style={{
display: 'flex', alignItems: 'center', height: 44,
background: CHROME_C.barBg, paddingRight: 8,
}}>
<ChromeTrafficLights />
<div style={{ display: 'flex', alignItems: 'flex-end', height: '100%', paddingLeft: 4, flex: 1 }}>
{tabs.map((t, i) => <ChromeTab key={i} title={t.title} active={i === activeIndex} />)}
</div>
</div>
);
}
function ChromeToolbar({ url = 'example.com' }) {
const iconDot = (
<div style={{
width: 28, height: 28, display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
<div style={{ width: 16, height: 16, borderRadius: '50%', background: CHROME_C.dim, opacity: 0.4 }} />
</div>
);
return (
<div style={{
height: 40, background: CHROME_C.tabBg,
display: 'flex', alignItems: 'center', gap: 4, padding: '0 8px',
}}>
{iconDot}
{/* url bar */}
<div style={{
flex: 1, height: 30, borderRadius: 15, background: CHROME_C.urlBg,
display: 'flex', alignItems: 'center', gap: 8, padding: '0 14px',
margin: '0 6px',
}}>
<div style={{ width: 12, height: 12, borderRadius: '50%', background: CHROME_C.dim, opacity: 0.4 }} />
<span style={{
flex: 1, color: CHROME_C.text, fontSize: 13,
fontFamily: 'system-ui, sans-serif',
}}>{url}</span>
</div>
{iconDot}
</div>
);
}
function ChromeWindow({
tabs = [{ title: 'New Tab' }], activeIndex = 0, url = 'example.com',
width = 900, height = 600, children,
}) {
return (
<div style={{
width, height, borderRadius: 10, overflow: 'hidden',
border: '1px solid #DEE0E3',
display: 'flex', flexDirection: 'column', background: CHROME_C.tabBg,
}}>
<ChromeTabBar tabs={tabs} activeIndex={activeIndex} />
<ChromeToolbar url={url} />
<div style={{ flex: 1, background: '#fff', overflow: 'auto' }}>
{children}
</div>
</div>
);
}
Object.assign(window, {
ChromeWindow, ChromeTabBar, ChromeToolbar, ChromeTab, ChromeTrafficLights,
});

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,270 @@
/* BEGIN USAGE */
// iOS.jsx — Simplified iOS 26 (Liquid Glass) device frame
// Based on the iOS 26 UI Kit + Figma status bar spec. No assets, no deps.
// Exports (to window): IOSDevice, IOSStatusBar, IOSList, IOSListRow, IOSKeyboard
//
// Usage — wrap your screen content in <IOSDevice> to get the bezel, status bar
// and home indicator (props: width=402, height=874, dark, keyboard):
//
// <IOSDevice>
// ...your screen content...
// </IOSDevice>
// <IOSDevice dark keyboard>…</IOSDevice>
// <IOSDevice width={390} height={844}>…</IOSDevice> // smaller device size
//
// Safe areas — REQUIRED on every screen. The status bar (top) and home
// indicator (bottom) float OVER your content; inset it or it overlaps them.
// --ios-safe-top top inset (Dynamic Island + status bar)
// --ios-safe-bottom bottom inset (home indicator)
/* END USAGE */
// ─────────────────────────────────────────────────────────────
// Status bar
// ─────────────────────────────────────────────────────────────
function IOSStatusBar({ dark = false, time = '9:41' }) {
const c = dark ? '#fff' : '#000';
return (
<div style={{
display: 'flex', gap: 154, alignItems: 'center', justifyContent: 'center',
padding: '21px 24px 19px', boxSizing: 'border-box',
position: 'relative', zIndex: 20, width: '100%',
}}>
<div style={{ flex: 1, height: 22, display: 'flex', alignItems: 'center', justifyContent: 'center', paddingTop: 1.5 }}>
<span style={{
fontFamily: '-apple-system, "SF Pro", system-ui', fontWeight: 590,
fontSize: 17, lineHeight: '22px', color: c,
}}>{time}</span>
</div>
<div style={{ flex: 1, height: 22, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, paddingTop: 1, paddingRight: 1 }}>
<svg width="19" height="12" viewBox="0 0 19 12">
<rect x="0" y="7.5" width="3.2" height="4.5" rx="0.7" fill={c}/>
<rect x="4.8" y="5" width="3.2" height="7" rx="0.7" fill={c}/>
<rect x="9.6" y="2.5" width="3.2" height="9.5" rx="0.7" fill={c}/>
<rect x="14.4" y="0" width="3.2" height="12" rx="0.7" fill={c}/>
</svg>
<svg width="17" height="12" viewBox="0 0 17 12">
<path d="M8.5 3.2C10.8 3.2 12.9 4.1 14.4 5.6L15.5 4.5C13.7 2.7 11.2 1.5 8.5 1.5C5.8 1.5 3.3 2.7 1.5 4.5L2.6 5.6C4.1 4.1 6.2 3.2 8.5 3.2Z" fill={c}/>
<path d="M8.5 6.8C9.9 6.8 11.1 7.3 12 8.2L13.1 7.1C11.8 5.9 10.2 5.1 8.5 5.1C6.8 5.1 5.2 5.9 3.9 7.1L5 8.2C5.9 7.3 7.1 6.8 8.5 6.8Z" fill={c}/>
<circle cx="8.5" cy="10.5" r="1.5" fill={c}/>
</svg>
<svg width="27" height="13" viewBox="0 0 27 13">
<rect x="0.5" y="0.5" width="23" height="12" rx="3.5" stroke={c} strokeOpacity="0.35" fill="none"/>
<rect x="2" y="2" width="20" height="9" rx="2" fill={c}/>
<path d="M25 4.5V8.5C25.8 8.2 26.5 7.2 26.5 6.5C26.5 5.8 25.8 4.8 25 4.5Z" fill={c} fillOpacity="0.4"/>
</svg>
</div>
</div>
);
}
// ─────────────────────────────────────────────────────────────
// Grouped list (inset card, r:26) + row (52px)
// ─────────────────────────────────────────────────────────────
function IOSListRow({ title, detail, icon, chevron = true, isLast = false, dark = false }) {
const text = dark ? '#fff' : '#000';
const sec = dark ? 'rgba(235,235,245,0.6)' : 'rgba(60,60,67,0.6)';
const ter = dark ? 'rgba(235,235,245,0.3)' : 'rgba(60,60,67,0.3)';
const sep = dark ? 'rgba(84,84,88,0.65)' : 'rgba(60,60,67,0.12)';
return (
<div style={{
display: 'flex', alignItems: 'center', minHeight: 52,
padding: '0 16px', position: 'relative',
fontFamily: '-apple-system, system-ui', fontSize: 17,
letterSpacing: -0.43,
}}>
{icon && (
<div style={{
width: 30, height: 30, borderRadius: 7, background: icon,
marginRight: 12, flexShrink: 0,
}} />
)}
<div style={{ flex: 1, color: text }}>{title}</div>
{detail && <span style={{ color: sec, marginRight: 6 }}>{detail}</span>}
{chevron && (
<svg width="8" height="14" viewBox="0 0 8 14" style={{ flexShrink: 0 }}>
<path d="M1 1l6 6-6 6" stroke={ter} strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
)}
{!isLast && (
<div style={{
position: 'absolute', bottom: 0, right: 0,
left: icon ? 58 : 16, height: 0.5, background: sep,
}} />
)}
</div>
);
}
function IOSList({ header, children, dark = false }) {
const hc = dark ? 'rgba(235,235,245,0.6)' : 'rgba(60,60,67,0.6)';
const bg = dark ? '#1C1C1E' : '#fff';
return (
<div>
{header && (
<div style={{
fontFamily: '-apple-system, system-ui', fontSize: 13,
color: hc, textTransform: 'uppercase',
padding: '8px 36px 6px', letterSpacing: -0.08,
}}>{header}</div>
)}
<div style={{
background: bg, borderRadius: 26,
margin: '0 16px', overflow: 'hidden',
}}>{children}</div>
</div>
);
}
// ─────────────────────────────────────────────────────────────
// Device frame
// ─────────────────────────────────────────────────────────────
function IOSDevice({
children, width = 402, height = 874, dark = false,
keyboard = false,
}) {
return (
<div style={{
width, height, borderRadius: 48, overflow: 'hidden',
position: 'relative', background: dark ? '#000' : '#F2F2F7',
border: '1px solid #DEE0E3',
fontFamily: '-apple-system, system-ui, sans-serif',
WebkitFontSmoothing: 'antialiased',
'--ios-safe-top': '62px',
'--ios-safe-bottom': '34px',
}}>
{/* dynamic island */}
<div style={{
position: 'absolute', top: 11, left: '50%', transform: 'translateX(-50%)',
width: 126, height: 37, borderRadius: 24, background: '#000', zIndex: 50,
}} />
{/* status bar (absolute) */}
<div style={{ position: 'absolute', top: 0, left: 0, right: 0, zIndex: 10 }}>
<IOSStatusBar dark={dark} />
</div>
{/* content */}
<div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
<div style={{ flex: 1, overflow: 'auto' }}>{children}</div>
{keyboard && <IOSKeyboard dark={dark} />}
</div>
{/* home indicator — always on top */}
<div style={{
position: 'absolute', bottom: 0, left: 0, right: 0, zIndex: 60,
height: 34, display: 'flex', justifyContent: 'center', alignItems: 'flex-end',
paddingBottom: 8, pointerEvents: 'none',
}}>
<div style={{
width: 139, height: 5, borderRadius: 100,
background: dark ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.25)',
}} />
</div>
</div>
);
}
// ─────────────────────────────────────────────────────────────
// Keyboard — iOS 26 liquid glass
// ─────────────────────────────────────────────────────────────
function IOSKeyboard({ dark = false }) {
const glyph = dark ? 'rgba(255,255,255,0.7)' : '#595959';
const sugg = dark ? 'rgba(255,255,255,0.6)' : '#333';
const keyBg = dark ? 'rgba(255,255,255,0.22)' : 'rgba(255,255,255,0.85)';
// special-key icons
const icons = {
shift: <svg width="19" height="17" viewBox="0 0 19 17"><path d="M9.5 1L1 9.5h4.5V16h8V9.5H18L9.5 1z" fill={glyph}/></svg>,
del: <svg width="23" height="17" viewBox="0 0 23 17"><path d="M7 1h13a2 2 0 012 2v11a2 2 0 01-2 2H7l-6-7.5L7 1z" fill="none" stroke={glyph} strokeWidth="1.6" strokeLinejoin="round"/><path d="M10 5l7 7M17 5l-7 7" stroke={glyph} strokeWidth="1.6" strokeLinecap="round"/></svg>,
ret: <svg width="20" height="14" viewBox="0 0 20 14"><path d="M18 1v6H4m0 0l4-4M4 7l4 4" fill="none" stroke="#fff" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/></svg>,
};
const key = (content, { w, flex, ret, fs = 25, k } = {}) => (
<div key={k} style={{
height: 42, borderRadius: 8.5,
flex: flex ? 1 : undefined, width: w, minWidth: 0,
background: ret ? '#08f' : keyBg,
boxShadow: '0 1px 0 rgba(0,0,0,0.075)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontFamily: '-apple-system, "SF Compact", system-ui',
fontSize: fs, fontWeight: 458, color: ret ? '#fff' : glyph,
}}>{content}</div>
);
const row = (keys, pad = 0) => (
<div style={{ display: 'flex', gap: 6.5, justifyContent: 'center', padding: `0 ${pad}px` }}>
{keys.map(l => key(l, { flex: true, k: l }))}
</div>
);
return (
<div style={{
position: 'relative', zIndex: 15, borderRadius: 27, overflow: 'hidden',
padding: '11px 0 2px',
display: 'flex', flexDirection: 'column', alignItems: 'center',
boxShadow: dark
? '0 -2px 20px rgba(0,0,0,0.09)'
: '0 -1px 6px rgba(0,0,0,0.018), 0 -3px 20px rgba(0,0,0,0.012)',
}}>
{/* liquid glass bg — same recipe as nav pills */}
<div style={{
position: 'absolute', inset: 0, borderRadius: 27,
backdropFilter: 'blur(12px) saturate(180%)',
WebkitBackdropFilter: 'blur(12px) saturate(180%)',
background: dark ? 'rgba(120,120,128,0.14)' : 'rgba(255,255,255,0.25)',
}} />
<div style={{
position: 'absolute', inset: 0, borderRadius: 27,
boxShadow: dark
? 'inset 1.5px 1.5px 1px rgba(255,255,255,0.15)'
: 'inset 1.5px 1.5px 1px rgba(255,255,255,0.7), inset -1px -1px 1px rgba(255,255,255,0.4)',
border: dark ? '0.5px solid rgba(255,255,255,0.15)' : '0.5px solid rgba(0,0,0,0.06)',
pointerEvents: 'none',
}} />
{/* autocorrect bar */}
<div style={{
display: 'flex', gap: 20, alignItems: 'center',
padding: '8px 22px 13px', width: '100%', boxSizing: 'border-box',
position: 'relative',
}}>
{['"The"', 'the', 'to'].map((w, i) => (
<React.Fragment key={i}>
{i > 0 && <div style={{ width: 1, height: 25, background: '#ccc', opacity: 0.3 }} />}
<div style={{
flex: 1, textAlign: 'center',
fontFamily: '-apple-system, system-ui', fontSize: 17,
color: sugg, letterSpacing: -0.43, lineHeight: '22px',
}}>{w}</div>
</React.Fragment>
))}
</div>
{/* key layout */}
<div style={{
display: 'flex', flexDirection: 'column', gap: 13,
padding: '0 6.5px', width: '100%', boxSizing: 'border-box',
position: 'relative',
}}>
{row(['q','w','e','r','t','y','u','i','o','p'])}
{row(['a','s','d','f','g','h','j','k','l'], 20)}
<div style={{ display: 'flex', gap: 14.25, alignItems: 'center' }}>
{key(icons.shift, { w: 45, k: 'shift' })}
<div style={{ display: 'flex', gap: 6.5, flex: 1 }}>
{['z','x','c','v','b','n','m'].map(l => key(l, { flex: true, k: l }))}
</div>
{key(icons.del, { w: 45, k: 'del' })}
</div>
<div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
{key('ABC', { w: 92.25, fs: 18, k: 'abc' })}
{key('', { flex: true, k: 'space' })}
{key(icons.ret, { w: 92.25, ret: true, k: 'ret' })}
</div>
</div>
{/* bottom spacer (emoji+mic area, icons omitted) */}
<div style={{ height: 56, width: '100%', position: 'relative' }} />
</div>
);
}
Object.assign(window, {
IOSDevice, IOSStatusBar, IOSList, IOSListRow, IOSKeyboard,
});

View File

@@ -0,0 +1,197 @@
/* BEGIN USAGE */
// MacOS.jsx — Simplified macOS Tahoe (Liquid Glass) window
// Based on the macOS Tahoe UI Kit. No image assets, no dependencies.
// Exports (to window): MacWindow, MacSidebar, MacSidebarItem, MacSidebarHeader, MacToolbar, MacGlass, MacTrafficLights
//
// Usage — wrap your app content in <MacWindow> to get the window chrome
// (traffic lights + titlebar). Props: width, height, title, sidebar (pass a
// <MacSidebar> element); compose MacToolbar/MacGlass inside as needed:
//
// <MacWindow width={980} height={620} title="Documents"
// sidebar={<MacSidebar>…</MacSidebar>}>
// ...your app content...
// </MacWindow>
/* END USAGE */
const MAC_FONT = '-apple-system, BlinkMacSystemFont, "SF Pro", "Helvetica Neue", sans-serif';
// ─────────────────────────────────────────────────────────────
// Liquid glass primitive — blur + white tint + inset highlight
// ─────────────────────────────────────────────────────────────
function MacGlass({ children, radius = 296, dark = false, style = {} }) {
return (
<div style={{ position: 'relative', borderRadius: radius, ...style }}>
<div style={{
position: 'absolute', inset: 0, borderRadius: radius,
background: dark ? 'rgba(255,255,255,0.08)' : 'rgba(255,255,255,0.35)',
backdropFilter: 'blur(40px) saturate(180%)',
WebkitBackdropFilter: 'blur(40px) saturate(180%)',
border: dark ? '0.5px solid rgba(255,255,255,0.12)' : '0.5px solid rgba(255,255,255,0.6)',
boxShadow: dark
? '0 8px 40px rgba(0,0,0,0.2)'
: '0 8px 40px rgba(0,0,0,0.08), inset 0 1px 0 rgba(255,255,255,0.4)',
}} />
<div style={{ position: 'relative', zIndex: 1 }}>{children}</div>
</div>
);
}
// ─────────────────────────────────────────────────────────────
// Traffic lights (14px, Tahoe colors)
// ─────────────────────────────────────────────────────────────
function MacTrafficLights({ style = {} }) {
const dot = (bg) => (
<div style={{
width: 14, height: 14, borderRadius: '50%', background: bg,
border: '0.5px solid rgba(0,0,0,0.1)',
}} />
);
return (
<div style={{ display: 'flex', gap: 9, alignItems: 'center', padding: 1, ...style }}>
{dot('#ff736a')}{dot('#febc2e')}{dot('#19c332')}
</div>
);
}
// ─────────────────────────────────────────────────────────────
// Toolbar — title + single glass pill icon
// ─────────────────────────────────────────────────────────────
function MacToolbar({ title = 'Folder' }) {
return (
<div style={{
display: 'flex', gap: 8, alignItems: 'center', padding: 8, flexShrink: 0,
}}>
{/* title */}
<div style={{
fontFamily: MAC_FONT, fontSize: 15, fontWeight: 700,
color: 'rgba(0,0,0,0.85)', whiteSpace: 'nowrap', paddingLeft: 8,
}}>{title}</div>
<div style={{ flex: 1 }} />
{/* single action */}
<MacGlass>
<div style={{
width: 36, height: 36, display: 'flex',
alignItems: 'center', justifyContent: 'center',
}}>
<div style={{ width: 14, height: 14, borderRadius: '50%', background: '#4c4c4c', opacity: 0.4 }} />
</div>
</MacGlass>
{/* search */}
<MacGlass>
<div style={{
width: 140, height: 36, display: 'flex', alignItems: 'center',
gap: 6, padding: '0 12px',
}}>
<svg width="13" height="13" viewBox="0 0 13 13" fill="none">
<circle cx="5.5" cy="5.5" r="4" stroke="#727272" strokeWidth="1.5"/>
<path d="M8.5 8.5l3 3" stroke="#727272" strokeWidth="1.5" strokeLinecap="round"/>
</svg>
<span style={{
fontFamily: MAC_FONT, fontSize: 13, fontWeight: 500, color: '#727272',
}}>Search</span>
</div>
</MacGlass>
</div>
);
}
// ─────────────────────────────────────────────────────────────
// Sidebar — frosted glass panel floating inside the window
// ─────────────────────────────────────────────────────────────
function MacSidebarItem({ label, selected = false }) {
return (
<div style={{
display: 'flex', alignItems: 'center', gap: 6,
height: 24, padding: '4px 10px 4px 6px', margin: '0 10px',
borderRadius: 8, position: 'relative',
fontFamily: MAC_FONT, fontSize: 11, fontWeight: 500,
}}>
{selected && (
<div style={{
position: 'absolute', inset: 0, borderRadius: 8,
background: 'rgba(0,0,0,0.11)', mixBlendMode: 'multiply',
}} />
)}
<div style={{
width: 14, height: 14, borderRadius: '50%',
background: selected ? '#007aff' : 'rgba(0,0,0,0.4)',
opacity: selected ? 1 : 0.5, flexShrink: 0, position: 'relative',
}} />
<span style={{ color: 'rgba(0,0,0,0.85)', position: 'relative' }}>{label}</span>
</div>
);
}
function MacSidebar({ children }) {
return (
<div style={{
width: 220, height: '100%', padding: 8, flexShrink: 0,
position: 'relative', display: 'flex', flexDirection: 'column',
}}>
{/* glass panel */}
<div style={{
position: 'absolute', inset: 8, borderRadius: 18,
background: 'rgba(210,225,245,0.45)',
backdropFilter: 'blur(50px) saturate(200%)',
WebkitBackdropFilter: 'blur(50px) saturate(200%)',
border: '0.5px solid rgba(255,255,255,0.5)',
boxShadow: '0 8px 40px rgba(0,0,0,0.10), inset 0 1px 0 rgba(255,255,255,0.35)',
}} />
{/* content */}
<div style={{
position: 'relative', zIndex: 1, padding: '10px 0',
display: 'flex', flexDirection: 'column', gap: 2,
}}>
{/* window controls + sidebar toggle */}
<div style={{
height: 32, display: 'flex', alignItems: 'center',
justifyContent: 'space-between', padding: '0 10px', marginBottom: 4,
}}>
<MacTrafficLights />
</div>
{children}
</div>
</div>
);
}
function MacSidebarHeader({ title }) {
return (
<div style={{
padding: '14px 18px 5px',
fontFamily: MAC_FONT, fontSize: 11, fontWeight: 700,
color: 'rgba(0,0,0,0.5)',
}}>{title}</div>
);
}
// ─────────────────────────────────────────────────────────────
// Window — r:26, big shadow, sidebar + toolbar + content
// ─────────────────────────────────────────────────────────────
function MacWindow({
width = 900, height = 600, title = 'Folder',
sidebar, children,
}) {
return (
<div style={{
width, height, borderRadius: 26, overflow: 'hidden',
background: '#fff',
border: '1px solid #DEE0E3',
display: 'flex', position: 'relative',
fontFamily: MAC_FONT,
}}>
<MacSidebar>{sidebar}</MacSidebar>
<div style={{ flex: 1, display: 'flex', flexDirection: 'column' }}>
<MacToolbar title={title} />
<div style={{ flex: 1, overflow: 'auto', padding: '4px 8px' }}>
{children}
</div>
</div>
</div>
);
}
Object.assign(window, {
MacWindow, MacSidebar, MacSidebarItem, MacSidebarHeader,
MacToolbar, MacGlass, MacTrafficLights,
});

View File

@@ -0,0 +1,752 @@
/* BEGIN USAGE */
// tweaks-panel.jsx
// Reusable Tweaks shell + form-control helpers.
// Exports (to window): useTweaks, TweaksPanel, TweakSection, TweakRow, TweakSlider,
// TweakToggle, TweakRadio, TweakSelect, TweakText, TweakNumber, TweakColor, TweakButton.
//
// Owns the host protocol (listens for miaoda:tweaks:activate / miaoda:tweaks:deactivate,
// posts miaoda:tweaks:available / miaoda:tweaks:set-keys / miaoda:tweaks:dismissed) so
// individual prototypes don't re-roll it. Ships a consistent set of controls so you
// don't hand-draw <input type="range">, segmented radios, steppers, etc.
//
// Usage (in an HTML file that loads React + Babel):
//
// const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
// "primaryColor": "#D97757",
// "palette": ["#D97757", "#29261b", "#f6f4ef"],
// "fontSize": 16,
// "density": "regular",
// "dark": false
// }/*EDITMODE-END*/;
//
// TWEAK_DEFAULTS must live inline in the HTML file — in a <script type="text/babel"> block,
// not in a separate .jsx/.js loaded via <script src>. That in-HTML block is the region the
// host rewrites when the user adjusts a tweak, so keep it wrapped in the /*EDITMODE-BEGIN*/ …
// /*EDITMODE-END*/ markers and the object between them valid JSON — double-quoted keys, no
// trailing commas, no comments or expressions — even after you rename the keys. Move it out
// of the HTML, strip the markers, or use a non-JSON body and tweak edits silently stop persisting.
//
// function App() {
// const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
// return (
// <div style={{ fontSize: t.fontSize, color: t.primaryColor }}>
// Hello
// <TweaksPanel>
// <TweakSection label="Typography" />
// <TweakSlider label="Font size" value={t.fontSize} min={10} max={32} unit="px"
// onChange={(v) => setTweak('fontSize', v)} />
// <TweakRadio label="Density" value={t.density}
// options={['compact', 'regular', 'comfy']}
// onChange={(v) => setTweak('density', v)} />
// <TweakSection label="Theme" />
// <TweakColor label="Primary" value={t.primaryColor}
// options={['#D97757', '#2A6FDB', '#1F8A5B', '#7A5AE0']}
// onChange={(v) => setTweak('primaryColor', v)} />
// <TweakColor label="Palette" value={t.palette}
// options={[['#D97757', '#29261b', '#f6f4ef'],
// ['#475569', '#0f172a', '#f1f5f9']]}
// onChange={(v) => setTweak('palette', v)} />
// <TweakToggle label="Dark mode" value={t.dark}
// onChange={(v) => setTweak('dark', v)} />
// </TweaksPanel>
// </div>
// );
// }
//
// TweakRadio is the segmented control for 23 short options (auto-falls-back to
// TweakSelect past ~16/~10 chars per label); reach for TweakSelect directly when
// options are many or long. For color tweaks always curate 3-4 options rather than
// a free picker; an option can also be a whole 25 color palette (the stored value
// is the array). The Tweak* controls are a floor, not a ceiling — build custom
// controls inside the panel if a tweak calls for UI they don't cover.
/* END USAGE */
// ─────────────────────────────────────────────────────────────────────────────
const __TWEAKS_STYLE = `
.twk-panel{position:fixed;right:16px;bottom:16px;z-index:2147483646;width:280px;
max-height:calc(100vh - 32px);display:flex;flex-direction:column;
transform:scale(var(--dc-inv-zoom,1));transform-origin:bottom right;
background:rgba(250,249,247,.78);color:#29261b;
-webkit-backdrop-filter:blur(24px) saturate(160%);backdrop-filter:blur(24px) saturate(160%);
border:.5px solid rgba(255,255,255,.6);border-radius:14px;
box-shadow:0 1px 0 rgba(255,255,255,.5) inset,0 12px 40px rgba(0,0,0,.18);
font:11.5px/1.4 ui-sans-serif,system-ui,-apple-system,sans-serif;overflow:hidden}
.twk-hd{display:flex;align-items:center;justify-content:space-between;
padding:10px 8px 10px 14px;cursor:move;user-select:none}
.twk-hd b{font-size:12px;font-weight:600;letter-spacing:.01em}
.twk-x{appearance:none;border:0;background:transparent;color:rgba(41,38,27,.55);
width:22px;height:22px;border-radius:6px;cursor:default;font-size:13px;line-height:1}
.twk-x:hover{background:rgba(0,0,0,.06);color:#29261b}
.twk-body{padding:2px 14px 14px;display:flex;flex-direction:column;gap:10px;
overflow-y:auto;overflow-x:hidden;min-height:0;
scrollbar-width:thin;scrollbar-color:rgba(0,0,0,.15) transparent}
.twk-body::-webkit-scrollbar{width:8px}
.twk-body::-webkit-scrollbar-track{background:transparent;margin:2px}
.twk-body::-webkit-scrollbar-thumb{background:rgba(0,0,0,.15);border-radius:4px;
border:2px solid transparent;background-clip:content-box}
.twk-body::-webkit-scrollbar-thumb:hover{background:rgba(0,0,0,.25);
border:2px solid transparent;background-clip:content-box}
.twk-row{display:flex;flex-direction:column;gap:5px}
.twk-row-h{flex-direction:row;align-items:center;justify-content:space-between;gap:10px}
.twk-lbl{display:flex;justify-content:space-between;align-items:baseline;
color:rgba(41,38,27,.72)}
.twk-lbl>span:first-child{font-weight:500}
.twk-val{color:rgba(41,38,27,.5);font-variant-numeric:tabular-nums}
.twk-sect{font-size:10px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;
color:rgba(41,38,27,.45);padding:10px 0 0}
.twk-sect:first-child{padding-top:0}
.twk-field{appearance:none;box-sizing:border-box;width:100%;min-width:0;height:26px;padding:0 8px;
border:.5px solid rgba(0,0,0,.1);border-radius:7px;
background:rgba(255,255,255,.6);color:inherit;font:inherit;outline:none}
.twk-field:focus{border-color:rgba(0,0,0,.25);background:rgba(255,255,255,.85)}
select.twk-field{padding-right:22px;
background-image:url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'><path fill='rgba(0,0,0,.5)' d='M0 0h10L5 6z'/></svg>");
background-repeat:no-repeat;background-position:right 8px center}
.twk-slider{appearance:none;-webkit-appearance:none;width:100%;height:4px;margin:6px 0;
border-radius:999px;background:rgba(0,0,0,.12);outline:none}
.twk-slider::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;
width:14px;height:14px;border-radius:50%;background:#fff;
border:.5px solid rgba(0,0,0,.12);box-shadow:0 1px 3px rgba(0,0,0,.2);cursor:default}
.twk-slider::-moz-range-thumb{width:14px;height:14px;border-radius:50%;
background:#fff;border:.5px solid rgba(0,0,0,.12);box-shadow:0 1px 3px rgba(0,0,0,.2);cursor:default}
.twk-seg{position:relative;display:flex;padding:2px;border-radius:8px;
background:rgba(0,0,0,.06);user-select:none}
.twk-seg-thumb{position:absolute;top:2px;bottom:2px;border-radius:6px;
background:rgba(255,255,255,.9);box-shadow:0 1px 2px rgba(0,0,0,.12);
transition:left .15s cubic-bezier(.3,.7,.4,1),width .15s}
.twk-seg.dragging .twk-seg-thumb{transition:none}
.twk-seg button{appearance:none;position:relative;z-index:1;flex:1;border:0;
background:transparent;color:inherit;font:inherit;font-weight:500;min-height:22px;
border-radius:6px;cursor:default;padding:4px 6px;line-height:1.2;
overflow-wrap:anywhere}
.twk-toggle{position:relative;width:32px;height:18px;border:0;border-radius:999px;
background:rgba(0,0,0,.15);transition:background .15s;cursor:default;padding:0}
.twk-toggle[data-on="1"]{background:#34c759}
.twk-toggle i{position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;
background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.25);transition:transform .15s}
.twk-toggle[data-on="1"] i{transform:translateX(14px)}
.twk-num{display:flex;align-items:center;box-sizing:border-box;min-width:0;height:26px;padding:0 0 0 8px;
border:.5px solid rgba(0,0,0,.1);border-radius:7px;background:rgba(255,255,255,.6)}
.twk-num-lbl{font-weight:500;color:rgba(41,38,27,.6);cursor:ew-resize;
user-select:none;padding-right:8px}
.twk-num input{flex:1;min-width:0;height:100%;border:0;background:transparent;
font:inherit;font-variant-numeric:tabular-nums;text-align:right;padding:0 8px 0 0;
outline:none;color:inherit;-moz-appearance:textfield}
.twk-num input::-webkit-inner-spin-button,.twk-num input::-webkit-outer-spin-button{
-webkit-appearance:none;margin:0}
.twk-num-unit{padding-right:8px;color:rgba(41,38,27,.45)}
.twk-btn{appearance:none;height:26px;padding:0 12px;border:0;border-radius:7px;
background:rgba(0,0,0,.78);color:#fff;font:inherit;font-weight:500;cursor:default}
.twk-btn:hover{background:rgba(0,0,0,.88)}
.twk-btn.secondary{background:rgba(0,0,0,.06);color:inherit}
.twk-btn.secondary:hover{background:rgba(0,0,0,.1)}
.twk-swatch{appearance:none;-webkit-appearance:none;width:56px;height:22px;
border:.5px solid rgba(0,0,0,.1);border-radius:6px;padding:0;cursor:default;
background:transparent;flex-shrink:0}
.twk-swatch::-webkit-color-swatch-wrapper{padding:0}
.twk-swatch::-webkit-color-swatch{border:0;border-radius:5.5px}
.twk-swatch::-moz-color-swatch{border:0;border-radius:5.5px}
.twk-chips{display:flex;gap:6px}
.twk-chip{position:relative;appearance:none;flex:1;min-width:0;height:46px;
padding:0;border:0;border-radius:6px;overflow:hidden;cursor:default;
box-shadow:0 0 0 .5px rgba(0,0,0,.12),0 1px 2px rgba(0,0,0,.06);
transition:transform .12s cubic-bezier(.3,.7,.4,1),box-shadow .12s}
.twk-chip:hover{transform:translateY(-1px);
box-shadow:0 0 0 .5px rgba(0,0,0,.18),0 4px 10px rgba(0,0,0,.12)}
.twk-chip[data-on="1"]{box-shadow:0 0 0 1.5px rgba(0,0,0,.85),
0 2px 6px rgba(0,0,0,.15)}
.twk-chip>span{position:absolute;top:0;bottom:0;right:0;width:34%;
display:flex;flex-direction:column;box-shadow:-1px 0 0 rgba(0,0,0,.1)}
.twk-chip>span>i{flex:1;box-shadow:0 -1px 0 rgba(0,0,0,.1)}
.twk-chip>span>i:first-child{box-shadow:none}
.twk-chip svg{position:absolute;top:6px;left:6px;width:13px;height:13px;
filter:drop-shadow(0 1px 1px rgba(0,0,0,.3))}
`;
// ── useTweaks ───────────────────────────────────────────────────────────────
// Single source of truth for tweak values. setTweak persists via the host
// (miaoda:tweaks:set-keys → host rewrites the EDITMODE block on disk).
function useTweaks(defaults) {
const [values, setValues] = React.useState(defaults);
// Accepts either setTweak('key', value) or setTweak({ key: value, ... }) so a
// useState-style call doesn't write a "[object Object]" key into the persisted
// JSON block.
const setTweak = React.useCallback((keyOrEdits, val) => {
const edits = typeof keyOrEdits === 'object' && keyOrEdits !== null
? keyOrEdits : { [keyOrEdits]: val };
setValues((prev) => ({ ...prev, ...edits }));
window.parent.postMessage({ type: 'miaoda:tweaks:set-keys', edits }, '*');
// Same-window signal so in-page listeners (deck-stage rail thumbnails)
// can react — the parent message only reaches the host, not peers.
window.dispatchEvent(new CustomEvent('tweakchange', { detail: edits }));
}, []);
return [values, setTweak];
}
// ── TweaksPanel ─────────────────────────────────────────────────────────────
// Floating shell. Registers the protocol listener BEFORE announcing
// availability — if the announce ran first, the host's activate could land
// before our handler exists and the toolbar toggle would silently no-op.
// The close button posts miaoda:tweaks:dismissed so the host's toolbar toggle
// flips off in lockstep; the host echoes miaoda:tweaks:deactivate back which
// is what actually hides the panel.
function TweaksPanel({ title = 'Tweaks', children }) {
const [open, setOpen] = React.useState(false);
const dragRef = React.useRef(null);
const offsetRef = React.useRef({ x: 16, y: 16 });
const PAD = 16;
const clampToViewport = React.useCallback(() => {
const panel = dragRef.current;
if (!panel) return;
const w = panel.offsetWidth, h = panel.offsetHeight;
const maxRight = Math.max(PAD, window.innerWidth - w - PAD);
const maxBottom = Math.max(PAD, window.innerHeight - h - PAD);
offsetRef.current = {
x: Math.min(maxRight, Math.max(PAD, offsetRef.current.x)),
y: Math.min(maxBottom, Math.max(PAD, offsetRef.current.y)),
};
panel.style.right = offsetRef.current.x + 'px';
panel.style.bottom = offsetRef.current.y + 'px';
}, []);
React.useEffect(() => {
if (!open) return;
clampToViewport();
if (typeof ResizeObserver === 'undefined') {
window.addEventListener('resize', clampToViewport);
return () => window.removeEventListener('resize', clampToViewport);
}
const ro = new ResizeObserver(clampToViewport);
ro.observe(document.documentElement);
return () => ro.disconnect();
}, [open, clampToViewport]);
React.useEffect(() => {
const onMsg = (e) => {
const t = e?.data?.type;
if (t === 'miaoda:tweaks:activate') setOpen(true);
else if (t === 'miaoda:tweaks:deactivate') setOpen(false);
};
window.addEventListener('message', onMsg);
window.parent.postMessage({ type: 'miaoda:tweaks:available' }, '*');
return () => window.removeEventListener('message', onMsg);
}, []);
const dismiss = () => {
setOpen(false);
window.parent.postMessage({ type: 'miaoda:tweaks:dismissed' }, '*');
};
const onDragStart = (e) => {
const panel = dragRef.current;
if (!panel) return;
const r = panel.getBoundingClientRect();
const sx = e.clientX, sy = e.clientY;
const startRight = window.innerWidth - r.right;
const startBottom = window.innerHeight - r.bottom;
const move = (ev) => {
offsetRef.current = {
x: startRight - (ev.clientX - sx),
y: startBottom - (ev.clientY - sy),
};
clampToViewport();
};
const up = () => {
window.removeEventListener('mousemove', move);
window.removeEventListener('mouseup', up);
};
window.addEventListener('mousemove', move);
window.addEventListener('mouseup', up);
};
if (!open) return null;
return (
<>
<style>{__TWEAKS_STYLE}</style>
<div ref={dragRef} className="twk-panel" data-miaoda-chrome=""
style={{ right: offsetRef.current.x, bottom: offsetRef.current.y }}>
<div className="twk-hd" onMouseDown={onDragStart}>
<b>{title}</b>
<button className="twk-x" aria-label="Close tweaks"
onMouseDown={(e) => e.stopPropagation()}
onClick={dismiss}></button>
</div>
<div className="twk-body">
{children}
</div>
</div>
</>
);
}
// ── Layout helpers ──────────────────────────────────────────────────────────
function TweakSection({ label, children }) {
return (
<>
<div className="twk-sect">{label}</div>
{children}
</>
);
}
function TweakRow({ label, value, children, inline = false }) {
return (
<div className={inline ? 'twk-row twk-row-h' : 'twk-row'}>
<div className="twk-lbl">
<span>{label}</span>
{value != null && <span className="twk-val">{value}</span>}
</div>
{children}
</div>
);
}
// ── Controls ────────────────────────────────────────────────────────────────
function TweakSlider({ label, value, min = 0, max = 100, step = 1, unit = '', onChange }) {
return (
<TweakRow label={label} value={`${value}${unit}`}>
<input type="range" className="twk-slider" min={min} max={max} step={step}
value={value} onChange={(e) => onChange(Number(e.target.value))} />
</TweakRow>
);
}
function TweakToggle({ label, value, onChange }) {
return (
<div className="twk-row twk-row-h">
<div className="twk-lbl"><span>{label}</span></div>
<button type="button" className="twk-toggle" data-on={value ? '1' : '0'}
role="switch" aria-checked={!!value}
onClick={() => onChange(!value)}><i /></button>
</div>
);
}
function TweakRadio({ label, value, options, onChange }) {
const trackRef = React.useRef(null);
const [dragging, setDragging] = React.useState(false);
// The active value is read by pointer-move handlers attached for the lifetime
// of a drag — ref it so a stale closure doesn't fire onChange for every move.
const valueRef = React.useRef(value);
valueRef.current = value;
// Segments wrap mid-word once per-segment width runs out. The track is
// ~248px (280 panel 28 body pad 4 seg pad), each button loses 12px
// to its own padding, and 11.5px system-ui averages ~6.3px/char — so 2
// options fit ~16 chars each, 3 fit ~10. Past that (or >3 options), fall
// back to a dropdown rather than wrap.
const labelLen = (o) => String(typeof o === 'object' ? o.label : o).length;
const maxLen = options.reduce((m, o) => Math.max(m, labelLen(o)), 0);
const fitsAsSegments = maxLen <= ({ 2: 16, 3: 10 }[options.length] ?? 0);
if (!fitsAsSegments) {
// <select> emits strings — map back to the original option value so the
// fallback stays type-preserving (numbers, booleans) like the segment path.
const resolve = (s) => {
const m = options.find((o) => String(typeof o === 'object' ? o.value : o) === s);
return m === undefined ? s : typeof m === 'object' ? m.value : m;
};
return <TweakSelect label={label} value={value} options={options}
onChange={(s) => onChange(resolve(s))} />;
}
const opts = options.map((o) => (typeof o === 'object' ? o : { value: o, label: o }));
const idx = Math.max(0, opts.findIndex((o) => o.value === value));
const n = opts.length;
const segAt = (clientX) => {
const r = trackRef.current.getBoundingClientRect();
const inner = r.width - 4;
const i = Math.floor(((clientX - r.left - 2) / inner) * n);
return opts[Math.max(0, Math.min(n - 1, i))].value;
};
const onPointerDown = (e) => {
setDragging(true);
const v0 = segAt(e.clientX);
if (v0 !== valueRef.current) onChange(v0);
const move = (ev) => {
if (!trackRef.current) return;
const v = segAt(ev.clientX);
if (v !== valueRef.current) onChange(v);
};
const up = () => {
setDragging(false);
window.removeEventListener('pointermove', move);
window.removeEventListener('pointerup', up);
};
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', up);
};
return (
<TweakRow label={label}>
<div ref={trackRef} role="radiogroup" onPointerDown={onPointerDown}
className={dragging ? 'twk-seg dragging' : 'twk-seg'}>
<div className="twk-seg-thumb"
style={{ left: `calc(2px + ${idx} * (100% - 4px) / ${n})`,
width: `calc((100% - 4px) / ${n})` }} />
{opts.map((o) => (
<button key={o.value} type="button" role="radio" aria-checked={o.value === value}>
{o.label}
</button>
))}
</div>
</TweakRow>
);
}
function TweakSelect({ label, value, options, onChange }) {
return (
<TweakRow label={label}>
<select className="twk-field" value={value} onChange={(e) => onChange(e.target.value)}>
{options.map((o) => {
const v = typeof o === 'object' ? o.value : o;
const l = typeof o === 'object' ? o.label : o;
return <option key={v} value={v}>{l}</option>;
})}
</select>
</TweakRow>
);
}
function TweakText({ label, value, placeholder, onChange }) {
return (
<TweakRow label={label}>
<input className="twk-field" type="text" value={value} placeholder={placeholder}
onChange={(e) => onChange(e.target.value)} />
</TweakRow>
);
}
function TweakNumber({ label, value, min, max, step = 1, unit = '', onChange }) {
const clamp = (n) => {
if (min != null && n < min) return min;
if (max != null && n > max) return max;
return n;
};
const startRef = React.useRef({ x: 0, val: 0 });
const onScrubStart = (e) => {
e.preventDefault();
startRef.current = { x: e.clientX, val: value };
const decimals = (String(step).split('.')[1] || '').length;
const move = (ev) => {
const dx = ev.clientX - startRef.current.x;
const raw = startRef.current.val + dx * step;
const snapped = Math.round(raw / step) * step;
onChange(clamp(Number(snapped.toFixed(decimals))));
};
const up = () => {
window.removeEventListener('pointermove', move);
window.removeEventListener('pointerup', up);
};
window.addEventListener('pointermove', move);
window.addEventListener('pointerup', up);
};
return (
<div className="twk-num">
<span className="twk-num-lbl" onPointerDown={onScrubStart}>{label}</span>
<input type="number" value={value} min={min} max={max} step={step}
onChange={(e) => onChange(clamp(Number(e.target.value)))} />
{unit && <span className="twk-num-unit">{unit}</span>}
</div>
);
}
// Relative-luminance contrast pick — checkmarks drawn over a swatch need to
// read on both #111 and #fafafa without per-option configuration. Hex input
// only (#rgb / #rrggbb); named or rgb()/hsl() colors fall through to "light".
function __twkIsLight(hex) {
const h = String(hex).replace('#', '');
const x = h.length === 3 ? h.replace(/./g, (c) => c + c) : h.padEnd(6, '0');
const n = parseInt(x.slice(0, 6), 16);
if (Number.isNaN(n)) return true;
const r = (n >> 16) & 255, g = (n >> 8) & 255, b = n & 255;
return r * 299 + g * 587 + b * 114 > 148000;
}
const __TwkCheck = ({ light }) => (
<svg viewBox="0 0 14 14" aria-hidden="true">
<path d="M3 7.2 5.8 10 11 4.2" fill="none" strokeWidth="2.2"
strokeLinecap="round" strokeLinejoin="round"
stroke={light ? 'rgba(0,0,0,.78)' : '#fff'} />
</svg>
);
// TweakColor — curated color/palette picker. Each option is either a single
// hex string or an array of 1-5 hex strings; the card adapts — a lone color
// renders solid, a palette renders colors[0] as the hero (left ~2/3) with the
// rest stacked in a sharp column on the right. onChange emits the
// option in the shape it was passed (string stays string, array stays array).
// Without options it falls back to the native color input for back-compat.
function TweakColor({ label, value, options, onChange }) {
if (!options || !options.length) {
return (
<div className="twk-row twk-row-h">
<div className="twk-lbl"><span>{label}</span></div>
<input type="color" className="twk-swatch" value={value}
onChange={(e) => onChange(e.target.value)} />
</div>
);
}
// Native <input type=color> emits lowercase hex per the HTML spec, so
// compare case-insensitively. String() guards JSON.stringify(undefined),
// which returns the primitive undefined (no .toLowerCase).
const key = (o) => String(JSON.stringify(o)).toLowerCase();
const cur = key(value);
return (
<TweakRow label={label}>
<div className="twk-chips" role="radiogroup">
{options.map((o, i) => {
const colors = Array.isArray(o) ? o : [o];
const [hero, ...rest] = colors;
const sup = rest.slice(0, 4);
const on = key(o) === cur;
return (
<button key={i} type="button" className="twk-chip" role="radio"
aria-checked={on} data-on={on ? '1' : '0'}
aria-label={colors.join(', ')} title={colors.join(' · ')}
style={{ background: hero }}
onClick={() => onChange(o)}>
{sup.length > 0 && (
<span>
{sup.map((c, j) => <i key={j} style={{ background: c }} />)}
</span>
)}
{on && <__TwkCheck light={__twkIsLight(hero)} />}
</button>
);
})}
</div>
</TweakRow>
);
}
function TweakButton({ label, onClick, secondary = false }) {
return (
<button type="button" className={secondary ? 'twk-btn secondary' : 'twk-btn'}
onClick={onClick}>{label}</button>
);
}
// Opt out of DCViewport's transform so position:fixed works against the viewport.
TweaksPanel.dcOverlay = true;
Object.assign(window, {
useTweaks, TweaksPanel, TweakSection, TweakRow,
TweakSlider, TweakToggle, TweakRadio, TweakSelect,
TweakText, TweakNumber, TweakColor, TweakButton,
});
// ── TweakSuggestionBar (flag-gated addon) ───────────────────────────────────
(function () {
const s = document.createElement('style');
s.textContent = `
@keyframes twk-blink{50%{opacity:0}}
@keyframes twk-fadein{from{opacity:0;transform:translateX(4px)}to{opacity:1;transform:none}}
.twk-sugg{display:flex;align-items:center;gap:6px;padding:5px 8px;border-radius:8px;
background:rgba(0,0,0,.04);border:.5px solid rgba(0,0,0,.06);transition:all .15s}
.twk-sugg:focus-within{background:rgba(0,0,0,.06);border-color:rgba(0,0,0,.12)}
.twk-sugg-field{position:relative;flex:1;min-width:0}
.twk-sugg-field input{width:100%;height:20px;border:0;background:transparent;
font:inherit;outline:none;color:inherit}
.twk-sugg-ghost{position:absolute;inset:0;display:flex;align-items:center;
color:rgba(41,38,27,.42);pointer-events:none;white-space:nowrap;overflow:hidden}
.twk-sugg-ghost.hint{color:rgba(41,38,27,.28)}
.twk-sugg-caret{display:inline-block;width:1px;height:13px;margin-left:1px;
border-right:1.5px solid currentColor;opacity:.5;animation:twk-blink 1s step-end infinite}
.twk-sugg-ideas{appearance:none;border:0;background:transparent;font:inherit;
font-size:10.5px;font-weight:600;color:rgba(41,38,27,.6);cursor:default;padding:0 2px;
white-space:nowrap;animation:twk-fadein .25s ease}
.twk-sugg-ideas:hover{color:rgba(41,38,27,.85)}
.twk-sugg-ideas svg{color:#D97757}
.twk-sugg-send{appearance:none;border:0;height:20px;padding:0 8px;border-radius:5px;
background:#29261b;color:#fff;font:inherit;font-size:10px;font-weight:600;cursor:default}
`;
document.head.appendChild(s);
})();
const __twkSendChat = (text) =>
window.parent.postMessage({ type: 'miaoda:tweaks:chat', text }, '*');
const __TWK_SPARK_PATH = 'M18.3658 62.2435L36.7823 51.9165L37.0858 51.012L36.7823 50.5083H35.8716L32.7853 50.3206L22.2616 50.0389L13.1546 49.6634L4.30054 49.194L2.07438 48.7246L0 45.9551L0.202378 44.5938L2.07438 43.3264L4.75589 43.5611L10.6755 43.9836L19.5801 44.5938L26.0056 44.9693L35.568 45.9551H37.0858L37.2882 45.3448L36.7823 44.9693L36.3775 44.5938L27.1693 38.3507L17.2022 31.7789L11.9909 27.9767L9.20822 26.0522L7.79157 24.2684L7.18443 20.3254L9.71416 17.5089L13.1546 17.7436L14.0147 17.9783L17.5057 20.654L24.9431 26.4277L34.6573 33.5627L36.0739 34.7362L36.6444 34.3512L36.7317 34.079L36.0739 32.9994L30.8121 23.4704L25.1961 13.7537L22.6664 9.71675L22.0086 7.32277C21.7539 6.31812 21.6039 5.48695 21.6039 4.45938L24.4878 0.516349L26.1068 0L30.0026 0.516349L31.6216 1.92457L34.0502 7.46359L37.9459 16.1476L44.0173 27.9767L45.7881 31.4973L46.7494 34.7362L47.1036 35.722H47.7107V35.1587L48.2166 28.4931L49.1274 20.3254L50.0381 9.81063L50.3416 6.85336L51.8089 3.28586L54.7434 1.36128L57.0201 2.44092L58.8921 5.11655L58.6391 6.85336L57.5261 14.0822L55.3505 25.395L53.9338 32.9994H54.7434L55.7047 32.0136L59.5498 26.944L65.9753 18.8702L68.8086 15.6782L72.1479 12.1577L74.2729 10.4678H78.3204L81.2549 14.8802L79.9395 19.4335L75.7907 24.6909L72.3503 29.1503L67.4173 35.7593L64.3563 41.0732L64.6308 41.5116L65.3682 41.4487L76.499 39.0548L82.5198 37.9751L89.7042 36.7547L92.9423 38.2568L93.2964 39.8058L92.0316 42.9509L84.3412 44.8285L75.3354 46.6592L61.9245 49.8162L61.776 49.9356L61.9513 50.1956L67.9991 50.743L70.5795 50.8839H76.9038L88.6923 51.7757L91.7786 53.7942L93.6 56.282L93.2964 58.2066L88.5405 60.6006L82.1656 59.0985L67.2402 55.531L62.1302 54.2636H61.4218V54.6861L65.6718 58.8638L73.514 65.9049L83.2787 75.0114L83.7846 77.2646L82.5198 79.0483L81.2043 78.8606L72.6032 72.3827L69.264 69.4724L61.776 63.1354H61.2701V63.7926L62.9903 66.3274L72.1479 80.081L72.6032 84.3057L71.9455 85.667L69.5676 86.5119L66.9872 86.0425L61.5736 78.4851L56.0588 70.0357L51.6065 62.4313L51.0687 62.7708L48.419 91.0652L47.2048 92.5204L44.3715 93.6L41.9935 91.8162L40.7286 88.9059L41.9935 83.1322L43.5114 75.6217L44.7256 69.6602L45.8387 62.2435L46.5185 59.7659L46.4584 59.6001L45.9153 59.6914L40.3239 67.3601L31.824 78.8606L25.0949 86.0425L23.4759 86.6997L20.6932 85.2445L20.9462 82.6628L22.5146 80.3627L31.824 68.5336L37.44 61.1639L41.0595 56.9335L41.0243 56.3216L40.8245 56.3046L16.0891 72.4297L11.6874 72.993L9.76476 71.2092L10.0177 68.2989L10.9284 67.3601L18.3658 62.2435Z';
function ClaudeSpark({ size = 12 }) {
return (
<svg width={size} height={size} viewBox="0 0 94 94" fill="currentColor"
style={{ display: 'inline-block', verticalAlign: '-1px' }}>
<path d={__TWK_SPARK_PATH} />
</svg>
);
}
// Typewriter-cycles through `suggestions`. Clicking the field while a
// suggestion is animating freezes it as ghost text; Tab accepts it into the
// input. Enter posts miaoda:tweaks:chat (host drops the text into the chat
// composer for the user to send). After the cycle the static placeholder
// types in and "Ideas" appears — clicking asks for three more suggestions.
function TweakSuggestionBar({
suggestions = [],
placeholder = 'Describe a tweak…',
ideasPrompt = 'Suggest three more tweak ideas for this design and update the suggestions on TweakSuggestionBar.',
}) {
const [val, setVal] = React.useState('');
const [ghost, setGhost] = React.useState('');
const [focused, setFocused] = React.useState(false);
const inputRef = React.useRef(null);
const tw = useTwkTypewriter(suggestions, { placeholder, enabled: !val && !ghost && !focused });
const freeze = () => {
tw.markPlayed();
if (val || ghost) return;
const target = !tw.done ? suggestions[tw.idx] : '';
if (target) setGhost(target);
inputRef.current?.focus();
};
const submit = () => {
const v = (val || ghost).trim();
if (!v) return;
__twkSendChat(v);
setVal('');
setGhost('');
};
const onKeyDown = (e) => {
if (e.key === 'Tab' && ghost && !val) {
e.preventDefault();
setVal(ghost);
setGhost('');
} else if (e.key === 'Enter') {
e.preventDefault();
submit();
} else if (e.key === 'Escape') {
setGhost('');
}
};
const requestIdeas = () => __twkSendChat(ideasPrompt);
const showAnim = !val && !ghost && !focused && !tw.done;
const showStatic = !val && !ghost && !focused && tw.done;
return (
<div className="twk-sugg" onMouseDown={freeze}>
<div className="twk-sugg-field">
<input
ref={inputRef}
value={val}
placeholder={focused && !ghost ? placeholder : ''}
onChange={(e) => { setVal(e.target.value); setGhost(''); }}
onFocus={() => { setFocused(true); tw.markPlayed(); }}
onBlur={() => { setFocused(false); if (!val) setGhost(''); }}
onKeyDown={onKeyDown}
/>
{showAnim && (
<div className="twk-sugg-ghost">
{tw.text}<span className="twk-sugg-caret" />
</div>
)}
{showStatic && (
<div className="twk-sugg-ghost">
{tw.tail}{tw.tail.length < placeholder.length && <span className="twk-sugg-caret" />}
</div>
)}
{ghost && !val && (
<div className="twk-sugg-ghost hint">{ghost}</div>
)}
</div>
{val || ghost ? (
<button className="twk-sugg-send"
onMouseDown={(e) => { e.stopPropagation(); e.preventDefault(); }}
onClick={submit}>
Add
</button>
) : tw.done && !focused ? (
<button className="twk-sugg-ideas"
onMouseDown={(e) => { e.stopPropagation(); e.preventDefault(); }}
onClick={requestIdeas}>
Ideas <ClaudeSpark />
</button>
) : null}
</div>
);
}
// Minimal type→pause→erase cycler. Plays once per unique `items` content per
// session — a reload from a tweak-value write skips straight to done; a new
// suggestion set (after "Ideas") gets a fresh animation.
function useTwkTypewriter(items, { placeholder, typeMs = 35, eraseMs = 22, pauseMs = 1800, enabled = true } = {}) {
const key = React.useMemo(() => '__twk_played:' + JSON.stringify(items), [items.join('\n')]);
const played = () => { try { return sessionStorage.getItem(key) === '1'; } catch { return false; } };
const [text, setText] = React.useState('');
const [tail, setTail] = React.useState(() => (items.length === 0 || played() ? placeholder : ''));
const [idx, setIdx] = React.useState(0);
const [done, setDone] = React.useState(() => items.length === 0 || played());
const phase = React.useRef('type');
const n = React.useRef(0);
const markPlayed = React.useCallback(() => {
try { sessionStorage.setItem(key, '1'); } catch {}
setDone(true);
}, [key]);
React.useEffect(() => {
const skip = items.length === 0 || played();
setText(''); setIdx(0);
setDone(skip);
setTail(skip ? placeholder : '');
phase.current = 'type'; n.current = 0;
}, [key]);
React.useEffect(() => {
if (done || !enabled) return;
const item = items[idx] ?? '';
let t;
const tick = () => {
if (phase.current === 'type') {
n.current++;
setText(item.slice(0, n.current));
if (n.current >= item.length) { phase.current = 'pause'; t = setTimeout(tick, pauseMs); }
else t = setTimeout(tick, typeMs + Math.random() * 20);
} else if (phase.current === 'pause') {
phase.current = 'erase'; t = setTimeout(tick, eraseMs);
} else {
n.current--;
setText(item.slice(0, n.current));
if (n.current <= 0) {
if (idx === items.length - 1) { markPlayed(); return; }
phase.current = 'type'; setIdx((i) => i + 1);
} else t = setTimeout(tick, eraseMs);
}
};
phase.current = 'type'; n.current = 0; setText('');
t = setTimeout(tick, 400);
return () => clearTimeout(t);
}, [idx, done, key, enabled, typeMs, eraseMs, pauseMs]);
React.useEffect(() => {
if (!done || tail === placeholder) return;
let i = 0;
const t = setInterval(() => {
i++; setTail(placeholder.slice(0, i));
if (i >= placeholder.length) clearInterval(t);
}, 28);
return () => clearInterval(t);
}, [done, placeholder]);
return { text, tail, idx, done, markPlayed };
}
Object.assign(window, { TweakSuggestionBar });

View File

@@ -12,8 +12,10 @@
- 「(审批 / 报销 / 请假 / 出差)(通过 / 拒绝 / 提交 / 撤回)后自动 X」→ `+automation-create --trigger-type feishu-approval`
- 「这个应用配了哪些(自动化 / 触发器 / 定时任务)」→ `+automation-list`
- 「(暂停 / 停用 / 先别自动跑 / 关掉自动触发)某个(触发器 / 定时任务 / 自动化)」→ `+automation-disable`(不是 update 改条件、不是 delete——本 skill 不提供删除)
- 「启用 / 启动已有 trigger」→ 先核对现有状态;只启用时不要修改源码或发布应用。
- 「换 / 重置 webhook 回调地址 / URL」→ `+automation-update --reset-url --app-env <preview|runtime>`
- 「换 / 重置 / 轮换 webhook token / bearer」→ `+automation-update --reset-token`
- 「触发器没反应 / enable 了不触发 / 为什么没执行 / 验证一下触发器」→ 先按「未触发时的诊断顺序」诊断;对 UPSERT 和 feishu-approval 仅验证配置边界,不承诺 handler 或 live 验证。
**边界(防误路由)**`lark-event` 是**实时事件流消费**agent 长连接订阅事件),不管妙搭应用触发器的**配置**;用户说「配 / 设置一个触发器」而不是「订阅事件流」时,本 skill 才是正确选择。「审批通过触发」在妙搭应用语境下属于本 skill 的 `feishu-approval` 类型,不是 lark-event。
@@ -146,6 +148,82 @@
创建成功后的推荐话术:`已创建 <name>,当前 disabled需要真正开始自动运行时告诉我我用 +automation-enable 启用它。` **不要**在创建成功后立即启用,即使 skill 里说"需 enable 才自动触发"——这条是给用户的说明,不是给 agent 的行动指令。
## 本地全栈 Trigger 闭环
当用户希望触发器实际执行业务代码时,先确认当前工作区是已初始化的应用项目,并读取其中与触发器任务匹配的 guide。
`--name` 是应用内唯一的 trigger 定位键;代码侧绑定名称必须与它逐字相同。不得用 trigger ID 或方法名代替它。具体 handler 语法和接入方式以项目 guide 为准。
### 仅创建/配置触发器
适用于 cron、record-change、webhook 和 feishu-approval。用 `+automation-create` 创建,并省略 `--status` 或显式传 `disabled`,然后报告 name 和 disabled 状态。
不要传 `--status enabled`,也不要写 handler、commit/push、release 或 enable更不能把创建 API 成功称为“可运行”。默认 disabled 是这个意图的终点,不是稍后自动 enable 的待办。
### 仅启用已有 disabled trigger
用户只要求启用已存在且 disabled 的 trigger、没有要求修改代码或制造真实 runtime 事件时,先用 `+automation-get` 核对 name、类型和 disabled 状态,再用 `+release-list --status finished --page-size 1` 核对是否存在已完成线上 release。release history 只能证明当前线上应用有已发布版本,不能证明该 trigger name 已绑定 handler。不存在 finished release 时说明 enable 只会改变配置状态、当前没有可执行的线上版本;存在时说明它会对当前线上应用激活这条 trigger 配置。随后按用户要求执行 `+automation-enable`,再用 `+automation-get` 确认 enabled。
这条路径不得修改 handler、commit/push 或 release。未发布时不得自动创建 release也不得声称 trigger 已开始实际运行。即使存在 finished release也只能把 enable 报告为配置激活;没有 handler 来源或 runtime 结果时,不得声称业务 handler 已存在、已运行或可用。若用户期待尚未发布的本地改动生效,或检查后发现确实需要新增/修改 handler转到下方“实现或更新 handler 后发布并启动/测试”路径;不要为单纯 enable 发布整个 `sprint/default`。
对 UPSERT 或 feishu-approval 只改变配置状态;由于本 guide 没有其已证实的 handler、投递或 live 验证契约,启用后也不得声称业务代码已运行或触发器已实测可用。
### 测试已有线上 trigger不改代码
用户要求测试已经发布的 trigger、没有要求修改 handler 时,先用 `+automation-get` 核对 name、类型、当前状态再用 `+release-list --status finished --page-size 1` 确认应用存在 finished release并说明本次测试覆盖当前线上代码。没有 finished release 时停止 runtime test只报告配置状态不得为测试自动修改源码、commit/push 或 release。release history 不证明该 name 已绑定 handler真实 probe 的结果才是本次验证证据;若用户期待本地未发布改动,改走代码变更闭环。
记录测试前状态,并在任何临时 enable 之前完成两类授权和全部 preflight测试请求已明确包含临时 enable或另行取得 enable 授权;同时按下方“运行时验证的操作级授权”确定具体事件、影响、载荷、观察结果和清理。原本 disabled 时完成这些门槛后才临时 enable并在验证结束后恢复 disabled原本 enabled 时不要无意义切换状态。原本为 disabled 时,无论 probe 成功、失败、结果不确定,还是临时 enable 后提前结束或中断,最终都必须 `+automation-disable` 并回读 disabled不得停在 enabled。测试意图本身不决定数据库记录、Webhook 请求或其他事件载荷。
### 仅完成 handler不发布/不启用)
仅对 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` 使用此路径。
创建或定位已明确 name 的 disabled trigger读取项目 guide按其要求实现同名业务 handler完成本地验证。只在既有 Git 确认或预授权下 commit/push停止在 `+release-create` 和 `+automation-enable` 之前。用户没有明确“发布好”时,先问,不能默认把完整应用上线。
### 把 handler 发布好,但先不要启动
仅对 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` 使用此路径。先用 `+automation-get` 定位;不存在时用 `+automation-create` 创建同名 disabled trigger再次回读确认。已存在时记录它是否 enabled。按项目 guide 完成同名业务 handler 并本地验证后commit、`git push origin sprint/default`。若 trigger 已 enabled先说明发布前必须临时停用以及可能造成的运行中断并取得这次临时停用授权未获授权时停止在发布前。取得授权后在发布前执行 `+automation-disable`,并再次用 `+automation-get` 确认 disabled。随后发布完整应用
```bash
lark-cli apps +release-create --as user --app-id <app_id> --branch sprint/default
```
若 `+release-create` 本身返回错误或未返回 `data.release_id`:视为确认未创建本轮 release新代码未上线原本 enabled 的 trigger 恢复 enabled 并回读、原本 disabled 的保持 disabled然后停止若因超时等导致创建结果未知保持 disabled先用 `+release-list --status finished --page-size 1` 核对是否已产生新 release 再决定。取得 `data.release_id` 后,对**这一轮** ID 调用 `+release-get``publishing` 时每 20 秒继续轮询,整体最多约 5 分钟;超时且状态仍不确定时报告 `release_id` 和当前 status并保持 disabled只有 `data.status=finished` 才算完成。确认 `failed` 且新代码未上线时,原本 enabled 的 trigger 恢复 enabled 并回读,原本 disabled 的保持 disabled。release 是整个应用上线可能影响既有线上功能未获得启动或测试授权时finished 后始终保持 disabled不执行 `+automation-enable`。
### 实现或更新 handler 后发布并启动/测试
仅当本轮确实需要新增或修改 cron、webhook、record-change 的 `INSERT`、`UPDATE`、`DELETE` handler且用户要求把这次代码发布后启动或测试时才使用此路径。按以下不可跳过的顺序执行
1. 用 `+automation-get` 定位并记录发布前状态,再核对其 `--name`、类型并读取项目 guide不存在时用 `+automation-create` 创建同名 trigger 并保持默认 disabled。
2. 按项目 guide 完成同名业务 handler 并本地验证。
3. 在 Git 已确认/预授权时 commit然后执行 `git push origin sprint/default`。
4. 若 trigger 当前 enabled先说明发布前必须临时停用以及可能造成的运行中断并取得这次临时停用授权未获授权时停止在发布前。取得授权后执行 `+automation-disable`,并再次用 `+automation-get` 确认 disabled原本 disabled 时不要无意义切换状态。
5. 执行 `+release-create --branch sprint/default`。若该命令本身返回错误或未返回 `data.release_id`:视为确认未创建本轮 release新代码未上线原本 enabled 的 trigger 恢复 enabled 并回读、原本 disabled 的保持 disabled 后停止;若因超时等导致结果未知,保持 disabled先用 `+release-list --status finished --page-size 1` 核对是否已产生新 release 再决定。取得 `data.release_id` 后进入下一步。
6. 对该 ID 执行 `+release-get`,只有 `data.status=finished` 才能继续;`publishing` 时每 20 秒继续轮询,整体最多约 5 分钟。超时且状态仍不确定时停止本轮轮询、报告 `release_id` 和当前 status并保持 disabled确认 `failed` 时报告发布失败,原本 enabled 的 trigger 仅在确认新代码未上线后恢复 enabled原本 disabled 的保持 disabled。发布状态仍不确定时不得进入 enable、probe 或状态恢复分支。`is_published=true` 不能代替这轮发布完成。
7. **仅启动**:取得持续启动授权后执行 `+automation-enable`,并用 `+automation-get` 确认 enabled到此结束不制造 runtime probe。
8. **测试(含“启动并测试”)**:先按下节“运行时验证的操作级授权”完成全部 preflight包括具体事件、sibling 影响、载荷、观察结果和清理;完成前保持 disabled之后才执行 `+automation-enable` 并回读,再由已授权主体制造真实 runtime 条件并核验业务结果。若同时明确要求持续启动,只有 probe 成功后才保持 enabled。
9. 若用户仅要求测试而不是持续启动,只在本轮 release 已 `finished` 且 probe 成功后恢复到发布前状态:原本 disabled 或本轮新建的 trigger `+automation-disable` 并回读;原本 enabled 的可保持 enabled。无论用户是仅测试还是启动并测试probe 失败、结果不确定或 enable 后提前结束时,一律 `+automation-disable` 并回读 disabled不得把“发布前 enabled”当作失败后的恢复依据因为本轮新代码已经上线。只有旧 release 已回滚并验证,或修复后重新发布且 probe 成功,才可再次 enabled。恢复失败时明确报告当前状态。
没有通用的 `automation-debug` 或 trigger 日志 shortcut。缺少安全事件入口、匹配环境或可观察结果时记录 blocked不能编造测试成功。
### 运行时验证的操作级授权
启用 trigger 的授权不等于制造 runtime 事件的授权测试授权也不等于任意数据库写入授权。cron 可等待计划时间webhook 只能向既有 runtime URL 发送已授权、安全且不泄露凭证的请求。record-change 在执行任何 DML 前必须明确并取得覆盖以下作用域的授权环境、表、操作、精确测试记录或筛选条件、payload、预期结果和清理方式。
优先使用专用测试记录不要任取线上业务记录。用户已明确授权精确、可撤回的测试夹具及其清理时不机械追加一轮确认目标或影响仍不清楚时必须停下。record-change probe 前先执行 `+automation-list --trigger-type record-change --all`,检查同一环境、表和操作可能命中的其他 enabled trigger若存在 sibling match必须说明聚合业务影响并取得覆盖这些影响的授权或换成隔离夹具/经授权临时停用后再测。`UPDATE` 要限定精确条件并保留恢复方式;`INSERT` 要预先约定清理;恢复 UPDATE 或清理 INSERT 也可能再次触发自动化,必须纳入影响说明和授权。`DELETE` 必须遵循 [lark-apps-db-execute.md](lark-apps-db-execute.md):先 `SELECT count(*)`、执行 `--dry-run`,展示影响后取得针对该删除目标的明确授权,再带 `--yes` 执行;清理动作若包含未预先授权的删除,同样走该门槛。
缺少安全、已授权且可清理的事件入口时,记录 blocked不得用“测试一下”推导任意 online 数据写入。
### UPSERT 与飞书审批边界
record-change 的 UPSERT 可创建 disabled 配置,但当前没有已证实的运行时代码契约;不得静默按 UPDATE 处理,也不得承诺 handler 或 live 验证。
feishu-approval 可创建 disabled 配置,并读取或更新 `event_type`、对应 status 和可选 `approval_code`。当前没有已证实的运行时 handler 契约或实际投递验证;不要把 enable 或审批 API 成功称为业务代码已执行。
### 未触发时的诊断顺序
按 `--name` / 项目 guide 要求的代码接入 → 本轮 release `finished` → enabled 状态 → 类型条件、环境和已有日志的顺序排查。客户审批投递故障属于服务端事件投递排查,不要归因于此 SOP 或改写无关业务代码。
## 常见错误与决策场景
| 现象 / 用户意图 | 正确处理 |
@@ -154,11 +232,11 @@
| cron 报非法 / 间隔过小 | 检查是否五段式、分钟字段是否 `*` 或 `*/n`(n<30) |
| `--reset-url` 报缺 app-env | 补 `--app-env preview` 或 `--app-env runtime` |
| 想把 cron 触发器改成 webhook跨类型改 | update 不支持换类型,本 skill 也不提供删除。旧触发器只能 `+automation-disable` 停用(保留在应用里),另建一个 webhook 触发器;若要真正清理旧触发器,请到妙搭 web 手动删除 |
| 触发器 enable 了但不触发 | 确认应用**已发布**;触发器跑的是线上已发布代码 |
| 触发器 enable 了但不触发 | 已证实的 cron、webhook、record-changeINSERT/UPDATE/DELETE按「未触发时的诊断顺序」排查UPSERT 和 feishu-approval 仅核对配置边界,不承诺 handler 或 live 验证。 |
| 「token 泄露了」 | 优先 `+automation-update --reset-token --yes` 轮换(旧 token 立即失效),而非直接 disable-token 关校验 |
| 「回调 URL 泄露了」 | `+automation-update --reset-url --app-env <env> --yes` 轮换 |
## 不在本 skill 范围
- 审批定义查询、Webhook 消费端实现、实时触发日志 tail本期不支持。
- 身份选择、权限不足处理、exit-10 审批、通用「禁输出密钥」红线、高风险操作通用框架:见 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),不在此重复。
- 身份选择、权限不足处理、exit-10 审批、通用「禁输出密钥」红线、高风险操作通用框架:见 [`../../lark-shared/SKILL.md`](../../lark-shared/SKILL.md),不在此重复。

View File

@@ -116,5 +116,4 @@ lark-cli apps +session-list --app-id app_xxx
## 不适用
- 用户已有本地 HTML/dist要马上发布 URL读 [`lark-apps-html-publish.md`](lark-apps-html-publish.md)。
- 用户要本地写代码、改仓库、跑 dev server读 [`lark-apps-local-dev.md`](lark-apps-local-dev.md)。

View File

@@ -35,6 +35,5 @@ lark-cli apps +create --name "Demo" --app-type html --dry-run
创建后按用户路径继续:
- 发布现成 HTML/静态目录:读 [`lark-apps-html-publish.md`](lark-apps-html-publish.md)。
- 本地全栈开发:读 [`lark-apps-local-dev.md`](lark-apps-local-dev.md)。
- 本地应用开发(含 html 和 full_stack:读 [`lark-apps-local-dev.md`](lark-apps-local-dev.md)。
- 云端 Agent 生成/迭代:读 [`lark-apps-cloud-dev.md`](lark-apps-cloud-dev.md)。

View File

@@ -1,6 +1,6 @@
# apps db 域命令
管理妙搭应用数据库:看表与结构、初始化与发布多环境、数据搬运、变更治理、时间点恢复、用量。逐条跑 SQLSELECT/DML/DDL走 [`+db-execute`](lark-apps-db-execute.md)(单独一篇)。运行时命令事实以 `lark-cli apps +<cmd> --help` 为准;认证、`--as user`、exit 码、`_notice` 等通用处理见 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md) 与本域 [`SKILL.md`](../SKILL.md)。
管理妙搭应用数据库:看表与结构、初始化与发布多环境、数据搬运、变更治理、时间点恢复、用量。逐条跑 SQLSELECT/DML/DDL走 [`+db-execute`](lark-apps-db-execute.md)(单独一篇)。运行时命令事实以 `lark-cli apps +<cmd> --help` 为准;认证、`--as user`、exit 码、`_notice` 等通用处理见 [`../../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 与本域 [`SKILL.md`](../SKILL.md)。
## 何时用

View File

@@ -33,5 +33,5 @@ lark-cli apps +env-pull --app-id <app_id>
## 参考
- [lark-apps](../SKILL.md) — 妙搭应用全部命令 + 心智模型
- [lark-apps-local-dev](lark-apps-local-dev.md) — 本地全栈开发端到端流程
- [lark-apps-local-dev](lark-apps-local-dev.md) — 本地应用开发端到端流程
- [lark-shared](../../lark-shared/SKILL.md) — 认证和全局参数

View File

@@ -1,6 +1,6 @@
# apps file 域命令(应用存储)
管理妙搭应用的文件存储:上传 / 下载本地文件、列出与查看已存文件、生成临时分享链接、批量删除、查看用量。运行时命令事实以 `lark-cli apps +<cmd> --help` 为准;认证、`--as user`、exit 码、`_notice` 等通用处理见 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md) 与本域 [`SKILL.md`](../SKILL.md)。
管理妙搭应用的文件存储:上传 / 下载本地文件、列出与查看已存文件、生成临时分享链接、批量删除、查看用量。运行时命令事实以 `lark-cli apps +<cmd> --help` 为准;认证、`--as user`、exit 码、`_notice` 等通用处理见 [`../../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 与本域 [`SKILL.md`](../SKILL.md)。
## 何时用

View File

@@ -12,7 +12,7 @@ lark-cli apps +git-credential-remove --app-id app_xxx
## 输出契约
- `+git-credential-init` 成功后读取 `data.repository_url`;不要展示或保存其中的凭据细节,只用于下一步 `git clone`
- `+git-credential-init` 成功后读取 `data.repository_url`;不要展示或保存其中的凭据细节,只用于下一步 `git clone`响应还包含 `data.commit_author_name``data.commit_author_email`,这两个字段由 `+init` 内部消费,自动写入仓库 repo-local git config`user.name` / `user.email`agent 和用户无需手动配置。
- `+git-credential-list` 返回本地记录和状态;可用来判断是否需要重新 init。
- `+git-credential-remove` 只清本地配置;成功后告知不会删除云端应用或仓库。

View File

@@ -9,6 +9,7 @@
## 命令骨架
- 必填:`--app-id``--path`
- `--path` **必须是相对路径**(如 `./dist``./index.html`),不支持绝对路径。如果目标文件在其他目录,先 `cd` 到该目录再用相对路径,或用相对于当前目录的路径。
- `--path` 可以是单个文件或目录;入口必须是 `index.html`
- 可选:`--allow-sensitive`,跳过凭据文件扫描。
- 客户端打包 tar.gz 上传发布。三条硬性大小限制,任一超限即被客户端拒绝、无法发布:单个 `.html` 文件 ≤ 10MB、打包后 tar.gz ≤ 20MB、未压缩候选文件总量 ≤ 200MB。
@@ -23,19 +24,13 @@ lark-cli apps +html-publish --app-id app_xxx --path ./index.html --dry-run
## 输出契约
根据应用类型,输出字段不同:
- **静态 HTML 应用**`data.url` 是本轮发布后的访问链接,一步完成发布。
- **其他 HTML 应用**`data.release_id` 是发布标识,命令内部已完成产物上传和发布创建。用 `+release-get --app-id <app_id> --release-id <release_id>` 轮询发布状态直到 `finished`
判断走哪条路径:有 `url` 字段说明已直接发布完成;有 `release_id` 字段说明需要用 `+release-get` 轮询。
命令内部完成 tar.gz 打包 → TOS 上传 → 触发发布,返回 `data.release_id`。拿到 `release_id` 后用 `+release-get --app-id <app_id> --release-id <release_id>` 轮询发布状态直到 `finished`,从中读取 `online_url`
- 业务失败如构建失败、应用不存在通常带 `error.hint`;优先转述 hint。网络/服务端失败则建议稍后重试。
## 链接边界
- 开发态链接可由 `app_id` 拼出:`https://miaoda.feishu.cn/app/{app_id}`,用于进入妙搭编辑/开发态
- 发布态访问链接以本命令成功返回的 `data.url` 为准。
- 发布态访问链接以 `+release-get` 轮询 `finished` 返回的 `online_url` 为准
- 重新发布前,`+list``is_published=true` 只能说明历史上发布过,不代表当前本地产物已经部署。
## 发布前置门(第一步,先于任何其他动作)
@@ -59,4 +54,5 @@ lark-cli apps +html-publish --app-id app_xxx --path ./index.html --dry-run
## 常见失败
- `--path` 传了绝对路径:`--path` 只接受相对路径,传绝对路径会报 `--path must be a relative path within the current directory`。改用 `cd` + 相对路径,例如 `cd /target/dir && lark-cli apps +html-publish --path .`
- 缺少 `index.html`:目录根放置 `index.html`,或单文件路径直接指向名为 `index.html` 的文件。

View File

@@ -4,7 +4,7 @@
## 何时用
用于把妙搭全栈应用源码拉到本地并准备开发环境。用户只是要云端 Agent 生成应用时,不要初始化本地仓库。
用于把妙搭应用源码拉到本地并准备开发环境。用户只是要云端 Agent 生成应用时,不要初始化本地仓库。
## 命令骨架

View File

@@ -34,4 +34,4 @@ lark-cli apps +list --page-token "<cursor>"
多候选时展示名称、app_id、updated_at 让用户确认。用户描述里已经有 `app_xxx` 或妙搭链接时,直接提取,不再 `+list`
`+list` 当定位工具和发布态快照工具,不要把 `is_published` 当部署完成证明。需要证明“最新内容已上线”时,使用对应发布命令的完成状态:全栈`+release-get``finished`HTML 看 `+html-publish` 的成功返回
`+list` 当定位工具和发布态快照工具,不要把 `is_published` 当部署完成证明。需要证明“最新内容已上线”时,使用对应发布命令的完成状态:看 `+release-get``finished`

View File

@@ -1,6 +1,6 @@
# lark-apps 本地全栈开发
# lark-apps 本地开发
适用:用户要把妙搭全栈应用源码拉到本地,用本地 code agent/IDE 开发、调试数据库,再发布。
适用:用户要把妙搭应用full_stack 或 html源码拉到本地,用本地 code agent/IDE 开发、调试数据库,再发布。
## 新建 vs 已有应用
@@ -11,15 +11,17 @@
## 端到端流程(新建应用)
`+create(full_stack)` -> `+init`(或手动 `+git-credential-init` + `git clone`-> 读仓库 Skill -> `npm install && npm run dev` -> 按需 `+db-*` 调库 -> `git add` + `git commit`(提交本次改动)-> `git push origin sprint/default` -> `+release-create` -> `+release-get`
### full_stack
`+create(full_stack)` -> `+init`(或手动 `+git-credential-init` + `git clone`-> 读仓库 Skill -> `npm install && npm run dev` -> 按需 `+db-*` 调库 -> 非自动化改动按本页 commit/push/release包含自动化 handler 时,在任何 release 前转到 [automation SOP](lark-apps-automation.md),由它接管状态门禁和完整发布。
```bash
# 新建 full_stack 应用
lark-cli apps +create --name "审批系统" --app-type full_stack \
lark-cli apps +create --as user --name "审批系统" --app-type full_stack \
--description "支持登录、提交申请、多级审批、状态查询"
# 初始化本地仓库(--dir 取值见下方「领域规则」,勿照抄此处示例值)
lark-cli apps +init --app-id app_xxx --dir ./approval-app
lark-cli apps +init --as user --app-id app_xxx --dir ./approval-app
# 进入仓库后按项目脚手架启动
cd ./approval-app
@@ -31,35 +33,77 @@ npm run dev
git add <本次开发的文件> # 提交粒度见下方「改完代码后部署上线」
git commit -m "feat: ..."
git push origin sprint/default
lark-cli apps +release-create --as user --app-id app_xxx --branch sprint/default
```
### html
#### 首次开发(无 app无代码
`+create(html)``+init` → 加载 [`creative-design`](../creative-design/SKILL.md) skill 在 repo 根目录产出文件 → `git add .` + `git commit``git push origin sprint/default``+release-create``+release-get`
```bash
lark-cli apps +create --name "活动页" --app-type html --as user
lark-cli apps +init --app-id app_xxx --dir ./my-page
cd ./my-page
# html 类型无需 npm install+init 已跳过依赖安装
# 加载 creative-design skill在 repo 根目录产出 HTML 及关联文件JSX 组件、starter components 等)
git add .
git commit -m "feat: ..."
git push origin sprint/default
lark-cli apps +release-create --app-id app_xxx
```
#### 已有 app二次开发/迭代
`+init`(拉取远程代码)→ 加载 creative-design skill 在 repo 根目录迭代 → `git add .` + `git commit``git push origin sprint/default``+release-create``+release-get`
#### creative-design 已提前生成文件,需要 init 后迁入
`+create(html)``+init` → 先 `ls` 查看 repo 根目录模板结构(创意模式模板无 `src/` 目录,文件直接放根目录)→ 将已生成的所有产出文件HTML、JSX 组件、starter components 等)拷贝到 repo 根目录 → `git add .` + `git commit``git push origin sprint/default``+release-create``+release-get`
`+init` 是推荐便捷入口;想逐步手动控制时,先 `+git-credential-init``repository_url`,再用原生 `git clone` / `git checkout sprint/default`
**`+init` 完成后必须执行**`cat <project-path>/.agents/skills/plugin-guide/SKILL.md`,读取仓库插件指引。该文件包含插件目录、实例配置规则和调用代码生成方式——不读就无法正确集成插件能力。文件不存在则跳过。
## Trigger guide 的项目边界
涉及自动化业务代码时,先查看工作区 `.agents/skills/`,读取与自动化任务匹配的 `trigger-guide`。它定义业务 handler 的实现与接入约束Apps 触发器配置细节见 [automation SOP](lark-apps-automation.md)。
文件缺失或不能覆盖当前任务时,报告项目缺少可用的领域 guide不要在本 lark-cli reference 中猜测安装命令、版本或包内目录。由项目维护方通过其受支持的初始化或同步流程补齐后,再继续代码闭环;`+init` 只负责准备本地项目,不能替代领域 guide。
## 改完代码后部署上线
已拉到本地、改完代码,用户说"推上去""部署""上线""发布到云端"时,按此序列。
若本次改动包含自动化 handler在执行本节通用 commit/push/release 序列前就转到 [automation SOP](lark-apps-automation.md) 的匹配路径,由该 SOP 负责完整的状态门禁、commit/push、release 和可选 enable/test不要先按本节发布再补 trigger 状态检查。下列通用序列只用于不含自动化 handler 的改动。
> `+release-create` 部署的是远端 `sprint/default` 上**已 push** 的代码,不是你本地工作区——未 commit / 未 push 的改动不会进入这次发布。所以发布前务必先把本次改动提交并推送。
1. `git status` 看本次改动;`git add <本次相关文件>` 暂存后 `git commit` 提交。只提交本次任务相关的改动即可,无关的零散文件不必强求清空——发布门禁是「**本次相关改动已提交并推送**」,不是「工作区绝对干净」。
2. `git push origin sprint/default` 把工作分支推到云端(遇非 fast-forward`git pull --rebase origin sprint/default` 解决冲突再推,绝不 force-push
3. `lark-cli apps +release-create --app-id <app_id>` 发起部署上线,记下返回的 `release_id`
4. `lark-cli apps +release-get --app-id <app_id> --release-id <release_id>` 轮询:`publishing` 继续轮询;`finished` 成功时该命令输出已含 `online_url`,直接读取它返回给用户(这是本轮发布完成后的可分享链接),无需再调 `+list``failed`该命令输出已含 `error_logs`直接据此给出失败原因(`+list` 仅作独立查询入口)。
2. `git push origin sprint/default` 把工作分支推到云端(遇非 fast-forward`git pull --rebase origin sprint/default` 解决冲突再推,绝不 force-push;遇 Git 认证失败 / 401 / 403 / credential helper 缺失 / token 过期:先执行 `lark-cli apps +git-credential-init --app-id <app_id> --as user` 刷新本地 Git 凭证,再重试原 git 命令;刷新凭证也失败时,停止并向用户报告错误,不要换路)。
3. `lark-cli apps +release-create --as user --app-id <app_id> --branch sprint/default` 发起部署上线,记下返回的 `release_id`
4. `lark-cli apps +release-get --as user --app-id <app_id> --release-id <release_id>` 轮询:`publishing` 时每 20 秒继续轮询,整体最多约 5 分钟;超时仍未完成时停止本轮轮询、报告 `release_id` 和当前 status。`finished` 成功时,若返回 `online_url`直接使用;未返回时不要编造链接。交付线上访问链接给他人前,注意 `online_url` 默认仅创建者可见,需先告知当前仅本人可见、按需用 `+access-scope-set` 放开可见范围。无需再调 `+list``failed`若返回非空 `error_logs`,据此给出失败原因;否则只报告 `release_id` 和当前 status不要编造原因`+list` 仅作独立查询入口)。
用户只要求启用已有 trigger 时,转到 [automation SOP 的「仅启用已有 disabled trigger」路径](lark-apps-automation.md#仅启用已有-disabled-trigger);不得因 enable 反向修改 handler、commit/push 或 release。
## 领域规则
- 代码读写走原生 `git`CLI 负责凭证、初始化、发布和数据库调试。不存在 `apps +pull` / `apps +push` / `apps code +read` 这类代码读写 shortcut不要臆造。
- 工作环境没有 `git` 时,先引导安装 GitmacOS 可用 `xcode-select --install``brew install git`Linux 按发行版包管理器安装),安装后重试原 `+init` / git 命令;不要因此改走其他发布链路。
- `+init` 会编排 `+git-credential-init``git clone`、切到 `sprint/default`、运行脚手架,并在有变更时提交/推送。
- `+init --dir` 选目录:用户已预授权或表达"不要询问"(见 SKILL.md「预授权判定」→ 按应用名派生 `./<app-name>` 直接传 `--dir`、不停问;否则先问用户用哪个目录再传。目标已存在/非空时回问换目录。
- `sprint/default` 是工作分支;`main` 是发布态快照,由 `+release-create` 成功后服务端 fast-forward 推进;服务端护栏禁直推 `main`、拒 force-push、要求 `sprint/default` fast-forward。
- 已拉到本地后pull/push/diff/log 都用原生 git云端 `sprint/default` 比本地新时,先 `git pull --rebase origin sprint/default`,解决冲突后再 push 和 publish。
- `git clone` / `git pull` / `git push` 如果报认证失败、401/403、credential helper 缺失或 token 过期,优先重新执行 `lark-cli apps +git-credential-init --app-id <app_id> --as user` 更新本地 Git 凭证,然后重试原 git 命令;刷新凭证也失败时,停止并向用户报告错误,不要换路;不要手动复制 token、不要把 token 拼进 remote URL。
- 环境变量由脚手架在本地启动时处理;需要手动刷新时用 `+env-pull`
- 资源型文件(图片、字体、音视频等)不要直接引用本地路径,也不要提交到 git 仓库或以 base64 内联到代码中。先通过 `lark-cli apps +file-upload --app-id <app_id> --file <local_path>` 上传到应用文件存储,拿到返回的远端 URL 后在代码中引用该 URL。详情读 [`lark-apps-file.md`](lark-apps-file.md)。上传返回的链接按 app 隔离,不同应用必须各自重新上传,不能跨应用复用同一链接。
- DB 调试用 `+db-table-list` / `+db-table-get` / `+db-execute`;不要裸连数据库或自行拼连接串。
- DB 分 `dev` / `online`日常调试优先 `--env dev`。dev 的库结构变更要上线时,仍按应用发布链路走 `+release-create`,不要另造“数据库发布”步骤。
- 存量单库应用需要 dev/online 多环境时,用 `+db-env-create --env dev`。这是不可逆 high-risk 操作。
- DB 分 `dev` / `online`使用 `--environment dev|online`,不要使用旧的 `--env`。只有确认应用已开启多环境时才引导 `--environment dev`;单环境应用省略 `--environment`(服务端选 online或显式传 `--environment online`。在 dev 写入不能证明线上 handler 已验证。dev 的库结构变更要上线时,仍按应用发布链路走 `+release-create`,不要另造“数据库发布”步骤。
- 存量单库应用需要 dev/online 多环境时,用 `+db-env-create --environment dev`。这是不可逆 high-risk 操作。
- 只从 `+list` 看到 `is_published=true`,不能证明本地刚推送的代码已经部署;必须有本轮 `+release-get finished`
## 存量应用入口
@@ -74,5 +118,4 @@ lark-cli apps +list --keyword "应用名"
## 何时不用
- 用户只想发布现成 HTML / 静态目录拿分享链接:读 [`lark-apps-html-publish.md`](lark-apps-html-publish.md)。
- 用户明确要云端妙搭 Agent 生成/迭代,而不是本地写代码:读 [`lark-apps-cloud-dev.md`](lark-apps-cloud-dev.md)。

View File

@@ -76,4 +76,4 @@ CLI 提供三种互斥的 scope 表达方式:
## 不在本 skill 范围
- OpenAPI spec 全量导出、实时日志 tail、Webhook 消费、多鉴权方式:本期不支持。
- 身份选择、权限不足处理(`missing_scopes`→`console_url`、exit-10 审批、通用"禁输出密钥"红线、高风险操作通用框架:见 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),不在此重复。
- 身份选择、权限不足处理(`missing_scopes`→`console_url`、exit-10 审批、通用"禁输出密钥"红线、高风险操作通用框架:见 [`../../lark-shared/SKILL.md`](../../lark-shared/SKILL.md),不在此重复。

View File

@@ -4,7 +4,7 @@
## 何时用
用于把全栈应用的代码分支推进到发布流程。它不是 HTML 静态发布入口;本地 `index.html` / `dist` 要读 [`lark-apps-html-publish.md`](lark-apps-html-publish.md)
用于把应用的代码分支推进到发布流程html 和 full_stack 统一走此入口)
## 命令骨架
@@ -29,4 +29,4 @@ lark-cli apps +release-create --app-id app_xxx --branch sprint/default --dry-run
## Agent 规则
`+release-create` 部署的是远端 `sprint/default` 上已 push 的代码,不是本地工作区——本地若有你修改但未推送的改动,需要先 `git add` + `git commit``git push``sprint/default`,否则这些改动不会进入这次发布。发布后若 status 是 `publishing`,用 [`+release-get`](lark-apps-release-get.md) 查询。`+release-create` 部署上线属高影响动作——作为别的命令的连带前置时,按 SKILL.md「高影响动作确认与预授权」先征得用户同意再发布。
`+release-create` 部署的是远端 `sprint/default` 上已 push 的代码,不是本地工作区——本地若有你修改但未推送的改动,需要先 `git add` + `git commit``git push``sprint/default`,否则这些改动不会进入这次发布。`git push` 如遇认证失败、401/403、credential helper 缺失或 token 过期,先执行 `lark-cli apps +git-credential-init --app-id <app_id> --as user` 刷新本地 Git 凭证,再重试原 git 命令;刷新凭证也失败时,停止并向用户报告错误,不要换路;不要手动复制 token 或改 remote URL。发布后若 status 是 `publishing`,用 [`+release-get`](lark-apps-release-get.md) 查询。`+release-create` 部署上线属高影响动作——作为别的命令的连带前置时,按 SKILL.md「高影响动作确认与预授权」先征得用户同意再发布。

View File

@@ -22,7 +22,7 @@ lark-cli apps +release-get --app-id app_xxx --release-id release_yyy
## 输出契约
- 成功可能直接返回 release 字段,也可能包在 `data.release`;读取 `release_id``status``created_at``updated_at`,以及 `commit_id`(本轮发布对应的 git commit SHApretty 输出在其非空时展示一行)。
- `status=publishing` 继续轮询。此时尚无 `online_url`;不要拿其它链接(如 `+list` 里的应用主页 / 开发态预览 URL冒充"本轮发布的访问链接"——只回报 `release_id``status`,并说明 `finished` 后才有 `online_url`
- `status=finished` 发布成功——**本命令输出`online_url`,直接读取它作为本轮发布的线上访问链接**返回用户,无需再调 `+list``+list` 仍可用于按应用名浏览,但不是发布主流程的必经步骤)。
- `status=failed` 发布失败——**本命令输出`error_logs``step`/`error_log`直接据此向用户转述关键失败步骤和可行动修复**
- `status=publishing` 继续轮询。此时尚无 `online_url`;不要拿其它链接(如 `+list` 里的应用主页 / 开发态预览 URL冒充"本轮发布的访问链接"——只回报 `release_id``status`,并说明 `finished` 后才可能`online_url`
- `status=finished` 发布成功——输出含 `online_url`,直接读取它作为本轮发布的线上访问链接;未返回时只报告发布完成,不要编造链接。该链接默认仅创建者可见,交付他人前先告知当前仅本人可见、按需用 `+access-scope-set` 放开可见范围。无需再调 `+list``+list` 仍可用于按应用名浏览,但不是发布主流程的必经步骤)。
- `status=failed` 发布失败——输出含 `error_logs``step`/`error_log`),据此向用户转述关键失败步骤和可行动修复;未返回时不要编造失败原因
- 只有当这个 `release_id` 已返回 `finished`,随后读到的 `online_url` 才能被表述为"本轮发布后的访问链接"。单独从 `+list` 看到 `is_published=true` 不能证明最新版本已部署。

View File

@@ -65,6 +65,9 @@ lark-cli calendar +update \
- 更新重复性日程时,必须先确定操作范围(仅此次/全部/此次及后续),然后按 [重复性日程操作规范](lark-calendar-recurring.md) 执行。
- 当同一次命令组合多个动作时,执行顺序为“日程字段 -> 移除参会人 -> 添加参会人”。若中途失败,不会自动回滚已成功步骤;错误信息会说明已完成的步骤。
**⚠️ 高风险操作**: 修改时间时必须先读取原日程时长并计算新 end。如果 end 计算错误,会导致日程时长变化,用户会直接感知,禁止擅自改变原日程的时长。
**不得擅自附加 `--skip-room-check` 重试**:将错误信息(含会议室 ID 与原因)原样透传给用户,说明本次更新会导致会议室预定失败,明确询问是否仍要继续;用户确认后再带 `--skip-room-check` 重新执行。
预检失败(如接口 404 或返回错误)会降级放行:向 stderr 打一条 warning 后继续执行,避免因新接口不稳定阻塞正常更新。
## 高级用法(完整 API 命令)

View File

@@ -98,8 +98,8 @@ Sub Agent 需要携带以下的最小上下文,以及后续的 [SVG 设计 Wor
###### 画板怎么处理 SVG
画板的 svg-parser 把可识别元素转成可编辑节点, 其余降级为内嵌图片(渲染没问题, 虽然不可编辑, 但是可以正常显示);但
`<radialGradient>` / `<filter>` / `<clipPath>` 等装饰特性画板完全不支持,会导致渲染问题(见下方⚠️)
画板的 svg-parser 把可识别元素转成可编辑节点, 其余降级为内嵌图片(渲染没问题, 虽然不可编辑, 但是可以正常显示);但非阴影用途的
`<filter>` / `<pattern>` / `<clipPath>` / `<mask>` 等装饰特性画板不支持(见下方⚠️)
**不需要所有元素都可编辑, 但必须避免使用不支持的装饰特性, 且要兼顾可编辑和美观漂亮**
**可识别的元素**
@@ -109,12 +109,14 @@ Sub Agent 需要携带以下的最小上下文,以及后续的 [SVG 设计 Wor
- 文本:`<text>` / `<tspan>` 画板硬编码 Noto Sans SC **文字必须用 `<text>`**
- 分组:`<g>` / `<a>` / `<use>` 引用 `<symbol>`
- 变换:`translate` / `rotate` / `scale` 正常;`skewX` / `skewY` / `matrix(...)` 降级
- 阴影:`<filter>` 里放 `<feDropShadow>` 或标准 drop/inner primitive 链 (`<feGaussianBlur in="SourceAlpha">` + `<feOffset>` + `<feFlood>` + `<feComposite>` + `<feMerge>`), 会被识别成节点阴影, drop 至多 1 个, inner 至多 1 个; 其余 filter 效果不识别
- 渐变:`<linearGradient>` / `<radialGradient>``<defs>` 中定义, 通过 `fill="url(#id)"` 引用 (载体限 `<rect>` / `<circle>` / `<ellipse>` / `<polygon>` / `<path>`), 需要至少 2 个 `<stop>`, `gradientUnits` 只支持默认的 `objectBoundingBox` (不写即可)
> [!IMPORTANT]
> ⚠️ ** 不支持的装饰特性**
> ⚠️ **不支持的装饰特性**
- `<radialGradient>` / `<filter>` / `<pattern>` / `<clipPath>` / `<mask>` → 画板不支持,**请避免使用,否则会导致画板渲染问题
**
- `<pattern>` / `<clipPath>` / `<mask>` / 非阴影用途的 `<filter>` (blur / hue-rotate / 复合合成 / `flood-color=url(...)` / 多个 `<feDropShadow>` 等) → 画板不支持,**请避免使用,否则会导致画板渲染问题**
- 渐变边界:`gradientUnits="userSpaceOnUse"` / `spreadMethod="reflect|repeat"` / stops 少于 2 个 / 复杂 `gradientTransform` 会变成不可编辑图片, 视觉正确但失去可编辑性, 若无必要请沿用默认 `objectBoundingBox`
###### 3.插入后审查
@@ -150,7 +152,6 @@ lark-cli whiteboard +query \
---
---
## 关联参考

View File

@@ -147,6 +147,7 @@ Lark-defined semantic tags (**not** JSON Schema's standard `format`). Common val
| Topic | Reference | Coverage |
|------------|------------------------------------------------------------------------------|---|
| Application | [`references/lark-event-application.md`](references/lark-event-application.md) | Catalog of Application EventKeys, including `application.bot.menu_v6` for custom bot menu push events + flattened `event_key` / operator fields + jq recipe |
| Approval | [`references/lark-event-approval.md`](references/lark-event-approval.md) | Catalog of 2 Approval EventKeys (`approval.instance.status_changed_v4`, `approval.task.status_changed_v4`) + optional/multi `subscription_type` pre-registration + user-auth subscription lifecycle + flat output field reference |
| IM | [`references/lark-event-im.md`](references/lark-event-im.md) | Catalog of 12 IM EventKeys + shape notes (flat vs V2 envelope) + `im.message.receive_v1` field gotchas (`sender_id` is open_id only; `.content` is plain text except for `interactive` cards) + common jq recipes (filter by chat_type / message_type / sender); for `card.action.trigger` see also [`../lark-im/references/lark-im-card-action-reply.md`](../lark-im/references/lark-im-card-action-reply.md) |
| Task | [`references/lark-event-task.md`](references/lark-event-task.md) | Catalog of 1 Task EventKey (`task.task.update_user_access_v2`) + Native V2 envelope shape + task commit types + user/bot subscription notes |

View File

@@ -0,0 +1,38 @@
# Lark Application Events
This page covers Application-domain EventKeys supported by `lark-cli event`.
## `application.bot.menu_v6`
Triggered when a user clicks a custom bot menu item whose response action is configured as a push event.
Listen as the bot identity:
```bash
lark-cli event consume application.bot.menu_v6 --as bot
```
Filter a specific menu event key:
```bash
lark-cli event consume application.bot.menu_v6 --as bot --jq 'select(.event_key == "start_eval")'
```
Output is flattened at the top level:
| Field | Meaning |
|---|---|
| `type` | Event type, always `application.bot.menu_v6` |
| `event_id` | Globally unique event ID from the event header |
| `timestamp` | Event delivery time, preferring `header.create_time` |
| `app_id` | App ID from the event header |
| `tenant_key` | Tenant key from the event header |
| `event_key` | Developer-defined menu event key, for example `start_eval` |
| `menu_timestamp` | Menu click timestamp from the event body |
| `operator_id` | Operator open_id alias |
| `operator_open_id` | Operator open_id |
| `operator_union_id` | Operator union_id |
| `operator_user_id` | Operator user_id |
| `operator_name` | Operator display name |
This EventKey has no `--param`; use `--jq` to filter by `event_key` or operator fields.

View File

@@ -1,7 +1,7 @@
---
name: lark-slides
version: 1.0.0
description: "飞书幻灯片:创建和编辑幻灯片。创建演示文稿、读取幻灯片内容、管理幻灯片页面(创建、删除、读取、局部替换)。当用户需要创建或编辑幻灯片、读取或修改单个页面时使用。当用户给出 doubao.com 的 /slides/ URL/token 时,也应直接使用本 skill不要因为域名不是飞书而回退到 WebFetch路由依据是 URL 路径模式和 token而不是域名。不负责云文档内容编辑走 lark-doc、云文档里的独立画板对象走 lark-whiteboard,注意 slide 内嵌的流程图/架构图仍属本 skill)、上传或下载普通文件(走 lark-drive。"
description: "飞书幻灯片:创建和编辑幻灯片。创建演示文稿、读取幻灯片内容、管理幻灯片页面(创建、删除、读取、局部替换)。当用户需要创建或编辑幻灯片、读取或修改单个页面时使用。当用户给出 doubao.com 的 /slides/ URL/token 时,也应直接使用本 skill不要因为域名不是飞书而回退到 WebFetch路由依据是 URL 路径模式和 token而不是域名。不负责云文档内容编辑走 lark-doc、云文档里的独立画板对象走 lark-whiteboard、上传或下载普通文件走 lark-drive。"
metadata:
requires:
bins: ["lark-cli"]
@@ -10,25 +10,82 @@ metadata:
# slides (v1)
**CRITICAL — 全局硬约束PPT 的尺寸是 960x540确保主体内容在页面边界内。**
> 本技能文档较长,务必使用 Read 工具阅读两次,必须阅读完整全文。
**CRITICAL — 图片至关重要:必须有意识的主动多用图片!素材图使用生图工具和搜图工具,缺图时用生图工具生成配图补足;背景图必须使用生图工具,且生图指令中必须明确要求不要出现任何文字。**
## 权威经验
**CRITICAL — 防文本溢出:所有承载突出信息和密集文字的 `<content>` 必须设置 `autoFit="normal-auto-fit"`,字号会在框内自动缩排以防溢出**
**权威经验是全局硬约束和高频易错点,必须牢记并严格遵守**
- 你有充足的时间完成这个 PPT质量永远比速度重要。
- PPT 的尺寸是 960x540必须严格确保主体内容在页面边界内。
- !!!禁止交付无图产物!!! 必须使用大量图片增强视觉效果!!! 禁止重复使用同一张图!!!
- 封面页的主视觉必须是 `<img>`(来自生图工具或搜图工具),不要使用 `<shape>``<icon>` 拼出封面视觉。
- 禁止用 `<shape>``<line>` 拟形具体物项,必须使用生图工具生成的 `<img>`
- 禁止在 `headline``title` 下方放置用于分隔或装饰的 `rect``<line>`
- 禁止在任何页面内部使用无意义的装饰线条或色块条带,页面任何一边都不要使用贴边窄条。
- 生图工具的指令参数必须以“不要出现任何文字和颜色色号”结尾,避免生成的图片上出现干扰文字。
- 禁止使用 emoji 图标,任何位置都不能出现。
- 字号必须显式设置 `<content>``fontSize` 属性,不要依赖 `textType` 的默认字号兜底,这些兜底值明显偏大。
- 大数字、字号大或字数多的 `<content>` 必须设置 `wrap="true" autoFit="normal-auto-fit"` 属性自动换行和缩排,避免文字溢出。
- 文字颜色必须用 `<content>``color` 属性而不是 `fontColor` 属性。
- 文字行间距必须设置 `<content>``lineSpacing="multiple:xx"``lineSpacing="fixed:xx"` 而不是 `lineSpacing="xx"`
- 图片必须用 `<img>` 而不是 `<image>`
- IconPark 图标必须填充颜色(设置 `<fill><fillColor color="rgba(R,G,B,A)"/></fill>`)并和背景有足够对比。
- 绘制图表时原生图表(柱状、条形、折线、面积、饼(环)、雷达、组合图)用 `<chart>`,其他(漏斗图、金字塔图、象限图、矩阵图等)用 `<shape>` + `<line>` 模拟。
- 隐藏 `<chart>` 的图例只能通过不写或删除 `<chartLegend>` 实现,`<chartLegend>` 不支持 `position="none"`
- 表格优先用 `rect``text` 模拟,其他用 `<table>`,没有 `<shape type="table">`
- 必须设置 `<table>``width``height` 固定表格大小,同时设置需要保留列宽或行高的 `<col>``width``<tr>``height`,其余自动分配。
- `<td>` 直接子元素只有 `<fill>`(背景)、`<content>`(文字)和边框配置(一般不用),不能嵌套 `<shape>``<img>``<icon>`
- `<shape type="rect">` 只是形状不是容器,`<icon>``<img>``<shape type="text">` 和其他 `<shape>` 必须与它平级靠坐标叠放。
- 填充渐变颜色必须用 `<fill><fillColor color="linear-gradient(135deg, rgba(R,G,B,A) 0%, rgba(R,G,B,A) 100%)"/></fill>`
- 编辑页面前必须阅读 [`lark-slides-edit-workflows.md`](references/lark-slides-edit-workflows.md)。
- 绘制图表前必须阅读 [`slides_chart_demo.xml`](references/slides_chart_demo.xml)。
- 当用户要求无损复述历史上下文时,必须无损复述以上权威经验、必读的技能文档(需要重新阅读)和易错元素语法(尤其是 `<table>``<chart>`)。
## 豆包设计原则
适用范围:
- 普通内容页的设计必须以豆包设计原则为最高准则,除非用户要求使用模板或直接提供设计方案。
- 不适用于 `title-cover``section-divider``conclusion``quote-highlight``big-number`
核心要求:
- 必须采用信息密度极高的图文卡片布局,追求充实饱满、图文丰富、可逐行细读的版面,宁可密而满,不要空而疏。
- **!!!信息密度极高!!! 图多!!! 卡多!!! 字多!!!**
排版布局:
- 卡片布局:卡片按多行网格铺满页面,版面对称、均衡、不留白。网格数、图文比例按内容变化,避免每页雷同。使用更多卡片做细分承载,避免在单张卡片里堆砌大量文字(例如 8 张 50 字卡片优于 2 张 200 字卡片),多个要点必须拆分为多张子卡片。
- 卡片样式:方角卡片 + 半透明填充 + 无边框 + 卡片贴边窄条(可选);所有卡片必须使用相同的配色方案(少量需强调的卡片除外),禁止同页出现彩虹卡片(卡片颜色超过 3 种)。
- 卡片结构:视觉锚点(关键词、编号或 IconPark 图标)+ 标题 + 内容(包括文字、图片、图表、子卡片)。
- 文字卡片:多数页面必须满足 6-8 张文字卡片、200-400 文字数量,字数不足时必须扩写成长句或段落,文字卡片不要留白,必须充实饱满。文字卡片不是短标签,而是“标题 + 完整说明”,像浓缩的分析文稿。文字内容不得不用列表、分栏、关键词或短句时,必须保证层次清晰,更建议拆分为多张子卡片。
- 图片卡片:多数页面必须满足 1-3 张图片卡片,缺少图片时必须用生图工具补充配图,图片卡片与文字卡片组成网格,确保图文丰富。
- 图表卡片:数据信息不要在文字卡片中罗列,必须在图表卡片中可视化(包括表格、图表、时间线、流程图等),图表卡片与其他卡片组成网格,展现数据驱动。
- 间距要求:所有边距都要左右对称,页面和内部内容的边距至少 40px内容不要贴边卡片和内部文字的边距至少 5px文字不要贴边卡片之间保持 20-40px 的间距。
- 文字对齐:正文默认左对齐,只在封面、结尾或大号数字场景中使用居中;表格里的文字左对齐、数字右对齐、仅关键词或短句时居中对齐。
视觉风格:
- 美学:干净、明亮、清爽但信息饱满;靠卡片和对齐网格在高密度下维持秩序感;同排卡片文字数量应相近以保持观感整齐。
- 字体:全篇以无衬线体(思源黑体)为主,封面或关键强调可少量使用衬线体。
- 字号:标题 28-36pt、正文 12-14pt、注释 10-12pt常规关键指标 16-32pt、核心指标用 36-52pt 数字,下面配 10-14pt 标签与简短解读,需要容纳更多文字时允许使用更小的字号。
- 图标:内嵌 IconPark 图标(可用关键词或编号替代)作为视觉锚点,让高密度文字也有图形节奏,而不是成片纯文字块。
- 配色:克制颜色数量,确保所有页面都只使用同样的 1 个背景色偏好浅米白、1 个主色、1 个强调色和 1 个辅助色;偏好莫兰迪配色,禁止彩虹配色(比如蓝配橙)。
## Quick Reference
| 用户需求 | 优先动作 | 关键文档 / 命令 |
|----------|----------|-----------------|
| 新建 PPT | 先规划 `slide_plan.json`,再按复杂度选择一步或两步创建 | `planning-layer.md``visual-planning.md``asset-planning.md``slides +create` |
| 从模板创建或编辑已有本地 PPTX | 导入 PPTX 为 Slides | `lark-slides-pptx-template-workflows.md` |
| 用户要求使用模板 | 将模板导入为 Slides 再编辑 | `lark-slides-pptx-template-workflows.md` |
| 编辑单个标题、文本块、图片或局部元素 | 优先块级替换/插入,不改页序 | `slides +replace-slide``lark-slides-replace-slide.md` |
| 读取或分析已有 PPT | 解析 slides/wiki token用 shortcut 回读全文 XML 或读取单页 XML保存 `xml_presentation_id``slide_id``revision_id` | `slides +xml-get``xml_presentation.slide.get` |
| 读取或分析已有 PPT | 解析 slides/wiki token用 shortcut 回读全文 XML 或读取单页 XML保存 `xml_presentation_id``slide_id``revision_id` | `slides +xml-get``xml_presentation.slide.get``lark-slides-xml-presentations-get.md` |
| 获取幻灯片页面截图 | 用 `slide_id` 或页号指定页面,一次不超过 10 页 | `slides +screenshot``lark-slides-screenshot.md` |
| 上传或使用图片 | 先上传为 `file_token`,禁止直接写 http(s) 外链 | `slides +media-upload`,或 `+create --slides``@./path` 占位符 |
| 绘制图表 | 原生图表`<chart>`,其他用 `<shape>` + `<line>`,只有复杂 Mermaid、SVG 用 `<whiteboard>` | `xml-schema-quick-ref.md``slides_chart_demo.xml` |
| 上传或使用图片 | 先上传为 `file_token`,禁止直接写 http(s) 外链 | `slides +media-upload``lark-slides-media-upload.md`,或 `+create --slides``@./path` 占位符 |
| 绘制图表 | 原生图表(柱状、条形、折线、面积、饼(环)、雷达、组合图)用 `<chart>`,其他(漏斗图、金字塔图、象限图、矩阵图等)用 `<shape>` + `<line>` 模拟 | `xml-schema-quick-ref.md``slides_chart_demo.xml` |
| 绘制表格 | 优先用 `rect``text` 模拟,其他用 `<table>` | `xml-schema-quick-ref.md` |
| 使用图标 | 禁止盲猜 `iconType`,必须先检索 IconPark再写 `<icon iconType="...">`,图标必须填充颜色并和背景有足够对比,禁止使用 emoji 图标 | `iconpark_tool.py search → resolve``iconpark.md` |
| 使用图标 | 禁止盲猜 iconType必须先检索 IconPark再写 `<icon iconType="...">`,图标必须填充颜色并和背景有足够对比,禁止使用 emoji 图标 | `iconpark_tool.py search → resolve``iconpark.md` |
| 创建失败、空白页、3350001、布局异常 | 先回读状态,再按排障清单修复,不假设原操作原子成功 | `troubleshooting.md``validation-checklist.md` |
**CRITICAL — 开始前 MUST 先用 Read 工具读取 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),认证、权限和全局参数均以 lark-shared 为准。**
@@ -39,16 +96,18 @@ metadata:
**CRITICAL — 新建演示文稿或大幅改写页面时,生成 XML 前 MUST 读取 [visual-planning.md](references/visual-planning.md),确保 `layout_type`、`visual_focus`、`text_density` 实际改变页面几何、主视觉和文本量。**
**CRITICAL — 新建演示文稿或大幅改写页面时,规划 `asset_need` MUST 遵循 [asset-planning.md](references/asset-planning.md)。**
**CRITICAL — 新建演示文稿或大幅改写页面时,规划 `asset_need` MUST 遵循 [asset-planning.md](references/asset-planning.md):只做元数据规划,必须有 `fallback_if_missing`,不得要求真实搜索、下载或上传素材**
**CRITICAL — 将完整 `<slide>` XML 提交给 `slides +create --slides`、`xml_presentation.slide create` 或 `slides +replace-pages` 之前MUST 先把待提交 XML 保存到本地文件并运行 [`scripts/xml_text_overlap_lint.py`](scripts/xml_text_overlap_lint.py)`summary.error_count` 必须为 0 才能调用接口。**
**CRITICAL — 创建或大幅改写后MUST 按 [validation-checklist.md](references/validation-checklist.md) 做显式验证:回读全文 XML、核对页数和关键元素、检查空白/破损页、明显溢出、布局风险。**
**CRITICAL — 创建或大幅改写后MUST 按 [validation-checklist.md](references/validation-checklist.md) 做显式验证:回读全文 XML、核对页数和关键元素、检查空白/破损页、明显溢出、布局风险XML 语法和文本重叠静态检查优先使用 [`scripts/xml_text_overlap_lint.py`](scripts/xml_text_overlap_lint.py)**
**CRITICAL — 创建前自检或失败排障时MUST 按 [troubleshooting.md](references/troubleshooting.md) 检查 XML 转义、结构、shell 截断、图片 token、3350001 和布局风险。**
**编辑已有幻灯片页面**:单个标题、文本块、图片或局部元素优先用 [`+replace-slide`](references/lark-slides-replace-slide.md)(块级替换/插入,不动页序);已有 Slides 的多页大改优先用 [`+replace-pages`](references/lark-slides-replace-pages.md) 在原 presentation 内批量重建页面,避免 `slides +create` 生成新链接。选择 action 和完整读-改-写流程见 [`lark-slides-edit-workflows.md`](references/lark-slides-edit-workflows.md)。
**用户要求使用模板**:按 [lark-slides-pptx-template-workflows.md](references/lark-slides-pptx-template-workflows.md) 处理。
## 身份选择
飞书幻灯片通常是用户自己的内容资源。**默认应优先显式使用 `--as user`(用户身份)执行 slides 相关操作**,始终显式指定身份。
@@ -82,16 +141,17 @@ lark-cli auth login --domain slides
按需再读:
- 创建:[`lark-slides-create.md`](references/lark-slides-create.md)
- 阅读:[`lark-slides-xml-presentations-get.md`](references/lark-slides-xml-presentations-get.md)
- 编辑:[`lark-slides-edit-workflows.md`](references/lark-slides-edit-workflows.md)、[`lark-slides-replace-slide.md`](references/lark-slides-replace-slide.md)、[`lark-slides-replace-pages.md`](references/lark-slides-replace-pages.md)
- 截图:[`lark-slides-screenshot.md`](references/lark-slides-screenshot.md)
- 图片:[`lark-slides-media-upload.md`](references/lark-slides-media-upload.md)
- 图表:[`slides_chart_demo.xml`](references/slides_chart_demo.xml)
- 图标:[`iconpark.md`](references/iconpark.md)、[`scripts/iconpark_tool.py`](scripts/iconpark_tool.py)
- 排障:[`troubleshooting.md`](references/troubleshooting.md)
- 完整协议:[`slides_xml_schema_definition.xml`](references/slides_xml_schema_definition.xml)
## Workflow
> **这是演示文稿,不是文档。** 每页 slide 是独立的视觉画面,信息密度要适当,排版要留白。
## Workflow
### Design Ideas
@@ -100,38 +160,30 @@ lark-cli auth login --domain slides
开始写 XML 前,先在 `slide_plan.json` 里确定 deck 级视觉策略:
- **主题化配色**:配色必须服务本次主题、行业和受众,不要默认蓝色商务风。如果把同一套颜色换到另一个完全不同主题仍然成立,说明配色不够具体。
- **主次比例**:选择 1 个主色承担约 60-70% 视觉权重1-2 个辅助色承担结构和分区1 个强调色只用于关键数字、结论或行动点。不要让所有颜色权重相同。
- **背景一致性**:先确定全 deck 的背景策略,默认保持同一明暗基调和底色体系;只有分节、转场或强调页才有意改变背景,并必须通过相同主色、纹理、边栏或 motif 让变化看起来属于同一套设计。无论深浅,都要保证正文、图标和线条对比充足。
- **统一 motif**:选择一个可复用视觉母题贯穿全文,例如粗侧边栏、圆形图标底、半出血图片区、编号节点、卡片左上角色块或大号数字。不要每页换一套装饰语言。
- **主次比例**:选择 1 个主色承担约 60-70% 视觉权重1 个辅助色承担结构和分区1 个强调色只用于关键数字、结论或行动点。不要让所有颜色权重相同。
- **背景一致性**:先确定全 deck 的背景策略,默认保持同一明暗基调和底色体系;无论深浅,都要保证内容和背景对比充足。
- **统一 motif**:选择一个可复用视觉母题贯穿全文,例如编号节点、卡片处理方式、半出血图片区域、标题、页脚。不要每页换一套装饰语言。
每页至少要有一个视觉元素:图片、图标、图表、表格、流程、对比结构大号数字、示意图或由 shape 组成的抽象视觉。文本框本身不算主视觉。
每页至少要有一个视觉元素:图片、图标、图表、表格、流程、对比结构大号数字。文本框本身不算主视觉。
可优先考虑这些页面形态:
常见页面形态:
- **双栏结构**:左文右图或左图右文,视觉区域占 35-45% 宽度。
- **图标行**:图标在色块或圆形底中,右侧是短标题和一句解释。
- **2x2 / 2x3 网格**:适合能力、模块、风险、行动项,每格内容保持同等层级。
- **半出血视觉**:图片或抽象形状占据左/右半屏,文字覆盖或贴边排布。
- **大数字卡片**关键指标用 60-72pt 数字,下面配 10-14pt 标签
- **网格**:适合能力、模块、风险、行动项,每格内容保持同等层级。
- **半出血视觉**:图片占据左/右半屏,文字覆盖或贴边排布。
- **大数字卡片**核心指标用大数字,下面配标签与简短解读
- **对比列**before/after、方案 A/B、问题/解法用左右并列,标题和基线严格对齐。
- **时间线/流程图**:步骤用节点和箭头表达,流程方向必须一眼可见。
字体和间距建议:
- 标题 36-44pt关键结论可更大正文 14-18pt注释 10-12pt。
- 正文默认左对齐;只在封面、结尾或大号数字场景中使用居中。
- 页面边距至少 40px内容块之间保持 24-40px 间距,并在同一 deck 内保持一致。
- 卡片内边距要真实留出空间,不要让文字贴边;对齐 shape 和文字时要考虑文本框 padding。
常见错误必须避免:
- 不要所有页面复用同一种标题 + 三 bullets 版式。
- 不要用低对比文字或低对比图标,例如浅灰字压在浅色背景上。
- 不要让装饰线穿过文字,或让页脚、来源、编号挤压主体内容。
- 不要把素材缺失表现为空白图片框;必须按 `fallback_if_missing` 生成 XML-native 视觉
- 不要留下模板占位文案、示例公司名、示例日期或与用户主题无关的原模板内容
- 不要使用 emoji。
- 不要为了画出一个具象物体而堆叠 3 个以上仅用于拟形的 shape。
- 不要把素材缺失表现为空白图片框;必须按 `fallback_if_missing` 生成替代图片
- 不要在任何位置使用 emoji 图标
### 创建方式选择
@@ -150,25 +202,26 @@ lark-cli auth login --domain slides
### 生成流程
```text
Step 1: 需求澄清 & 读取知识
- 澄清主题、受众、页数、风格;若用户上传 PPTX 作为模板,按顶部『用户自定义模板』规则处理
Step 1: 需求分析 & 读取知识
- 分析主题、受众、页数、风格;
- 若用户要求使用模板,按 lark-slides-pptx-template-workflows.md 处理
- 读取 xml-schema-quick-ref.md新建 / 大幅改写时还要读取 planning-layer.md、visual-planning.md、asset-planning.md
- 涉及图表读取 slides_chart_demo.xml
Step 2: 生成大纲 → 用户确认 → 写入 slide_plan.json
- 生成结构化大纲供用户确认
- 新建 / 大幅改写必须先创建目录并写入 `.lark-slides/plan/<deck-or-task-id>/slide_plan.json`
Step 2: 生成大纲 → 写入 slide_plan.json
- 生成结构化大纲
- 新建 / 大幅改写必须先创建目录并写入 `slide_plan.json`
- plan 字段、路径命名和 `asset_need` 结构按 planning-layer.md / asset-planning.md 执行
Step 3: 按 slide_plan.json 生成 XML → 创建
- 逐页消费 plankey_message 定主结论layout_type 定几何visual_focus 定主视觉text_density 定文本量
- 缺少真实素材时必须用 `fallback_if_missing` 生成 XML-native 兜底视觉;不要留空
- 调用创建或整页替换接口前,先保存待提交 XML 并运行 xml_text_overlap_lint.pyerror_count 不为 0 必须先修
- 缺少真实素材时必须用 `fallback_if_missing` 生成替代图片,不要留空
- 创建方式按“创建方式选择”判断;图片、复杂 XML、转义和 3350001 排查按 lark-slides-create.md、media-upload.md、troubleshooting.md 执行
Step 4: 审查 & 交付
- 创建完成后,必须用 `slides +xml-get` 读取全文 XML并按 validation-checklist.md 做显式验证记录
- 创建完成后,必须用 `slides +xml-get` 读取全文 XML并按 validation-checklist.md 做显式验证记录,包括 XML 文本重叠检查
- 失败或部分成功按 troubleshooting.md 处理;局部问题优先用 `+replace-slide` 修正
- 没问题 → 交付:告知用户演示文稿 ID 和访问方式
- 没问题 → 交付:使用 NotifyHuman 工具交付 PPT 链接
```
### jq 命令模板(编辑已有 PPT 时使用)
@@ -183,7 +236,7 @@ lark-cli slides xml_presentation.slide create \
--data "$(jq -n --arg content '<slide xmlns="http://www.larkoffice.com/sml/2.0">
<style><fill><fillColor color="BACKGROUND_COLOR"/></fill></style>
<data>
<!-- 在这里放置 shape、line、table、chart 等元素 -->
在这里放置 shape、line、table、chart 等元素
</data>
</slide>' '{slide:{content:$content}}')"
@@ -200,7 +253,7 @@ lark-cli slides xml_presentation.slide create \
### 大纲模板
生成大纲时使用以下格式,交给用户确认
生成大纲时使用以下格式:
```text
[PPT 标题] — [定位描述],面向 [目标受众]
@@ -257,7 +310,7 @@ Shortcut 是对常用操作的高级封装(`lark-cli slides +<verb> [flags]`
| Shortcut | 说明 |
|----------|------|
| [`+create`](references/lark-slides-create.md) | 创建 PPT可选 `--slides` 一步添加页面,支持 `<img src="@./local.png">` 占位符自动上传) |
| [`+xml-get`](references/lark-slides-xml-get.md) | 读取全文或单页 XML,并可保存到本地文件,避免终端输出被截断 |
| [`+xml-get`](references/lark-slides-xml-presentations-get.md) | 读取全文 XML保存到本地文件,避免终端输出被截断 |
| [`+media-upload`](references/lark-slides-media-upload.md) | 上传本地图片到指定演示文稿,返回 `file_token`(用作 `<img src="...">`),最大 20 MB |
| [`+replace-slide`](references/lark-slides-replace-slide.md) | 对已有幻灯片页面进行块级替换/插入(`block_replace` / `block_insert`),自动注入 id 和 `<content/>`,不改变页序 |
| [`+replace-pages`](references/lark-slides-replace-pages.md) | 在原演示文稿内批量重建多个页面:先创建新页到旧页前,再删除旧页;适合已有 Slides 的多页大改,不新建链接 |

View File

@@ -6,7 +6,8 @@
## Core Rules
- Every planned asset must include a fallback visual plan. The fallback can use native charts, tables, whiteboard diagrams, placeholder regions, or XML shapes, text, and arrows as appropriate.
- `asset_need` is metadata only. It can guide page design.
- Every planned asset must include a fallback visual plan. The fallback can use native charts, tables, placeholder regions, or XML shapes, text, and arrows as appropriate.
- Asset needs must serve the page's `key_message` and `visual_focus`. Do not add decorative assets that do not clarify the page.
- Prefer a few high-value asset plans over one asset on every page. For a 6-page technical or business deck, plan assets on at least 3 pages when the content allows.
- If a real local asset already exists or the user provides one, it can be used through the normal media-upload workflow. Still keep `fallback_if_missing` in the plan.
@@ -42,7 +43,7 @@ For a page without a meaningful asset need, use:
- `architecture_diagram`: system components, data flow, dependency map, or model structure.
- `icon`: small semantic symbol for a concept, step, role, or status.
- `logo`: brand, product, team, or customer mark.
- `chart`: column, bar, line, area, radar, pie, doughnut/ring, or combo data visual. Note: `<chart>` does not support funnel or scatter — map those to `<whiteboard>` SVG at generation time.
- `chart`: column, bar, line, area, radar, pie, doughnut/ring, or combo data visual. Note: `<chart>` does not support funnel or scatter.
- `infographic`: composed visual explanation, usually combining labels, numbers, and simple shapes.
- `screenshot`: product UI, terminal output, workflow state, or page capture.
- `flow_diagram`: process, sequence, decision tree, or mechanism diagram.
@@ -66,7 +67,7 @@ Match asset type to slide role:
For `asset_type: "chart"`:
- If the visual is a supported standard data chart — column, bar, line, area, radar, pie, doughnut/ring, or combo — `fallback_if_missing` must still render as a native `<chart>`.
- Do not imitate supported standard data visuals with manual drawing primitives or `<whiteboard>`.
- Do not imitate supported standard data visuals with manual drawing primitives.
- Choose the data source explicitly:
- `user_provided`: when the user provides concrete values, tables, CSV, or metric lists, use those values and do not replace them with mock data.
- `mock_placeholder`: when the user asks for a placeholder, template, example, or chart position to replace later, use mock data in a native `<chart>`.
@@ -129,7 +130,8 @@ Business comparison page:
When generating XML:
1. If an asset exists and the workflow supports it, place it in the planned visual region.
2. If no asset exists, immediately render `fallback_if_missing` with the planned XML-native element type. Supported standard data visuals still use native `<chart>`; other fallbacks may use shapes, text, lines, arrows, tables, whiteboard diagrams, or placeholder panels.
2. If no asset exists, immediately render `fallback_if_missing` with the planned generated close-enough image. Supported standard data visuals still use native `<chart>`; other fallbacks may use the image generation tool to create an approximate image.
3. Size the fallback to satisfy `visual_focus`; it should be a real page element, not a tiny decoration.
4. Keep text-density limits. Do not compensate for missing assets by adding long bullet text.
5. After creation, fetch the presentation and verify asset pages are not blank and that each planned fallback is visible when no real asset was used.
6. If the image generation tool is unavailable or fails, degrade to an XML-native fallback instead of leaving a blank: native `<chart>` for data, otherwise a simple in-card shape/text placeholder sized to fill `visual_focus`.

View File

@@ -1,91 +0,0 @@
# 完整操作示例
本文档提供与 CLI schema 一致的调用示例XML 内容均遵循 [slides_xml_schema_definition.xml](slides_xml_schema_definition.xml)。
> **重要**:新建 PPT 请使用 `slides +create --slides`,传入由 `<slide>` XML 字符串组成的 JSON 数组;每个元素必须是一页完整的 `<slide>`。复杂内容建议先创建空白 PPT再通过 `xml_presentation.slide.create` 逐页添加。完整 `<presentation>` XML 可用于本地 lint 或读取,但不能直接作为 `+create` 的提交参数。
## 目录
- [示例 1可靠创建 6 页 PPT](#示例-1可靠创建-6-页-ppt)
- [示例 7: +replace-slide + block_insert 给已有页加图](#示例-7-replace-slide--block_insert-给已有页加图)
- [示例 8: +replace-slide + block_replace 替换一个块](#示例-8-replace-slide--block_replace-替换一个块)
## 示例 1可靠创建 6 页 PPT
### 1. 写入规划文件
```bash
DECK_DIR=".lark-slides/plan/reliable-six-page-ppt"
mkdir -p "$DECK_DIR"
# 按 planning-layer.md 写入 "$DECK_DIR/slide_plan.json"
# 至少记录 6 页的顺序和标题。
```
### 2. 为每页保存独立 XML
每个文件都是完整的 `<slide>`。下面的循环会生成 6 个独立 XML 文件;实际项目中可将每页主体替换为规划内容。
```bash
titles=("主题与结论" "问题背景" "核心方法" "关键数据" "执行计划" "总结与行动")
for i in {1..6}; do
printf -v page '%02d' "$i"
cat > "$DECK_DIR/slide-$page.xml" <<XML
<slide xmlns="http://www.larkoffice.com/sml/2.0"><style><fill><fillColor color="rgb(248,250,252)"/></fill></style><data><shape type="rect" topLeftX="56" topLeftY="56" width="12" height="428"><fill><fillColor color="rgb(37,99,235)"/></fill></shape><shape type="text" topLeftX="100" topLeftY="160" width="760" height="90"><content textType="title" autoFit="normal-auto-fit"><p>${titles[$((i-1))]}</p></content></shape><shape type="text" topLeftX="100" topLeftY="290" width="700" height="70"><content textType="body" autoFit="normal-auto-fit"><p>页面主体内容。</p></content></shape></data></slide>
XML
done
```
### 3. 逐页运行 lint
提交前检查每个独立 XML。`summary.error_count` 必须为 `0`,否则先修复 XML 或布局问题。
```bash
for slide_xml in "$DECK_DIR"/slide-0{1,2,3,4,5,6}.xml; do
python3 skills/lark-slides/scripts/xml_text_overlap_lint.py \
--input "$slide_xml" | tee "${slide_xml%.xml}.lint.json"
done
test "$(jq -s 'map(.summary.error_count) | add' "$DECK_DIR"/slide-0{1,2,3,4,5,6}.lint.json)" = "0"
```
### 4. 使用 `+create` 创建 6 页 PPT
`--slides` 接收由 6 个完整 `<slide>` XML 字符串组成的 JSON 数组;使用 `jq --rawfile` 避免手动处理 XML 引号和换行。
```bash
lark-cli slides +create --as user \
--title "可靠创建 6 页 PPT" \
--slides "$(jq -n \
--rawfile s1 "$DECK_DIR/slide-01.xml" \
--rawfile s2 "$DECK_DIR/slide-02.xml" \
--rawfile s3 "$DECK_DIR/slide-03.xml" \
--rawfile s4 "$DECK_DIR/slide-04.xml" \
--rawfile s5 "$DECK_DIR/slide-05.xml" \
--rawfile s6 "$DECK_DIR/slide-06.xml" \
'[$s1, $s2, $s3, $s4, $s5, $s6]')" \
> "$DECK_DIR/create.json"
create_status=$?
if [ "$create_status" -ne 0 ]; then
exit "$create_status"
fi
if ! PRESENTATION_ID=$(jq -er '.data.xml_presentation_id | strings | select(length > 0)' "$DECK_DIR/create.json"); then
echo "missing non-empty data.xml_presentation_id in $DECK_DIR/create.json" >&2
exit 1
fi
echo "$PRESENTATION_ID" > "$DECK_DIR/xml_presentation_id"
```
如果创建中途失败,先保存已经返回的 `xml_presentation_id`,再回读确认实际已创建页数。
### 5. 用 `+xml-get` 回读全文 XML
```bash
lark-cli slides +xml-get --as user \
--presentation "$PRESENTATION_ID" \
--output "$DECK_DIR/readback.xml" \
--json | tee "$DECK_DIR/readback.json"
```

View File

@@ -25,8 +25,8 @@ python3 skills/lark-slides/scripts/iconpark_tool.py list-categories
- 默认先检索:语义图标需求必须先用 `iconpark_tool.py search --limit 8``--limit 10`,让 agent 从候选里结合版面语义二次判断;不要阅读全文索引,也不要编造不存在的 `iconType`
- 图标用于概念提示、步骤、状态、指标、角色和导航;不要用无关装饰图标填充版面。
- 常用尺寸:行内状态图标 16-24px卡片标题图标 28-40px主视觉图标 56-96px。
- 视觉规范要求图标设置非透明 `fillColor`,显式指定颜色并和背景有足够对比;深色背景优先放在浅色圆形/方形底上,或使用 `rgba(255, 255, 255, 1)` 作为图标填充色。
- 查不到合适图标时,用 shape、line、text 画 XML-native fallback,不留空图标位。
- 图标必须填充颜色并和背景有足够对比;深色背景优先放在浅色圆形/方形底上,或使用 `rgba(255, 255, 255, 1)` 作为图标填充色。
- 查不到合适图标时,从高频示例里选择替代图标(随机选择,不要千篇一律),不留空图标位。
## 高频示例

View File

@@ -1,8 +1,6 @@
# slides +create创建飞书幻灯片
> **前置条件:** 先阅读 [`../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 了解认证、全局参数和安全规则。
创建一个新的飞书幻灯片演示文稿,可选一步添加页面内容。
- 禁止:从完整 <presentation> XML 解析/拆分/重序列化生成提交 payload。
@@ -153,4 +151,5 @@ lark-cli slides xml_presentation.slide create --as user \
## 相关命令
- [slides +xml-get](lark-slides-xml-get.md) — 读取 PPT 内容并保存到本地文件
- [xml_presentation.slide create](lark-slides-xml-presentation-slide-create.md) — 添加幻灯片页面
- [slides +xml-get](lark-slides-xml-presentations-get.md) — 读取 PPT 内容并保存到本地文件

View File

@@ -1,8 +1,6 @@
# slides +media-upload上传本地图片到飞书幻灯片
> **前置条件:** 先阅读 [`../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 了解认证、全局参数和安全规则。
把本地图片上传到指定演示文稿的 drive 媒体库,返回 `file_token`。**返回的 token 作为 `<img src="...">` 的值塞进 slide XML 即可显示图片。**
## 命令
@@ -125,3 +123,4 @@ lark-cli slides +replace-slide --as user \
- [+create](lark-slides-create.md) — 新建 PPT支持 `@` 占位符自动上传图片)
- [+replace-slide](lark-slides-replace-slide.md) — 给已有页加图 / 换图(`block_insert` / `block_replace`
- [xml_presentation.slide create](lark-slides-xml-presentation-slide-create.md) — 创建 slide 页面(拿到 file_token 后塞进 XML

View File

@@ -1,12 +1,12 @@
# PPT Template Rewrite Principles
本页只约束“用户指定 PPT 模板、底稿、已有 PPTX/PDF/Slides并要求基于它二次创作”的场景。核心原则:模板不是风格参考,而是必须沿用的编辑底稿。
核心原则:模板不是风格参考,而是必须沿用的编辑底稿。
## Import First
用户指定 PPT 模板时,先把模板导入成 Lark Slides。后续写入目标是导入后的 Slides不是新建一个脱离模板的 deck也不是先在本地重画 PPTX 再导入。
如果用户提供的模板是 PPTX 格式,先把模板导入成 Lark Slides。后续写入目标是导入后的 Slides不是新建一个脱离模板的 deck也不是先在本地重画 PPTX 再导入。
直接使用以下命令,不需要先加载 `lark-drive` skill
直接使用以下命令,不需要先加载 `lark-drive` Skill
```bash
lark-cli drive +import --as user --file "<template.pptx>" --type slides --json
@@ -18,13 +18,9 @@ lark-cli drive +import --as user --file "<template.pptx>" --type slides --json
lark-cli drive +task_result --scenario import --ticket <TICKET>
```
导入后必须回读 Slides 内容理解每页的真实版式、字体、层级、图片、图表、shape、表格和文本容器。回读结果是模板二创的事实来源。
## Read Before Editing
编辑任何 PPT 页面前,必须先阅读该页面
如果当前上下文中没有该页内容,必须重新读取页面;这里的“当前上下文”不包含 System Prompt。不能只凭记忆、文件名、缩略图印象或模板整体风格判断来编辑具体页面。
导入后必须阅读 Slides 内容理解每页的真实版式、字体、层级、图片、图表、shape、表格和文本容器。阅读结果是后续编辑的事实来源
阅读页面时至少判断:
@@ -47,7 +43,7 @@ lark-cli drive +task_result --scenario import --ticket <TICKET>
## Preserve Design
模板二创必须严格沿用原版式和字体,只改内容,不做设计。
编辑必须严格沿用原版式和字体,只改内容,不做设计。
默认保留:
@@ -56,7 +52,7 @@ lark-cli drive +task_result --scenario import --ticket <TICKET>
- 背景图、图片、logo、图表、表格、装饰形状、线条、图标和页面结构。
- 模板中不同页型之间的差异。
不要把模板页改造成统一的通用卡片、白板、标题栏、三栏、2x2 卡片或大面积遮罩。不要把模板当作背景图后另起一套设计系统。
不要把模板页改造成统一的通用卡片、白板式布局、标题栏、三栏、2x2 卡片或大面积遮罩。不要把模板当作背景图后另起一套设计系统。
## Content Only
@@ -86,4 +82,4 @@ lark-cli drive +task_result --scenario import --ticket <TICKET>
发现文字溢出时,优先凝练文字或缩减字号。发现遮挡时,调整 shape 顺序、局部位置或复用原有空白区域解决。只有在这些方法都不能满足内容表达时,才做局部新增或删除。
模板二创的完成标准不是“生成了一套看起来统一的新 PPT”是“原模板的版式、字体和视觉结构仍清晰存在,内容已经被准确替换,并且回读后没有溢出和遮挡”。
完成标准是“原模板的版式、字体和视觉结构仍清晰存在,内容已经被准确替换,并且回读后没有溢出和遮挡”。

View File

@@ -1,7 +1,5 @@
# slides +replace-slide块级替换 / 插入)
> **前置条件:** 先阅读 [`../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 了解认证、全局参数和安全规则。
对指定 slide 做块级替换或插入。编辑已有 PPT 的主路径——`slide_id` 不变、页序不动、只影响被指定的块。
相比直接调 `xml_presentation.slide.replace`,这个 shortcut 的四个额外价值:
@@ -88,7 +86,6 @@ lark-cli slides +replace-slide --as user \
| `<table>` | 表格 | 整表替换会**重建内部 td id**,旧 td block_id 立即失效 |
| `<td>` | 单元格局部替换 | 只能 `block_replace`,不能 `block_insert``block_id` 必须是最新 `slide.get` 拿到的 td id |
| `<chart>` | 图表line/bar/column/pie/area/radar/combo | 必须嵌 `<chartPlotArea>` + `<chartData>` + `<dim1>/<dim2>/<chartField>` |
| `<whiteboard>` | 画板SVG 或 Mermaid | 内嵌 `<svg>``<mermaid>``slide.get` 返回结构不含内部数据,但可直接写完整新 XML 做 `block_replace` 覆盖;详见 [`lark-slides-whiteboard.md`](lark-slides-whiteboard.md) |
**不可作为根元素**

View File

@@ -4,7 +4,7 @@
获取幻灯片页面截图并保存为本地图片文件。默认用于已存在 PPT 页面截图;传入 `--content` 时用于直接渲染单个 `<slide>` XML 片段预览。本 shortcut 会在 CLI 进程内解码并写入文件stdout 只返回文件路径、大小、页面 ID 等元信息,避免把图片 Base64 输出给模型。
注意:该截图能力受应用白名单限制,绝大多数应用不可用。截图失败,记录错误即可;不要引导用户申请 `slides:presentation:screenshot` 权限。后续按 `validation-checklist.md` 走非截图验证,不要声称已完成截图验收
注意:该截图能力受应用白名单限制,绝大多数应用不可用。截图失败不要引导用户申请 `slides:presentation:screenshot` 权限;记录错误后降级到 XML 读回、结构 lint、文本重叠检查等非截图检查路径
## 命令

View File

@@ -1,331 +0,0 @@
# Whiteboard 画板元素
`<whiteboard>` 放在 `<data>` 内,内部可放 **SVG****Mermaid**,用于绘制流程图、时序图、架构图、散点图、漏斗图、自定义图标、装饰图案等 `<chart>``<shape>` 难以覆盖的视觉内容。
普通柱状图、条形图、折线图、面积图、雷达图、饼图 / 环图和组合图应优先使用原生 `<chart>`。除非用户明确要求像素级自定义,或图表类型确实不受 `<chart>` 支持,否则不要用 `<whiteboard>` + SVG / Mermaid 重画这些标准图表。
> 前置条件:使用本文档前先阅读 [lark-slides SKILL.md](../SKILL.md)。
---
## `<chart>` 还是 `<whiteboard>`
**先判断内容类型,再进入本文档:**
| 场景 | 推荐元素 |
|------|---------|
| 有结构化数据序列的柱/条/折线/面积/雷达/饼/环/组合图 | `<chart>` — 原生渲染,支持 legend / tooltip / 系列配色 |
| 散点图、漏斗图(`<chart>` 不支持)或其他非原生数据视觉 | `<whiteboard>` SVG |
| 流程图、时序图、架构图、类图、ER 图等拓扑图 | `<whiteboard>` Mermaid 或 SVG |
| 自定义图标、徽标、示意性图形(需要 path/polygon 精确控制) | `<whiteboard>` SVG |
| 进度条、波浪背景、装饰图案、像素级自定义可视化 | `<whiteboard>` SVG |
> 适合 `<chart>` 的内容就用 `<chart>`,不要用 SVG / Mermaid 手绘——原生渲染更省力、结构更稳定,也更容易被回读和后续编辑。
---
## whiteboard 公共属性
| 属性 | 必需 | 说明 |
|------|------|------|
| `topLeftX` | 是 | 左上角 X 坐标slide 坐标系slide 默认宽 960 |
| `topLeftY` | 是 | 左上角 Y 坐标slide 坐标系slide 默认高 540 |
| `width` | 是 | 画板宽度(像素) |
| `height` | 是 | 画板高度(像素) |
> SVG 模式下 `<svg>` 需声明 `xmlns="http://www.w3.org/2000/svg"`;内容大小由子元素包围盒决定,`width`/`height`/`viewBox` 不影响渲染(仅当元素属性使用百分比值时需要 `viewBox` 提供计算基准。Mermaid 模式不需要额外属性。
SVG 内的坐标相对于 whiteboard 自身左上角0,0与 slide 坐标系无关。
---
## SVG 还是 Mermaid
选择分三步:**先排除原生 `<chart>`,再判断 whiteboard 类型,最后看当前模型身份**。
### 第一步:先确认是否应该使用 `<chart>`
如果内容是柱状图、条形图、折线图、面积图、雷达图、饼图 / 环图或组合图,返回使用原生 `<chart>`,不要继续套用本文档的 SVG / Mermaid 路径。
### 第二步whiteboard 类型优先判断
以下类型**推荐 Mermaid**,自动布局、代码简洁;如需精确匹配品牌配色或自定义节点样式,可改用 SVG
| 图表类型 | Mermaid 关键字 |
|----------|--------------|
| 流程图、决策树、架构图 | `flowchart TD` / `flowchart LR` |
| 时序图 | `sequenceDiagram` |
| 类图 | `classDiagram` |
| 甘特图 | `gantt` |
| 状态图 | `stateDiagram-v2` |
| 思维导图 | `mindmap` |
| ER 图 | `erDiagram` |
### 第三步:非原生图表与装饰元素按模型身份选路径
上表以外的场景散点图、漏斗图、进度条、时间线、波浪背景、星点纹理等需要精确控制坐标和配色SVG 表达力更强,但各模型生成 SVG 的能力有差异:
| 模型身份 | 路径 |
|----------|------|
| Claude / Gemini / GPT / GLM | **SVG** — 精确控制坐标、颜色、透明度 |
| Doubao / Seed / Other | **Mermaid** — 用 `gantt``flowchart` 等近似表达;确实无法用 Mermaid 表达时才回退到简单 SVG 矩形/线条 |
> **先自报身份再选路径**:在决定使用 SVG 之前,确认当前模型属于哪一类。不要跳过这一步。
---
## 模式一SVG
### ⚠️ 设计品质要求
在 slide 里嵌入 `<whiteboard>` 的目的是**表达原生 `<chart>` 或基础 `<shape>` 难以覆盖的视觉关系**,不是把标准数据图表手绘一遍。
- **不要只用矩形加文字应付**:通篇纯白底色 + 方块 + 黑字等于白做,这是不及格输出
- **非原生数据视觉必须有坐标系**:散点、漏斗等仍要有必要的坐标轴、刻度、数值标注或分段说明,不要只画点或色块
- **字号必须有层级**:标题 ≠ 标签 ≠ 数值,混用同一字号会消灭视觉焦点
- **配色要与 slide 主题呼应**:深色 slide 背景下图表用透明底或深色卡片;浅色背景下避免再加纯白底块
- **每个 whiteboard 都是设计机会**:主动用圆角、半透明填充、清晰分组、节点状态等细节拉开与默认模板的差距
- **写 SVG 前先判断背景亮度**:背景亮度 < 30% 时,装饰元素"对比不足"比"过强"危害更大,宁重勿轻;
- **装饰层次用亮度跳跃,不用线性叠透明度**`α=0.04→0.08→0.12` 的等差递增在深色底上几乎看不出差异(相邻层亮度差 ≈20正确做法是非线性跳跃如 `0.10→0.40→0.70→1.0`,相邻层亮度差 ≥60。
### 语法
```xml
<whiteboard width="400" height="300" topLeftX="500" topLeftY="120">
<svg xmlns="http://www.w3.org/2000/svg">
<rect x="50" y="50" width="80" height="200" rx="4" fill="rgba(59,130,246,0.85)"/>
<text x="90" y="270" text-anchor="middle" font-size="12" fill="rgba(100,116,139,1)">ABC</text>
</svg>
</whiteboard>
```
`<svg>` 需声明 `xmlns="http://www.w3.org/2000/svg"``width`/`height`/`viewBox` 无需填写,若元素属性使用百分比值则需额外声明 `viewBox`
### ⚠️ 渲染包围盒规则
whiteboard 渲染时以**所有子元素的几何包围盒合并结果**为内容区域,自适应缩放到容器。
`<svg>` 上的 `width``height``viewBox` 不影响内容区域的计算,但 `viewBox` 有一个实际用途:**为百分比属性提供计算基准**。若元素使用 `width="50%"` 等百分比值,必须声明 `viewBox` 才能正确解析;绝对坐标元素则无需关心。推荐统一使用绝对坐标,避免引入百分比依赖。
### 支持的 SVG 元素
| 元素 | 说明 | 典型用途 |
|------|------|---------|
| `<rect>` | 矩形,支持 `rx` 圆角 | 卡片、进度条、分段色块 |
| `<circle>` | 圆 | 节点、装饰点、环形图 |
| `<ellipse>` | 椭圆 | 自定义轮廓图形 |
| `<line>` | 直线 | 轴线、分隔线、连接线 |
| `<path>` | 任意路径(支持 Q/C 曲线) | 波浪、曲线、弧形 |
| `<text>` | 文本,支持中文 | 标签、数值 |
| `<polygon>` | 多边形 | 箭头、星形、面积填充 |
| `<g>` | 分组 | 批量变换、语义分组 |
| `<linearGradient>` | 线性渐变定义,配合 `fill="url(#id)"` 使用 | 渐变背景、渐变填充 |
**颜色:** 统一用 `rgba(R,G,B,A)`,对深浅背景都友好。
**虚线:** `stroke-dasharray="4,4"` 用于网格线 / 坐标轴。
**变换:** `transform="translate(x,y)"` / `rotate(deg cx cy)` / `scale(n)` 均支持。
---
### 元素计算
SVG 中只要涉及批量定位、等间距排布或数据映射,**建议额外运行一个 Python 脚本把坐标算出来再填入 SVG**,而不是手动估值。适用范围包括散点、漏斗、装饰性点阵、等间距圆、重复图案等;普通柱状图、折线图、饼图仍应回到原生 `<chart>`
> **主动去算**:写 SVG 之前先运行脚本,把输出当注释贴在 `<svg>` 开头,再照着填坐标。估值几乎每次都需要反复调整,跳过这步反而更慢。
**散点图 / 装饰性点阵范式**
```python
W, H = 360, 260
origin_x, origin_y = 50, 216 # 左下角SVG Y 轴向下
cw, ch = 290, 184
points = [(12, 40), (28, 80), (45, 65)]
x_min, x_max, y_min, y_max = 0, 50, 0, 100
for i, (xv, yv) in enumerate(points):
x = round(origin_x + (xv - x_min) / (x_max - x_min) * cw)
y = round(origin_y - (yv - y_min) / (y_max - y_min) * ch)
print(f"point-{i}: cx={x} cy={y}")
```
**装饰性元素(等间距范式)**
```python
n, total_w, cy, r = 8, 340, 40, 4
step = total_w / (n - 1)
for i in range(n):
print(f"circle-{i}: cx={round(i * step)} cy={cy} r={r}")
```
**最大包围盒 → whiteboard 尺寸**
所有元素坐标算完后,汇总出整体包围盒,直接作为 whiteboard 的 `width`/`height`
```python
# 每个元素登记 (x, y, w, h),含 stroke 外扩
elements = [
(10, 20, 80, 160), # item-0
(107, 10, 80, 170), # item-1
(204, 40, 80, 140), # item-2
(0, 0, 300, 1), # x-axis
]
xs = [x for x, y, w, h in elements]
ys = [y for x, y, w, h in elements]
x2 = [x + w for x, y, w, h in elements]
y2 = [y + h for x, y, w, h in elements]
wb_w = max(x2) - min(xs)
wb_h = max(y2) - min(ys)
print(f"whiteboard width={wb_w} height={wb_h}")
```
输出即 `<whiteboard width=... height=...>` 的值,无需手动估算。
---
### 布局模式
**全屏装饰层**
```xml
<whiteboard width="960" height="540" topLeftX="0" topLeftY="0">
<svg xmlns="http://www.w3.org/2000/svg">
...
</svg>
</whiteboard>
```
> ⚠️ 全屏装饰 whiteboard 必须放在所有 `<shape>` / `<img>` / `<table>` 之前否则会遮挡文字内容。XML 中元素位置越靠后,渲染层级越高。
**侧栏图表(与文字 shape 并排)**
```xml
<!-- 左侧文字 -->
<shape type="text" topLeftX="60" topLeftY="120" width="500" height="340">...</shape>
<!-- 右侧图表 -->
<whiteboard width="340" height="340" topLeftX="580" topLeftY="120">
<svg xmlns="http://www.w3.org/2000/svg">
...
</svg>
</whiteboard>
```
**底部装饰条**
```xml
<whiteboard width="960" height="100" topLeftX="0" topLeftY="440">
<svg xmlns="http://www.w3.org/2000/svg">
...
</svg>
</whiteboard>
```
---
### 禁止使用的 SVG 特性
以下特性在 slide `<whiteboard>` 渲染端不支持或行为不可预测,必须避免:
| 禁止 | 原因 | 替代方案 |
|------|------|---------|
| `<radialGradient>` | 渲染失败 | 用 `<linearGradient>``rgba()` 透明度模拟深浅层次 |
| `<filter>`(阴影、模糊等) | 渲染失败 | 用半透明 `<rect>` 叠加模拟阴影 |
| `<clipPath>` / `<mask>` | 渲染失败 | 调整元素坐标和尺寸自然裁切 |
| `<pattern>` | 渲染失败 | 手动铺 `<circle>` / `<rect>` 点阵 |
| `skewX` / `skewY` / `matrix(...)` | 空间扭曲,降级渲染 | 用 `rotate` + `translate` 替代 |
| `<image>` 外链 URL | 不支持外链 | 先上传得到 file_token再用 `<img>` 元素 |
---
## 模式二Mermaid
### 语法
```xml
<whiteboard topLeftX="72" topLeftY="60" width="816" height="360">
<mermaid>
<![CDATA[
flowchart TD
A[检查 lark-cli 与 jq] --> B[编写每页 slide XML]
B --> C[通过 jq 生成 slides JSON]
C --> D[执行 slides +create]
D --> E[读取 xml_presentation_id]
E --> F[回读并验证创建结果]
]]>
</mermaid>
</whiteboard>
```
**关键点:**
- 内容用 `<![CDATA[...]]>` 包裹——Mermaid 语法里的 `[``>``-->` 是 XML 特殊字符CDATA 避免转义问题
- whiteboard 只需 `topLeftX``topLeftY``width``height`
### 支持的 Mermaid 图表类型
| 类型 | 关键字 | 适用场景 |
|------|--------|---------|
| 流程图 | `flowchart TD` / `flowchart LR` | 业务流程、决策树、工作流 |
| 时序图 | `sequenceDiagram` | 系统交互、API 调用链 |
| 甘特图 | `gantt` | 项目计划、里程碑 |
| 类图 | `classDiagram` | 对象关系、架构设计 |
| ER 图 | `erDiagram` | 数据库结构 |
| 状态图 | `stateDiagram-v2` | 状态机、生命周期 |
| 思维导图 | `mindmap` | 主题梳理、知识架构 |
| 用户旅程 | `journey` | 用户体验路径 |
### Mermaid 布局建议
Mermaid 图表会自动撑满 whiteboard 区域。建议:
- 流程图留足高度,节点较多时适当增加 height比如 400-480
- 避免一页放超过 15 个节点,内容太密时考虑分页
- 推荐尺寸参考:
| 图表类型 | 建议 width | 建议 height |
|---------|-----------|------------|
| 流程图5-8 节点) | 720-816 | 300-400 |
| 时序图3-5 参与者) | 720-816 | 320-420 |
| 甘特图 | 816 | 280-360 |
| 思维导图 | 816 | 380-480 |
---
## 注意事项 & 已知问题
### z-orderSVG 模式)
whiteboard 在 XML 中的位置决定渲染层级:在 shape 前 → 在下层;在 shape 后 → 在上层。全屏装饰 whiteboard 应放在所有 shape 之前。
### Mermaid CDATA 必要性
Mermaid 语法包含 `[``>``-->`,不用 CDATA 直接写会破坏 XML 解析。始终使用 `<![CDATA[ ... ]]>`
---
## 快速自检清单
**SVG 模式——结构检查:**
- [ ] `<svg>` 声明了 `xmlns="http://www.w3.org/2000/svg"`
- [ ] whiteboard 的 `width`/`height` 由所有元素的最大包围盒(含 stroke 外扩)计算得出,不手动估值
- [ ] `topLeftX + width ≤ 960``topLeftY + height ≤ 540`
- [ ]`<radialGradient>` / `<filter>` / `<clipPath>`
- [ ] 文字 `y` 坐标为 baseline 位置,最小值 ≥ font-size避免被裁切
**SVG 模式——视觉品质检查:**
- [ ] 非原生数据视觉有必要的坐标轴、网格线、数值标注或分段说明,没有"裸点"或无解释色块
- [ ] 字号有层级:标题 > 数值 > 轴标签,非全部相同
- [ ] 单一数据系列用同一颜色,多系列用不同颜色且对比充足
- [ ] 轴标签与图表元素互不遮挡,留有足够空间
- [ ] 坐标推导有注释(写明 originX/Y、chartW/H、数据映射公式
**Mermaid 模式:**
- [ ] 内容包在 `<![CDATA[...]]>`
- [ ] CDATA 结束符 `]]>` 不出现在 Mermaid 代码本身中
- [ ] `topLeftX + width ≤ 960``topLeftY + height ≤ 540`
- [ ] 节点数量合理(单图不超过 15-20 个节点)
**通用:**
- [ ] XML 标签全部闭合,属性引号完整
- [ ] 如果失败,检查是否是偶发 5001000重试一次
---
## 参考
- [lark-slides SKILL.md](../SKILL.md)

View File

@@ -1,100 +0,0 @@
# slides +xml-get读取 XML
读取已有演示文稿的完整 XML或按 `slide_id` / 页码读取单页 XML。适合创建后验收、编辑前备份、获取 `slide_id` / `revision_id`,以及排查空白页、破图、文本溢出等问题。相比直接调用底层 `xml_presentations.get` / `xml_presentation.slide.get`,本 shortcut 会自动解析 Slides URL / Wiki URL并可把 XML 保存到本地文件,避免终端输出被截断。
## 命令
```bash
lark-cli slides +xml-get \
--as user \
--presentation <slides_url_or_xml_presentation_id> \
--output .lark-slides/plan/<deck-id>/readback.xml
```
## 参数
| 参数 | 必需 | 说明 |
|------|------|------|
| `--presentation` | 是 | `xml_presentation_id``/slides/` URL 或 `/wiki/` URL |
| `--output` | 否 | 本地 XML 保存路径,必须是当前工作目录内的相对路径,不能传绝对路径。传入时 XML 内容保存到文件stdout 只返回保存后的绝对路径、大小等简短元信息;省略时默认返回 JSON envelope |
| `--slide-id` | 否 | 页面 short ID传入后只读取该页 XML。不能和 `--slide-number` 同时使用 |
| `--slide-number` | 否 | 1-based 页码;传入后只读取该页 XML。不能和 `--slide-id` 同时使用 |
| `--revision-id` | 否 | 读取指定版本;默认 `-1`,表示最新版本 |
| `--remove-attr-id` | 否 | 仅全文读取可用。移除返回 XML 中的 `id` 属性;适合只读检查,不适合精确块级编辑 |
| `--raw` | 否 | 省略 `--output` 时直接把 XML 原文写到 stdout不包 JSON envelope。不能和 `--output` / `--jq` / 非 json `--format` 同时使用 |
| `--dry-run` | 否 | 预览将调用的 API 和输出方式,不读取真实 XML |
## 输出到文件
推荐普通工作流都传 `--output`,尤其是中大型 PPT。`--output` 必须是当前工作目录内的相对路径,例如 `.lark-slides/plan/$PID/readback.xml`,不要传 `/tmp/readback.xml` 这类绝对路径。XML 会写入本地文件stdout 只保留元信息,便于后续脚本读取。
```bash
lark-cli slides +xml-get --as user \
--presentation "$PID" \
--output .lark-slides/plan/$PID/readback.xml
```
成功输出中的 `data` 类似:
```json
{
"xml_presentation_id": "slides_example_presentation_id",
"path": "/abs/path/.lark-slides/plan/slides_example_presentation_id/readback.xml",
"size": 123456,
"content_saved": true,
"revision_id": 12
}
```
其中 `path` 是 CLI 解析后的绝对路径。
如果传入 `--remove-attr-id`,返回元信息中会包含 `"remove_attr_id": true`
## 读取单页
已知页面 short ID 时,用 `--slide-id`
```bash
lark-cli slides +xml-get --as user \
--presentation "$PID" \
--slide-id "$SID" \
--output .lark-slides/plan/$PID/slide-$SID.xml
```
已知页码时,用 `--slide-number`(页码从 1 开始):
```bash
lark-cli slides +xml-get --as user \
--presentation "$PID" \
--slide-number 2 \
--output .lark-slides/plan/$PID/slide-2.xml
```
单页模式底层调用 `xml_presentation.slide.get`,返回或保存的是单个 `<slide>` XML 片段。`--slide-id``--slide-number` 不能同时传;`--remove-attr-id` 只支持全文读取。
## 输出到终端
省略 `--output`CLI 默认输出 JSON envelopeXML 位于 `data.xml_presentation.content`(全文)或 `data.slide.content`(单页)。这个模式适合配合 `--jq` 临时提取:
```bash
lark-cli slides +xml-get --as user \
--presentation "$PID" \
--jq '.data.xml_presentation.content'
```
需要把 XML 原文直接写到 stdout 时,加 `--raw`
```bash
lark-cli slides +xml-get --as user \
--presentation "$PID" \
--slide-number 2 \
--raw
```
## 相关命令
- [slides +screenshot](lark-slides-screenshot.md) - 获取页面截图做视觉验证
- [slides +replace-slide](lark-slides-replace-slide.md) - 局部替换或插入页面元素
- [slides +replace-pages](lark-slides-replace-pages.md) - 多页整页重建
- [xml_presentations get](lark-slides-xml-presentations-get.md) - 底层原生 API 参考

View File

@@ -0,0 +1,219 @@
# lark-slides xml_presentation.slide create
## 用途
在指定的 XML 演示文稿中创建新的幻灯片页面,通常用于给 `slides +create` 创建出的空白 PPT 逐页补充内容。
## 命令
```bash
lark-cli slides xml_presentation.slide create --as user --params '<json_params>' --data '<json_data>'
```
## 参数说明
| 参数 | 类型 | 必需 | 说明 |
|------|------|------|------|
| `--params` | JSON string | 是 | 路径参数与查询参数 |
| `--data` | JSON string | 是 | 请求体,包含新页面内容 |
### params JSON 结构
```json
{
"xml_presentation_id": "slides_example_presentation_id",
"revision_id": -1,
"tid": "idMock"
}
```
| 字段 | 类型 | 必需 | 说明 |
|------|------|------|------|
| `xml_presentation_id` | string | 是 | 目标演示文稿的唯一标识符 |
| `revision_id` | integer | 否 | 演示文稿版本号,`-1` 表示最新版本 |
| `tid` | string | 否 | 锁的事务 ID |
### data JSON 结构
```json
{
"slide": {
"slide_id": "slide_example_id",
"content": "<slide xmlns=\"http://www.larkoffice.com/sml/2.0\">...</slide>"
},
"before_slide_id": "slide_before_target"
}
```
| 字段 | 类型 | 必需 | 说明 |
|------|------|------|------|
| `slide.slide_id` | string | 否 | 幻灯片页面 short ID |
| `slide.content` | string | 否 | 新幻灯片的 XML 内容 |
| `before_slide_id` | string | 否 | 插入到指定页面之前 |
## slide XML 结构
`slide.content` 是一个完整的 `<slide>` 元素,遵循 SML 2.0 Schema
```xml
<slide xmlns="http://www.larkoffice.com/sml/2.0">
<data>
<shape type="text" topLeftX="80" topLeftY="80" width="800" height="120">
<content textType="title">
<p>标题</p>
</content>
</shape>
</data>
</slide>
```
详细格式请参考 [xml-schema-quick-ref.md](xml-schema-quick-ref.md)。
## 使用示例
### 在末尾添加幻灯片
```bash
lark-cli slides xml_presentation.slide create --as user --params '{
"xml_presentation_id": "slides_example_presentation_id"
}' --data '{
"slide": {
"content": "<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data><shape type=\"text\" topLeftX=\"80\" topLeftY=\"80\" width=\"800\" height=\"120\"><content textType=\"title\"><p>新页面标题</p></content></shape><shape type=\"text\" topLeftX=\"80\" topLeftY=\"200\" width=\"800\" height=\"180\"><content textType=\"body\"><p>内容文本</p></content></shape></data></slide>"
}
}'
```
### 在指定页面前插入幻灯片
```bash
lark-cli slides xml_presentation.slide create --as user --params '{
"xml_presentation_id": "slides_example_presentation_id"
}' --data '{
"slide": {
"content": "<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data><shape type=\"text\" topLeftX=\"80\" topLeftY=\"80\" width=\"800\" height=\"120\"><content textType=\"title\"><p>插入的标题页</p></content></shape></data></slide>"
},
"before_slide_id": "slide_before_target"
}'
```
### 带图形元素的幻灯片
```bash
lark-cli slides xml_presentation.slide create --as user --params '{
"xml_presentation_id": "slides_example_presentation_id"
}' --data '{
"slide": {
"content": "<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data><shape type=\"text\" topLeftX=\"80\" topLeftY=\"80\" width=\"520\" height=\"120\"><content textType=\"title\"><p>数据展示</p></content></shape><shape type=\"rect\" topLeftX=\"700\" topLeftY=\"100\" width=\"200\" height=\"150\"><fill><fillColor color=\"rgb(100, 149, 237)\"/></fill></shape></data></slide>"
}
}'
```
### 从文件读取 XML
```bash
# 先创建 slide.xml 文件
cat > slide.xml << 'EOF'
<slide xmlns="http://www.larkoffice.com/sml/2.0">
<data>
<shape type="text" topLeftX="80" topLeftY="80" width="800" height="120">
<content textType="title">
<p>从文件加载</p>
</content>
</shape>
<shape type="text" topLeftX="80" topLeftY="200" width="800" height="180">
<content textType="body">
<p>这是从文件读取的幻灯片内容</p>
</content>
</shape>
</data>
</slide>
EOF
# 然后创建幻灯片
lark-cli slides xml_presentation.slide create --as user \
--params '{"xml_presentation_id":"slides_example_presentation_id"}' \
--data "$(jq -n --arg content "$(cat slide.xml)" '{slide:{content:$content}}')"
```
## 返回值
成功时返回创建的幻灯片信息:
```json
{
"code": 0,
"data": {
"slide_id": "slide_example_id",
"revision_id": 100
},
"msg": "success"
}
```
### 返回字段说明
| 字段 | 类型 | 说明 |
|------|------|------|
| `data.slide_id` | string | 新幻灯片的唯一标识 |
| `data.revision_id` | integer | 演示文稿最新版本号 |
## slide 元素可用子元素
| 元素 | 说明 |
|------|------|
| `<style>` | 页面样式(背景填充) |
| `<data>` | 图形元素容器shape、img、table、chart 等) |
| `<note>` | 演讲者备注 |
> [!IMPORTANT]
> **本地图片必须先上传**`xml_presentation.slide.create` 不识别 `@./local.png` 占位符(那是 `+create --slides` 的语法糖)。直接调本接口添加带图新页时,必须先用 [`slides +media-upload`](lark-slides-media-upload.md) 拿到 `file_token`,再写进 `<img src="<file_token>">`。
>
> 如果是从零开始建带图 PPT**强烈建议改用 [`slides +create --slides '[...]'`](lark-slides-create.md#本地图片path-占位符)** 一步搞定(自动上传 + 替换 token
## 常见错误
| 错误码 | 含义 | 解决方案 |
|--------|------|----------|
| 404 | 演示文稿不存在 | 检查 `xml_presentation_id` 是否正确 |
| 400 | XML 格式错误 | 检查 `slide.content` 是否是完整 `<slide>` 元素 |
| 400 | 请求体结构错误 | 检查是否按 `slide.content``before_slide_id` 包装 |
| 403 | 权限不足 | 检查是否拥有 `slides:presentation:update``slides:presentation:write_only` scope |
| 3350001 | XML 非 well-formed 或服务端参数校验失败 | 优先检查未转义字符:文本 `Q&A -> Q&amp;A`,文本 `<` / `>` 写成 `&lt;` / `&gt;`,属性 URL `a=1&b=2 -> a=1&amp;b=2` |
## 注意事项
1. **执行前必做**: 使用 `lark-cli schema slides.xml_presentation.slide.create` 查看最新的参数结构
2. **slide.content 格式**: 必须是完整的 `<slide>` 元素,不是整个 presentation
3. **命名空间建议**: 协议标准写法应带 `xmlns`,例如 `<slide xmlns="http://www.larkoffice.com/sml/2.0">`;当前服务端实现可能兼容不带 `xmlns` 的输入,但不作为协议保证
4. **fill / border 写法**: 颜色填充使用 `<fill><fillColor color="..."/></fill>`,边框常用 `<border color="..." width="2"/>`
5. **插入位置**: 通过 `before_slide_id` 指定插入目标,而不是用 `position`
6. **JSON 转义**: 如果直接内联 XML需要正确转义双引号
7. **建议**: 先使用 `slides +xml-get` 获取现有结构,再添加新页面
## 批量添加建议
如果需要添加多张幻灯片,建议先明确每一页的 `before_slide_id`,或直接按最终顺序逐页追加:
```bash
#!/bin/bash
PRESENTATION_ID="slides_example_presentation_id"
declare -a slides=(
'<slide xmlns="http://www.larkoffice.com/sml/2.0"><data><shape type="text" topLeftX="80" topLeftY="80" width="800" height="120"><content textType="title"><p>页面 1</p></content></shape></data></slide>'
'<slide xmlns="http://www.larkoffice.com/sml/2.0"><data><shape type="text" topLeftX="80" topLeftY="80" width="800" height="120"><content textType="title"><p>页面 2</p></content></shape></data></slide>'
'<slide xmlns="http://www.larkoffice.com/sml/2.0"><data><shape type="text" topLeftX="80" topLeftY="80" width="800" height="120"><content textType="title"><p>页面 3</p></content></shape></data></slide>'
)
for slide_xml in "${slides[@]}"; do
payload=$(jq -n --arg content "$slide_xml" '{slide:{content:$content}}')
lark-cli slides xml_presentation.slide create --as user --params "{\"xml_presentation_id\":\"$PRESENTATION_ID\"}" --data "$payload"
done
```
## 相关命令
- [slides +create](lark-slides-create.md) - 创建空白 PPT
- [slides +xml-get](lark-slides-xml-presentations-get.md) - 读取 PPT 内容并保存到本地文件
- [xml_presentation.slide delete](lark-slides-xml-presentation-slide-delete.md) - 删除幻灯片页面
- [xml-schema-quick-ref.md](xml-schema-quick-ref.md) - XML Schema 快速参考

View File

@@ -64,11 +64,11 @@ lark-cli slides xml_presentation.slide delete --as user --params '{"xml_presenta
```json
{
"ok": true,
"identity": "user",
"code": 0,
"data": {
"revision_id": 100
}
},
"msg": "success"
}
```
@@ -121,5 +121,6 @@ done
## 相关命令
- [slides +create](lark-slides-create.md) - 创建 PPT / 添加幻灯片页面
- [slides +xml-get](lark-slides-xml-get.md) - 读取 PPT 内容并保存到本地文件
- [slides +create](lark-slides-create.md) - 创建空白 PPT
- [slides +xml-get](lark-slides-xml-presentations-get.md) - 读取 PPT 内容并保存到本地文件
- [xml_presentation.slide create](lark-slides-xml-presentation-slide-create.md) - 添加幻灯片页面

View File

@@ -94,7 +94,7 @@ lark-cli slides xml_presentation.slide get --as user --params '{
## 注意事项
1. **执行前必做**`lark-cli schema slides.xml_presentation.slide.get` 查看最新参数结构
2. **block_id 提取**:返回 XML 里每个顶层块shape、img、table、chart、whiteboard 等)的 `id` 属性即为 `block_id`,通常是 3 字符短码,例如 `<shape id="bUn" ...>`。用以下命令列出当前页所有 block_id
2. **block_id 提取**:返回 XML 里每个顶层块shape、img、table、chart 等)的 `id` 属性即为 `block_id`,通常是 3 字符短码,例如 `<shape id="bUn" ...>`。用以下命令列出当前页所有 block_id
```bash
lark-cli slides xml_presentation.slide get --as user \
@@ -106,5 +106,5 @@ lark-cli slides xml_presentation.slide get --as user --params '{
- [slides +replace-slide](lark-slides-replace-slide.md) — 块级替换 shortcut推荐
- [xml_presentation.slide replace](lark-slides-xml-presentation-slide-replace.md) — 底层 replace API 参考
- [slides +xml-get](lark-slides-xml-get.md) — 读整个 PPT 并保存到本地文件
- [slides +xml-get](lark-slides-xml-presentations-get.md) — 读整个 PPT 并保存到本地文件
- [lark-slides-edit-workflows.md](lark-slides-edit-workflows.md) — 读-改-写闭环

Some files were not shown because too many files have changed in this diff Show More