Compare commits

..

7 Commits

Author SHA1 Message Date
coderabbitai[bot]
6cfc2317a1 📝 Add docstrings to feat/whiteboard-skill-cli-v0.2.12
Docstrings generation was requested by @cl900811.

* https://github.com/larksuite/cli/pull/1559#issuecomment-4787542760

The following files were modified:

* `shortcuts/whiteboard/whiteboard_query.go`
* `shortcuts/whiteboard/whiteboard_update.go`
2026-06-24 13:12:34 +00:00
cl900811
418068f728 fix(whiteboard): add whiteboard query shortcut unit test 2026-06-24 21:08:48 +08:00
cl900811
cb63055c22 fix(whiteboard): whiteboard shortcuts unit test 2026-06-24 19:30:12 +08:00
cl900811
aeb40e67af feat(whiteboard): pin whiteboard-cli to v0.2.12 in lark-whiteboard skill 2026-06-24 17:52:08 +08:00
cl900811
7889be8902 feat(lark-whiteboard): update shortcut, support query or update whiteboard by svg 2026-06-24 17:52:08 +08:00
ILUO
b46e60c156 feat: add task event consumer (#1510)
* feat: add task event consumer

* fix: address task event review feedback

* feat: remove legacy task event subscription shortcut

* test: strengthen task preconsume error assertions
2026-06-24 17:32:02 +08:00
chenxingtong-bytedance
d71bab0061 docs(im): clarify audio message opus requirement (#1271)
Fix IM shortcut behavior for audio messages to match the Feishu/Lark file upload API: --audio is for voice messages and supports only Opus audio. Non-Opus local/URL inputs such as mp3 and wav are now rejected before upload with an actionable typed validation error. Users can still send those files as attachments with --file
2026-06-24 14:41:54 +08:00
65 changed files with 1637 additions and 2149 deletions

View File

@@ -260,15 +260,6 @@ func TestCollectScopesForDomains_NonexistentDomain(t *testing.T) {
} }
} }
func TestCollectScopesForDomains_SlidesDoesNotAdvertiseScreenshotScope(t *testing.T) {
scopes := collectScopesForDomains([]string{"slides"}, "user", "")
for _, scope := range scopes {
if scope == "slides:presentation:screenshot" {
t.Fatalf("slides domain scopes must not advertise allowlist-gated screenshot scope: %#v", scopes)
}
}
}
func TestGetDomainMetadata_IncludesFromMeta(t *testing.T) { func TestGetDomainMetadata_IncludesFromMeta(t *testing.T) {
domains := getDomainMetadata("zh") domains := getDomainMetadata("zh")
nameSet := make(map[string]bool) nameSet := make(map[string]bool)

View File

@@ -26,6 +26,7 @@ func TestRunList_TextOutput(t *testing.T) {
"KEY", "AUTH", "PARAMS", "DESCRIPTION", "KEY", "AUTH", "PARAMS", "DESCRIPTION",
"im.message.receive_v1", "im.message.receive_v1",
"im.message.message_read_v1", "im.message.message_read_v1",
"task.task.update_user_access_v2",
} { } {
if !strings.Contains(out, want) { if !strings.Contains(out, want) {
t.Errorf("list output missing %q; full output:\n%s", want, out) t.Errorf("list output missing %q; full output:\n%s", want, out)
@@ -55,4 +56,17 @@ func TestRunList_JSONOutput(t *testing.T) {
} }
} }
} }
var foundTask bool
for _, row := range rows {
if row["key"] == "task.task.update_user_access_v2" {
foundTask = true
if row["single_consumer"] != true {
t.Errorf("task row single_consumer = %v, want true", row["single_consumer"])
}
}
}
if !foundTask {
t.Fatal("event list JSON missing task.task.update_user_access_v2")
}
} }

View File

@@ -96,6 +96,34 @@ func TestRunSchema_JSONOutput(t *testing.T) {
} }
} }
func TestRunSchema_TaskUpdateUserAccessJSON(t *testing.T) {
f, stdout, _, _ := cmdutil.TestFactory(t, &core.CliConfig{AppID: "test"})
if err := runSchema(f, "task.task.update_user_access_v2", true); err != nil {
t.Fatalf("runSchema json: %v", err)
}
var payload map[string]interface{}
if err := json.Unmarshal(stdout.Bytes(), &payload); err != nil {
t.Fatalf("output is not valid JSON: %v\n%s", err, stdout.String())
}
if payload["jq_root_path"] != ".event" {
t.Errorf("jq_root_path = %v, want .event", payload["jq_root_path"])
}
if payload["single_consumer"] != true {
t.Errorf("single_consumer = %v, want true", payload["single_consumer"])
}
resolved := payload["resolved_output_schema"].(map[string]interface{})
props := resolved["properties"].(map[string]interface{})
eventProps := props["event"].(map[string]interface{})["properties"].(map[string]interface{})
if got := eventProps["task_guid"].(map[string]interface{})["format"]; got != "task_guid" {
t.Errorf("task_guid format = %v, want task_guid", got)
}
if _, ok := eventProps["event_types"].(map[string]interface{})["items"].(map[string]interface{})["enum"]; !ok {
t.Fatalf("event_types enum missing in schema: %#v", eventProps["event_types"])
}
}
func TestSchema_RendersSubscriptionKeyMarker(t *testing.T) { func TestSchema_RendersSubscriptionKeyMarker(t *testing.T) {
const syntheticKey = "test.evt_sub" const syntheticKey = "test.evt_sub"
t.Cleanup(func() { eventlib.UnregisterKeyForTest(syntheticKey) }) t.Cleanup(func() { eventlib.UnregisterKeyForTest(syntheticKey) })

View File

@@ -7,6 +7,7 @@ package events
import ( import (
"github.com/larksuite/cli/events/im" "github.com/larksuite/cli/events/im"
"github.com/larksuite/cli/events/minutes" "github.com/larksuite/cli/events/minutes"
"github.com/larksuite/cli/events/task"
"github.com/larksuite/cli/events/vc" "github.com/larksuite/cli/events/vc"
"github.com/larksuite/cli/events/whiteboard" "github.com/larksuite/cli/events/whiteboard"
"github.com/larksuite/cli/internal/event" "github.com/larksuite/cli/internal/event"
@@ -17,6 +18,7 @@ func init() {
all := [][]event.KeyDefinition{ all := [][]event.KeyDefinition{
im.Keys(), im.Keys(),
minutes.Keys(), minutes.Keys(),
task.Keys(),
vc.Keys(), vc.Keys(),
whiteboard.Keys(), whiteboard.Keys(),
} }

23
events/task/native.go Normal file
View File

@@ -0,0 +1,23 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package task
// TaskUpdateUserAccessV2Data is the Task v2 update event payload under the
// standard Lark V2 event envelope.
type TaskUpdateUserAccessV2Data struct {
EventTypes []string `json:"event_types,omitempty" desc:"Task commit types included in this event" enum:"task_create,task_deleted,task_summary_update,task_desc_update,task_assignees_update,task_followers_update,task_reminders_update,task_start_due_update,task_completed_update"`
TaskGUID string `json:"task_guid,omitempty" desc:"Task GUID that changed" kind:"task_guid"`
}
var taskUpdateUserAccessCommitTypes = []string{
"task_create",
"task_deleted",
"task_summary_update",
"task_desc_update",
"task_assignees_update",
"task_followers_update",
"task_reminders_update",
"task_start_due_update",
"task_completed_update",
}

32
events/task/preconsume.go Normal file
View File

@@ -0,0 +1,32 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package task
import (
"context"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/event"
)
const taskSubscriptionPath = "/open-apis/task/v2/task_v2/task_subscription?user_id_type=open_id"
func taskSubscriptionPreConsume(ctx context.Context, rt event.APIClient, _ map[string]string) (func() error, error) {
if rt == nil {
return nil, errs.NewInternalError(errs.SubtypeUnknown,
"runtime API client is required for pre-consume subscription")
}
if _, err := rt.CallAPI(ctx, "POST", taskSubscriptionPath, nil); err != nil {
if _, ok := errs.ProblemOf(err); ok {
return nil, err
}
return nil, errs.NewNetworkError(
errs.SubtypeNetworkTransport,
"failed to subscribe task event",
).WithCause(err)
}
return nil, nil
}

View File

@@ -0,0 +1,119 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package task
import (
"context"
"encoding/json"
"errors"
"testing"
"github.com/larksuite/cli/errs"
)
type stubAPIClient struct {
err error
method string
path string
body interface{}
calls int
}
func (s *stubAPIClient) CallAPI(_ context.Context, method, path string, body interface{}) (json.RawMessage, error) {
s.method = method
s.path = path
s.body = body
s.calls++
if s.err != nil {
return nil, s.err
}
return json.RawMessage(`{"code":0,"msg":"success","data":{}}`), nil
}
func TestTaskSubscriptionPreConsumeCallsSubscribeAPI(t *testing.T) {
rt := &stubAPIClient{}
cleanup, err := taskSubscriptionPreConsume(context.Background(), rt, nil)
if err != nil {
t.Fatalf("taskSubscriptionPreConsume error = %v", err)
}
if cleanup != nil {
t.Fatal("cleanup = non-nil, want nil because task subscription has no unsubscribe API")
}
if rt.calls != 1 {
t.Fatalf("calls = %d, want 1", rt.calls)
}
if rt.method != "POST" {
t.Errorf("method = %q, want POST", rt.method)
}
if rt.path != taskSubscriptionPath {
t.Errorf("path = %q, want %q", rt.path, taskSubscriptionPath)
}
if rt.body != nil {
t.Errorf("body = %#v, want nil", rt.body)
}
}
func TestTaskSubscriptionPreConsumeRequiresRuntime(t *testing.T) {
_, err := taskSubscriptionPreConsume(context.Background(), nil, nil)
if err == nil {
t.Fatal("expected error")
}
p, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("expected typed error, got %T: %v", err, err)
}
if p.Category != errs.CategoryInternal {
t.Errorf("category = %s, want %s", p.Category, errs.CategoryInternal)
}
if p.Subtype != errs.SubtypeUnknown {
t.Errorf("subtype = %s, want %s", p.Subtype, errs.SubtypeUnknown)
}
}
func TestTaskSubscriptionPreConsumePassesThroughAPIError(t *testing.T) {
wantErr := errs.NewValidationError(errs.SubtypeFailedPrecondition, "subscription already exists")
rt := &stubAPIClient{err: wantErr}
_, err := taskSubscriptionPreConsume(context.Background(), rt, nil)
if err != wantErr {
t.Fatalf("err identity changed: got %T %v, want original %T %v", err, err, wantErr, wantErr)
}
if !errors.Is(err, wantErr) {
t.Fatalf("err = %v, want %v", err, wantErr)
}
p, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("expected typed error, got %T: %v", err, err)
}
if p.Category != errs.CategoryValidation {
t.Errorf("category = %s, want %s", p.Category, errs.CategoryValidation)
}
if p.Subtype != errs.SubtypeFailedPrecondition {
t.Errorf("subtype = %s, want %s", p.Subtype, errs.SubtypeFailedPrecondition)
}
}
func TestTaskSubscriptionPreConsumeWrapsUntypedAPIError(t *testing.T) {
cause := errors.New("connection reset")
rt := &stubAPIClient{err: cause}
_, err := taskSubscriptionPreConsume(context.Background(), rt, nil)
if err == nil {
t.Fatal("expected error")
}
if !errors.Is(err, cause) {
t.Fatalf("err = %v, want cause %v", err, cause)
}
p, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("expected typed error, got %T: %v", err, err)
}
if p.Category != errs.CategoryNetwork {
t.Errorf("category = %s, want %s", p.Category, errs.CategoryNetwork)
}
if p.Subtype != errs.SubtypeNetworkTransport {
t.Errorf("subtype = %s, want %s", p.Subtype, errs.SubtypeNetworkTransport)
}
}

33
events/task/register.go Normal file
View File

@@ -0,0 +1,33 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
// Package task registers Task-domain EventKeys.
package task
import (
"reflect"
"github.com/larksuite/cli/internal/event"
)
const eventTypeTaskUpdateUserAccessV2 = "task.task.update_user_access_v2"
// Keys returns all Task-domain EventKey definitions.
func Keys() []event.KeyDefinition {
return []event.KeyDefinition{
{
Key: eventTypeTaskUpdateUserAccessV2,
DisplayName: "Task updated",
Description: "Triggered when tasks visible to the current user or app are created, deleted, or updated",
EventType: eventTypeTaskUpdateUserAccessV2,
Schema: event.SchemaDef{
Native: &event.SchemaSpec{Type: reflect.TypeOf(TaskUpdateUserAccessV2Data{})},
},
PreConsume: taskSubscriptionPreConsume,
Scopes: []string{"task:task:read"},
AuthTypes: []string{"user", "bot"},
RequiredConsoleEvents: []string{eventTypeTaskUpdateUserAccessV2},
SingleConsumer: true,
},
}
}

View File

@@ -0,0 +1,95 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package task
import (
"encoding/json"
"reflect"
"testing"
"github.com/larksuite/cli/internal/event"
"github.com/larksuite/cli/internal/event/schemas"
)
func TestKeysTaskUpdateUserAccessMetadata(t *testing.T) {
keys := Keys()
if len(keys) != 1 {
t.Fatalf("len(Keys()) = %d, want 1", len(keys))
}
def := keys[0]
if def.Key != eventTypeTaskUpdateUserAccessV2 {
t.Errorf("Key = %q, want %q", def.Key, eventTypeTaskUpdateUserAccessV2)
}
if def.EventType != eventTypeTaskUpdateUserAccessV2 {
t.Errorf("EventType = %q, want %q", def.EventType, eventTypeTaskUpdateUserAccessV2)
}
if def.Schema.Native == nil {
t.Fatal("Schema.Native is nil")
}
if def.Schema.Native.Type != reflect.TypeOf(TaskUpdateUserAccessV2Data{}) {
t.Errorf("native type = %v, want TaskUpdateUserAccessV2Data", def.Schema.Native.Type)
}
if def.Process != nil {
t.Fatal("Native Task EventKey must not set Process")
}
if def.PreConsume == nil {
t.Fatal("PreConsume is nil")
}
if !def.SingleConsumer {
t.Fatal("SingleConsumer = false, want true")
}
if !reflect.DeepEqual(def.Scopes, []string{"task:task:read"}) {
t.Errorf("Scopes = %#v", def.Scopes)
}
if !reflect.DeepEqual(def.AuthTypes, []string{"user", "bot"}) {
t.Errorf("AuthTypes = %#v", def.AuthTypes)
}
if !reflect.DeepEqual(def.RequiredConsoleEvents, []string{eventTypeTaskUpdateUserAccessV2}) {
t.Errorf("RequiredConsoleEvents = %#v", def.RequiredConsoleEvents)
}
}
func TestTaskUpdateUserAccessSchemaAnnotations(t *testing.T) {
raw := schemas.WrapV2Envelope(schemas.FromType(reflect.TypeOf(TaskUpdateUserAccessV2Data{})))
var schema map[string]interface{}
if err := json.Unmarshal(raw, &schema); err != nil {
t.Fatalf("unmarshal schema: %v", err)
}
eventProps := schema["properties"].(map[string]interface{})["event"].(map[string]interface{})["properties"].(map[string]interface{})
taskGUID := eventProps["task_guid"].(map[string]interface{})
if got := taskGUID["format"]; got != "task_guid" {
t.Errorf("task_guid format = %v, want task_guid", got)
}
eventTypes := eventProps["event_types"].(map[string]interface{})
items := eventTypes["items"].(map[string]interface{})
rawEnum, ok := items["enum"].([]interface{})
if !ok {
t.Fatalf("event_types item enum missing: %#v", items["enum"])
}
got := make(map[string]bool, len(rawEnum))
for _, v := range rawEnum {
got[v.(string)] = true
}
for _, want := range taskUpdateUserAccessCommitTypes {
if !got[want] {
t.Errorf("event_types enum missing %q; enum=%v", want, rawEnum)
}
}
}
func TestTaskUpdateUserAccessRegistersCleanly(t *testing.T) {
const key = eventTypeTaskUpdateUserAccessV2
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)
}
}

View File

@@ -469,6 +469,29 @@ func TestShortcutValidateBranches(t *testing.T) {
} }
}) })
t.Run("ImMessagesSend audio rejects non-opus local file", func(t *testing.T) {
runtime := newTestRuntimeContext(t, map[string]string{
"chat-id": "oc_123",
"audio": "./voice.mp3",
}, nil)
err := ImMessagesSend.Validate(context.Background(), runtime)
if err == nil || !strings.Contains(err.Error(), "--audio supports only Opus audio files") {
t.Fatalf("ImMessagesSend.Validate() error = %v", err)
}
})
t.Run("ImMessagesSend audio accepts opus and ogg local files", func(t *testing.T) {
for _, audio := range []string{"./voice.opus", "./voice.ogg"} {
runtime := newTestRuntimeContext(t, map[string]string{
"chat-id": "oc_123",
"audio": audio,
}, nil)
if err := ImMessagesSend.Validate(context.Background(), runtime); err != nil {
t.Fatalf("ImMessagesSend.Validate(%q) unexpected error = %v", audio, err)
}
}
})
t.Run("ImMessagesSend conflicting explicit msg-type", func(t *testing.T) { t.Run("ImMessagesSend conflicting explicit msg-type", func(t *testing.T) {
runtime := newTestRuntimeContext(t, map[string]string{ runtime := newTestRuntimeContext(t, map[string]string{
"chat-id": "oc_123", "chat-id": "oc_123",
@@ -492,6 +515,17 @@ func TestShortcutValidateBranches(t *testing.T) {
} }
}) })
t.Run("ImMessagesReply audio rejects non-opus local file", func(t *testing.T) {
runtime := newTestRuntimeContext(t, map[string]string{
"message-id": "om_123",
"audio": "./voice.mp3",
}, nil)
err := ImMessagesReply.Validate(context.Background(), runtime)
if err == nil || !strings.Contains(err.Error(), "--audio supports only Opus audio files") {
t.Fatalf("ImMessagesReply.Validate() error = %v", err)
}
})
t.Run("ImThreadsMessagesList invalid thread", func(t *testing.T) { t.Run("ImThreadsMessagesList invalid thread", func(t *testing.T) {
runtime := newTestRuntimeContext(t, map[string]string{ runtime := newTestRuntimeContext(t, map[string]string{
"thread": "bad_thread", "thread": "bad_thread",

View File

@@ -1048,6 +1048,42 @@ func detectIMFileType(filePath string) string {
} }
} }
const (
audioMessageInputDesc = "audio file key (file_xxx), URL, or cwd-relative local path for a voice message (absolute paths and .. are rejected); local paths and URLs must be Opus (.opus or Ogg Opus .ogg). For mp3/wav, convert to .opus first, or use --file to send as an attachment"
audioMessageHint = "Convert non-Opus audio to .opus and use --audio for a voice message, for example: ffmpeg -i input.mp3 -acodec libopus -ac 1 -ar 16000 output.opus. To send the original mp3/wav as an attachment, use --file instead."
)
func validateAudioMessageInput(flagName, value string) error {
value = strings.TrimSpace(value)
if value == "" || isMediaKey(value) {
return nil
}
ext := audioInputExt(value)
if ext == "" {
return nil
}
if ext == ".opus" || ext == ".ogg" {
return nil
}
return errs.NewValidationError(
errs.SubtypeInvalidArgument,
"%s supports only Opus audio files for audio messages, such as .opus files or Ogg Opus (.ogg) files",
flagName,
).WithParam(flagName).WithHint("%s", audioMessageHint)
}
func audioInputExt(value string) string {
if isURL(value) {
parsed, err := url.Parse(value)
if err != nil {
return ""
}
return strings.ToLower(path.Ext(parsed.Path))
}
return strings.ToLower(filepath.Ext(value))
}
const maxImageUploadSize = 5 * 1024 * 1024 // 5MB — Lark API limit for images const maxImageUploadSize = 5 * 1024 * 1024 // 5MB — Lark API limit for images
const maxFileUploadSize = 100 * 1024 * 1024 // 100MB — Lark API limit for files const maxFileUploadSize = 100 * 1024 * 1024 // 100MB — Lark API limit for files

View File

@@ -13,6 +13,7 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/shortcuts/common" "github.com/larksuite/cli/shortcuts/common"
) )
@@ -50,6 +51,56 @@ func TestDetectIMFileType(t *testing.T) {
} }
} }
func TestValidateAudioMessageInput(t *testing.T) {
tests := []struct {
name string
value string
wantErr bool
}{
{name: "empty", value: ""},
{name: "existing file key", value: "file_abc"},
{name: "opus file", value: "./voice.opus"},
{name: "ogg opus file", value: "./voice.ogg"},
{name: "uppercase opus", value: "./VOICE.OPUS"},
{name: "mp3 local file", value: "./voice.mp3", wantErr: true},
{name: "wav local file", value: "./voice.wav", wantErr: true},
{name: "extensionless local path", value: "./voice"},
{name: "opus url", value: "https://example.com/voice.opus?download=1"},
{name: "ogg url", value: "https://example.com/voice.ogg?download=1"},
{name: "mp3 url", value: "https://example.com/voice.mp3?download=1", wantErr: true},
{name: "extensionless url", value: "https://example.com/download?id=1"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateAudioMessageInput("--audio", tt.value)
if tt.wantErr {
if err == nil || !strings.Contains(err.Error(), "--audio supports only Opus audio files") {
t.Fatalf("validateAudioMessageInput(%q) error = %v", tt.value, err)
}
p, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("validateAudioMessageInput(%q) error is not typed: %v", tt.value, err)
}
if p.Category != errs.CategoryValidation || p.Subtype != errs.SubtypeInvalidArgument {
t.Fatalf("ProblemOf(%q) = category %q subtype %q", tt.value, p.Category, p.Subtype)
}
validationErr, ok := err.(*errs.ValidationError)
if !ok || validationErr.Param != "--audio" {
t.Fatalf("validateAudioMessageInput(%q) param = %q, want --audio", tt.value, validationErr.Param)
}
if !strings.Contains(p.Hint, "use --file") || !strings.Contains(p.Hint, "ffmpeg") {
t.Fatalf("validateAudioMessageInput(%q) hint = %q, want --file and ffmpeg guidance", tt.value, p.Hint)
}
return
}
if err != nil {
t.Fatalf("validateAudioMessageInput(%q) unexpected error = %v", tt.value, err)
}
})
}
}
// TestSplitCSV covers the shared helper that replaced the three identical functions // TestSplitCSV covers the shared helper that replaced the three identical functions
func TestSplitCSV(t *testing.T) { func TestSplitCSV(t *testing.T) {
tests := []struct { tests := []struct {

View File

@@ -33,7 +33,7 @@ var ImMessagesReply = common.Shortcut{
{Name: "file", Desc: "file key (file_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected)"}, {Name: "file", Desc: "file key (file_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected)"},
{Name: "video", Desc: "video file key (file_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected); must be used together with --video-cover"}, {Name: "video", Desc: "video file key (file_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected); must be used together with --video-cover"},
{Name: "video-cover", Desc: "video cover image key (img_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected); required when using --video"}, {Name: "video-cover", Desc: "video cover image key (img_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected); required when using --video"},
{Name: "audio", Desc: "audio file key (file_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected)"}, {Name: "audio", Desc: audioMessageInputDesc},
{Name: "reply-in-thread", Type: "bool", Desc: "reply in thread (message appears in thread stream instead of main chat)"}, {Name: "reply-in-thread", Type: "bool", Desc: "reply in thread (message appears in thread stream instead of main chat)"},
{Name: "idempotency-key", Desc: "idempotency key (prevents duplicate sends)"}, {Name: "idempotency-key", Desc: "idempotency key (prevents duplicate sends)"},
}, },
@@ -100,6 +100,9 @@ var ImMessagesReply = common.Shortcut{
return err return err
} }
} }
if err := validateAudioMessageInput("--audio", audioKey); err != nil {
return err
}
if messageId == "" { if messageId == "" {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--message-id is required (om_xxx)").WithParam("--message-id") return errs.NewValidationError(errs.SubtypeInvalidArgument, "--message-id is required (om_xxx)").WithParam("--message-id")

View File

@@ -37,7 +37,7 @@ var ImMessagesSend = common.Shortcut{
{Name: "file", Desc: "file key (file_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected)"}, {Name: "file", Desc: "file key (file_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected)"},
{Name: "video", Desc: "video file key (file_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected); must be used together with --video-cover"}, {Name: "video", Desc: "video file key (file_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected); must be used together with --video-cover"},
{Name: "video-cover", Desc: "video cover image key (img_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected); required when using --video"}, {Name: "video-cover", Desc: "video cover image key (img_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected); required when using --video"},
{Name: "audio", Desc: "audio file key (file_xxx), URL, or cwd-relative local path (absolute paths and .. are rejected)"}, {Name: "audio", Desc: audioMessageInputDesc},
}, },
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI { DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
chatFlag := runtime.Str("chat-id") chatFlag := runtime.Str("chat-id")
@@ -112,6 +112,9 @@ var ImMessagesSend = common.Shortcut{
return err return err
} }
} }
if err := validateAudioMessageInput("--audio", audioKey); err != nil {
return err
}
if err := common.ExactlyOneTyped(runtime, "chat-id", "user-id"); err != nil { if err := common.ExactlyOneTyped(runtime, "chat-id", "user-id"); err != nil {
return err return err

View File

@@ -11,8 +11,6 @@ func Shortcuts() []common.Shortcut {
SlidesCreate, SlidesCreate,
SlidesMediaUpload, SlidesMediaUpload,
SlidesReplaceSlide, SlidesReplaceSlide,
SlidesReplacePages,
SlidesScreenshot, SlidesScreenshot,
SlidesXMLGet,
} }
} }

View File

@@ -204,11 +204,13 @@ var SlidesCreate = common.Shortcut{
} }
} }
// Prefer the URL returned by presentation.create. Fall back to a local // Build the presentation URL locally from the token. The brand-standard
// brand-standard URL only when the API omits it. // host transparently redirects to the tenant domain (same fallback used by
if url := common.GetString(data, "url"); url != "" { // drive +upload / wiki +node-create). This avoids the prior best-effort
result["url"] = url // drive metas/batch_query call, which needed an extra drive scope and 403'd
} else if url := common.BuildResourceURL(runtime.Config.Brand, "slides", presentationID); url != "" { // for users who only authorized slides scopes — without ever blocking an
// otherwise-successful creation.
if url := common.BuildResourceURL(runtime.Config.Brand, "slides", presentationID); url != "" {
result["url"] = url result["url"] = url
} }

View File

@@ -34,7 +34,6 @@ func TestSlidesCreateBasic(t *testing.T) {
"data": map[string]interface{}{ "data": map[string]interface{}{
"xml_presentation_id": "pres_abc123", "xml_presentation_id": "pres_abc123",
"revision_id": 1, "revision_id": 1,
"url": "https://tenant.example.com/slides/pres_abc123",
}, },
}, },
}) })
@@ -55,8 +54,10 @@ func TestSlidesCreateBasic(t *testing.T) {
if data["title"] != "项目汇报" { if data["title"] != "项目汇报" {
t.Fatalf("title = %v, want 项目汇报", data["title"]) t.Fatalf("title = %v, want 项目汇报", data["title"])
} }
if data["url"] != "https://tenant.example.com/slides/pres_abc123" { // URL is built locally from the token (brand-standard host), not fetched from
t.Fatalf("url = %v, want https://tenant.example.com/slides/pres_abc123", data["url"]) // drive metas, so it is deterministic and needs no drive scope.
if data["url"] != "https://www.feishu.cn/slides/pres_abc123" {
t.Fatalf("url = %v, want https://www.feishu.cn/slides/pres_abc123", data["url"])
} }
if _, ok := data["permission_grant"]; ok { if _, ok := data["permission_grant"]; ok {
t.Fatalf("did not expect permission_grant in user mode") t.Fatalf("did not expect permission_grant in user mode")
@@ -646,12 +647,12 @@ func TestSlidesCreateWithoutSlidesUnchanged(t *testing.T) {
} }
} }
// TestSlidesCreateURLFallsBackToLocalBuild verifies the presentation URL is // TestSlidesCreateURLBuiltLocally verifies the presentation URL is constructed
// constructed locally from the token when presentation.create omits url — no // locally from the token — no drive metas/batch_query call is made, so creation
// drive metas/batch_query call is made, so creation works for users who only // works for users who only authorized slides scopes. The httpmock registry has no
// authorized slides scopes. The httpmock registry has no batch_query stub // batch_query stub registered; if the shortcut tried to call it, the request would
// registered; if the shortcut tried to call it, the request would fail the test. // fail the test (unregistered stub), proving the URL is built without a drive call.
func TestSlidesCreateURLFallsBackToLocalBuild(t *testing.T) { func TestSlidesCreateURLBuiltLocally(t *testing.T) {
t.Parallel() t.Parallel()
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, "")) f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
@@ -664,7 +665,6 @@ func TestSlidesCreateURLFallsBackToLocalBuild(t *testing.T) {
"data": map[string]interface{}{ "data": map[string]interface{}{
"xml_presentation_id": "pres_local_url", "xml_presentation_id": "pres_local_url",
"revision_id": 1, "revision_id": 1,
"url": "",
}, },
}, },
}) })

View File

@@ -1,413 +0,0 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package slides
import (
"context"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"strings"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/validate"
"github.com/larksuite/cli/shortcuts/common"
)
// SlidesReplacePages rebuilds multiple pages inside an existing presentation.
// It deliberately creates the new page before deleting the old one so a create
// failure cannot remove existing user content. The operation is not atomic.
const replacePagesInitialRevisionID = -1
var SlidesReplacePages = common.Shortcut{
Service: "slides",
Command: "+replace-pages",
Description: "Batch rebuild pages inside an existing Slides presentation (create before old page, then delete old page; not atomic)",
Risk: "write",
Scopes: []string{"slides:presentation:update", "slides:presentation:write_only", "wiki:node:read"},
AuthTypes: []string{"user", "bot"},
Flags: []common.Flag{
{Name: "presentation", Desc: "xml_presentation_id, slides URL, or wiki URL that resolves to slides", Required: true},
{Name: "pages", Desc: "JSON array of page replacements (each: {slide_id, content}); supports @file or -", Required: true, Input: []string{common.File, common.Stdin}},
{Name: "continue-on-error", Type: "bool", Desc: "continue with later pages after a create/delete failure; default false"},
{Name: "validate-only", Type: "bool", Desc: "validate input and build the create/delete plan without write calls"},
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
if _, err := parsePresentationRef(runtime.Str("presentation")); err != nil {
return err
}
pages, err := parseReplacePages(runtime.Str("pages"))
if err != nil {
return err
}
return validateReplacePagesInput(pages)
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
dry := common.NewDryRunAPI()
resolved, err := prepareReplacePages(runtime)
if err != nil {
return dry.Set("error", err.Error())
}
appendReplacePagesDryRunCalls(dry, resolved)
return dry.
Set("xml_presentation_id", resolved.PresentationID).
Set("pages_count", len(resolved.Plan)).
Set("plan", replacePagesPlanOutput(resolved.Plan)).
Set("note", "dry-run built a create/delete plan from slide_id inputs; no Slides presentation get/create/delete calls were executed")
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
resolved, err := prepareReplacePages(runtime)
if err != nil {
return err
}
if runtime.Bool("validate-only") {
runtime.Out(map[string]interface{}{
"xml_presentation_id": resolved.PresentationID,
"pages_count": len(resolved.Plan),
"plan": replacePagesPlanOutput(resolved.Plan),
"status": "validated",
"note": "validate-only checked input and built the create/delete plan; no Slides presentation get/create/delete calls were executed",
}, nil)
return nil
}
revisionID := replacePagesInitialRevisionID
results := make([]replacePageResult, 0, len(resolved.Plan))
for i, item := range resolved.Plan {
result, err := replaceOnePage(runtime, resolved.PresentationID, item, revisionID)
results = append(results, result)
if result.RevisionID != nil {
revisionID = *result.RevisionID
}
if err != nil {
if runtime.Bool("continue-on-error") {
continue
}
return appendSlidesProgressHint(err, fmt.Sprintf("slides +replace-pages stopped at item %d/%d; %d page(s) completed before failure; old page is kept when create failed", i+1, len(resolved.Plan), countReplacedPages(results)))
}
}
out := map[string]interface{}{
"xml_presentation_id": resolved.PresentationID,
"pages_count": len(resolved.Plan),
"results": replacePageResultsOutput(results),
"status": "completed",
"summary": replacePagesSummaryOutput(results),
"note": "batch replace is not atomic; each page was created before its old page was deleted",
}
if revisionID != replacePagesInitialRevisionID {
out["revision_id"] = revisionID
}
if hasReplacePageFailures(results) {
out["status"] = "partial_failure"
return runtime.OutPartialFailure(out, nil)
}
runtime.Out(out, nil)
return nil
},
}
type replacePageInput struct {
SlideID string
Content string
}
type replacePagePlanItem struct {
OldSlideID string
Content string
Locator string
}
type replacePagesPrepared struct {
PresentationID string
Plan []replacePagePlanItem
}
type replacePageResult struct {
OldSlideID string
NewSlideID string
Status string
Error string
RevisionID *int
}
func prepareReplacePages(runtime *common.RuntimeContext) (*replacePagesPrepared, error) {
ref, err := parsePresentationRef(runtime.Str("presentation"))
if err != nil {
return nil, err
}
presentationID, err := resolvePresentationID(runtime, ref)
if err != nil {
return nil, err
}
pages, err := parseReplacePages(runtime.Str("pages"))
if err != nil {
return nil, err
}
if err := validateReplacePagesInput(pages); err != nil {
return nil, err
}
plan, err := buildReplacePagesPlan(pages)
if err != nil {
return nil, err
}
return &replacePagesPrepared{PresentationID: presentationID, Plan: plan}, nil
}
func parseReplacePages(raw string) ([]replacePageInput, error) {
s := strings.TrimSpace(raw)
if s == "" {
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--pages cannot be empty").WithParam("--pages")
}
var decoded []map[string]interface{}
if err := json.Unmarshal([]byte(s), &decoded); err != nil {
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--pages invalid JSON, must be an array of objects: %v", err).WithParam("--pages").WithCause(err)
}
out := make([]replacePageInput, 0, len(decoded))
for i, m := range decoded {
p := replacePageInput{}
if v, ok := m["slide_number"]; ok {
_ = v
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--pages[%d].slide_number is no longer supported; use slide_id", i).WithParam("--pages").WithHint("read current slide IDs first, then pass slide_id for each page replacement")
}
if v, ok := m["slide_id"]; ok {
s, ok := v.(string)
if !ok {
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--pages[%d].slide_id must be a string", i).WithParam("--pages")
}
p.SlideID = s
}
if v, ok := m["content"]; ok {
s, ok := v.(string)
if !ok {
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--pages[%d].content must be a string", i).WithParam("--pages")
}
p.Content = s
}
out = append(out, p)
}
return out, nil
}
func validateReplacePagesInput(pages []replacePageInput) error {
if len(pages) == 0 {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--pages must contain at least 1 item").WithParam("--pages")
}
seenIDs := map[string]bool{}
for i, p := range pages {
id := strings.TrimSpace(p.SlideID)
if id == "" {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--pages[%d].slide_id is required", i).WithParam("--pages")
}
if seenIDs[id] {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--pages contains duplicate slide_id %q", id).WithParam("--pages")
}
seenIDs[id] = true
if strings.TrimSpace(p.Content) == "" {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--pages[%d].content cannot be empty", i).WithParam("--pages")
}
if err := validateCompleteSlideXML(p.Content); err != nil {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--pages[%d].content must be a complete <slide> XML element: %v", i, err).WithParam("--pages").WithCause(err)
}
}
return nil
}
func validateCompleteSlideXML(content string) error {
dec := xml.NewDecoder(strings.NewReader(content))
depth := 0
seenRoot := false
for {
tok, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
return err
}
switch t := tok.(type) {
case xml.StartElement:
if depth == 0 {
if seenRoot {
return fmt.Errorf("multiple root elements")
}
if t.Name.Local != "slide" {
return fmt.Errorf("root element is <%s>, want <slide>", t.Name.Local)
}
seenRoot = true
}
depth++
case xml.EndElement:
depth--
case xml.CharData:
if depth == 0 && strings.TrimSpace(string(t)) != "" {
return fmt.Errorf("non-whitespace text outside root element")
}
}
}
if !seenRoot {
return fmt.Errorf("missing root element")
}
if depth != 0 {
return fmt.Errorf("unclosed XML element")
}
return nil
}
func buildReplacePagesPlan(pages []replacePageInput) ([]replacePagePlanItem, error) {
plan := make([]replacePagePlanItem, 0, len(pages))
for _, page := range pages {
id := strings.TrimSpace(page.SlideID)
plan = append(plan, replacePagePlanItem{
OldSlideID: id,
Content: page.Content,
Locator: "slide_id",
})
}
return plan, nil
}
func appendReplacePagesDryRunCalls(dry *common.DryRunAPI, resolved *replacePagesPrepared) {
dry.Desc("Batch replace pages in-place: create each new page before old page, then delete old page (not atomic)")
for i, item := range resolved.Plan {
dry.POST(fmt.Sprintf("/open-apis/slides_ai/v1/xml_presentations/%s/slide", validate.EncodePathSegment(resolved.PresentationID))).
Desc(fmt.Sprintf("[%d/%d] Create replacement before old slide %s", i*2+1, len(resolved.Plan)*2, item.OldSlideID)).
Params(map[string]interface{}{"revision_id": "<latest_or_revision_returned_by_previous_step>"}).
Body(map[string]interface{}{
"slide": map[string]interface{}{"content": item.Content},
"before_slide_id": item.OldSlideID,
})
dry.DELETE(fmt.Sprintf("/open-apis/slides_ai/v1/xml_presentations/%s/slide", validate.EncodePathSegment(resolved.PresentationID))).
Desc(fmt.Sprintf("[%d/%d] Delete old slide %s after create succeeds", i*2+2, len(resolved.Plan)*2, item.OldSlideID)).
Params(map[string]interface{}{
"slide_id": item.OldSlideID,
"revision_id": "<revision_returned_by_create>",
})
}
}
func replaceOnePage(runtime *common.RuntimeContext, presentationID string, item replacePagePlanItem, revisionID int) (replacePageResult, error) {
result := replacePageResult{
OldSlideID: item.OldSlideID,
Status: "pending",
}
slideURL := fmt.Sprintf("/open-apis/slides_ai/v1/xml_presentations/%s/slide", validate.EncodePathSegment(presentationID))
createData, err := runtime.CallAPITyped(
"POST",
slideURL,
map[string]interface{}{"revision_id": revisionID},
map[string]interface{}{
"slide": map[string]interface{}{"content": item.Content},
"before_slide_id": item.OldSlideID,
},
)
if err != nil {
result.Status = "create_failed"
result.Error = err.Error()
return result, err
}
newSlideID := common.GetString(createData, "slide_id")
if newSlideID == "" {
err := errs.NewInternalError(errs.SubtypeInvalidResponse, "slide.create returned no slide_id for replacement of slide_id %q", item.OldSlideID)
result.Status = "create_failed"
result.Error = err.Error()
return result, err
}
result.NewSlideID = newSlideID
if rev, ok := revisionFromData(createData); ok {
revisionID = rev
result.RevisionID = &rev
}
deleteData, err := runtime.CallAPITyped(
"DELETE",
slideURL,
map[string]interface{}{
"slide_id": item.OldSlideID,
"revision_id": revisionID,
},
nil,
)
if err != nil {
result.Status = "delete_failed"
result.Error = err.Error()
return result, err
}
if rev, ok := revisionFromData(deleteData); ok {
result.RevisionID = &rev
}
result.Status = "replaced"
return result, nil
}
func revisionFromData(data map[string]interface{}) (int, bool) {
if _, ok := data["revision_id"]; !ok {
return 0, false
}
return int(common.GetFloat(data, "revision_id")), true
}
func replacePagesPlanOutput(plan []replacePagePlanItem) []map[string]interface{} {
out := make([]map[string]interface{}, 0, len(plan))
for _, item := range plan {
out = append(out, map[string]interface{}{
"old_slide_id": item.OldSlideID,
"insert_before_slide_id": item.OldSlideID,
"locator": item.Locator,
"action": "create_before_then_delete_old",
})
}
return out
}
func replacePageResultsOutput(results []replacePageResult) []map[string]interface{} {
out := make([]map[string]interface{}, 0, len(results))
for _, result := range results {
m := map[string]interface{}{
"old_slide_id": result.OldSlideID,
"status": result.Status,
}
if result.NewSlideID != "" {
m["new_slide_id"] = result.NewSlideID
}
if result.Error != "" {
m["error"] = result.Error
}
if result.RevisionID != nil {
m["revision_id"] = *result.RevisionID
}
out = append(out, m)
}
return out
}
func replacePagesSummaryOutput(results []replacePageResult) map[string]interface{} {
replaced := countReplacedPages(results)
return map[string]interface{}{
"replaced": replaced,
"failed": len(results) - replaced,
"total": len(results),
}
}
func countReplacedPages(results []replacePageResult) int {
n := 0
for _, result := range results {
if result.Status == "replaced" {
n++
}
}
return n
}
func hasReplacePageFailures(results []replacePageResult) bool {
for _, result := range results {
if result.Status == "create_failed" || result.Status == "delete_failed" {
return true
}
}
return false
}

View File

@@ -1,306 +0,0 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package slides
import (
"encoding/json"
"errors"
"strings"
"testing"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/internal/httpmock"
"github.com/larksuite/cli/internal/output"
)
func TestReplacePagesCreatesBeforeThenDeletesOld(t *testing.T) {
t.Parallel()
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
createStub := &httpmock.Stub{
Method: "POST",
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_abc/slide",
Body: map[string]interface{}{
"code": 0,
"data": map[string]interface{}{"slide_id": "new2", "revision_id": 11},
},
}
reg.Register(createStub)
deleteStub := &httpmock.Stub{
Method: "DELETE",
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_abc/slide",
Body: map[string]interface{}{
"code": 0,
"data": map[string]interface{}{"revision_id": 12},
},
}
reg.Register(deleteStub)
pages := `[{"slide_id":"old2","content":"<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data></data></slide>"}]`
err := runSlidesShortcut(t, f, stdout, SlidesReplacePages, []string{
"+replace-pages",
"--presentation", "pres_abc",
"--pages", pages,
"--as", "user",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var createBody struct {
Slide struct {
Content string `json:"content"`
} `json:"slide"`
BeforeSlideID string `json:"before_slide_id"`
}
if err := json.Unmarshal(createStub.CapturedBody, &createBody); err != nil {
t.Fatalf("decode create body: %v\nraw=%s", err, createStub.CapturedBody)
}
if createBody.BeforeSlideID != "old2" {
t.Fatalf("before_slide_id = %q, want old2", createBody.BeforeSlideID)
}
if !strings.Contains(createBody.Slide.Content, "<slide") {
t.Fatalf("create content = %q", createBody.Slide.Content)
}
deleteURL := string(deleteStub.CapturedBody)
if deleteURL != "" {
t.Fatalf("delete body = %q, want empty", deleteURL)
}
data := decodeShortcutData(t, stdout)
if data["xml_presentation_id"] != "pres_abc" {
t.Fatalf("xml_presentation_id = %v", data["xml_presentation_id"])
}
if data["revision_id"] != float64(12) {
t.Fatalf("revision_id = %v, want 12", data["revision_id"])
}
summary, _ := data["summary"].(map[string]interface{})
if summary["failed"] != float64(0) {
t.Fatalf("summary.failed = %v, want 0", summary["failed"])
}
results, _ := data["results"].([]interface{})
if len(results) != 1 {
t.Fatalf("results len = %d, want 1", len(results))
}
first, _ := results[0].(map[string]interface{})
if first["old_slide_id"] != "old2" || first["new_slide_id"] != "new2" || first["status"] != "replaced" {
t.Fatalf("result = %#v", first)
}
}
func TestReplacePagesContinueOnErrorReturnsPartialFailure(t *testing.T) {
t.Parallel()
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_abc/slide",
Body: map[string]interface{}{
"code": 3350001,
"msg": "invalid param",
"data": map[string]interface{}{},
},
})
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_abc/slide",
Body: map[string]interface{}{
"code": 0,
"data": map[string]interface{}{"slide_id": "new2", "revision_id": 11},
},
})
reg.Register(&httpmock.Stub{
Method: "DELETE",
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_abc/slide",
Body: map[string]interface{}{
"code": 0,
"data": map[string]interface{}{"revision_id": 12},
},
})
pages := `[
{"slide_id":"old1","content":"<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data></data></slide>"},
{"slide_id":"old2","content":"<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data></data></slide>"}
]`
err := runSlidesShortcut(t, f, stdout, SlidesReplacePages, []string{
"+replace-pages",
"--presentation", "pres_abc",
"--pages", pages,
"--continue-on-error",
"--as", "user",
})
var pfErr *output.PartialFailureError
if !errors.As(err, &pfErr) {
t.Fatalf("err = %T %v, want *output.PartialFailureError", err, err)
}
env := decodeReplacePagesEnvelope(t, stdout)
if env.OK {
t.Fatalf("stdout ok = true, want false for partial failure")
}
data := env.Data
if data["status"] != "partial_failure" {
t.Fatalf("status = %v, want partial_failure", data["status"])
}
summary, _ := data["summary"].(map[string]interface{})
if summary["replaced"] != float64(1) || summary["failed"] != float64(1) || summary["total"] != float64(2) {
t.Fatalf("summary = %#v, want replaced=1 failed=1 total=2", summary)
}
results, _ := data["results"].([]interface{})
if len(results) != 2 {
t.Fatalf("results len = %d, want 2", len(results))
}
first, _ := results[0].(map[string]interface{})
second, _ := results[1].(map[string]interface{})
if first["status"] != "create_failed" {
t.Fatalf("first status = %v, want create_failed", first["status"])
}
if second["status"] != "replaced" || second["new_slide_id"] != "new2" {
t.Fatalf("second result = %#v, want replaced with new2", second)
}
}
func TestReplacePagesContinueOnErrorDeleteFailureIncludesNewSlideID(t *testing.T) {
t.Parallel()
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_abc/slide",
Body: map[string]interface{}{
"code": 0,
"data": map[string]interface{}{"slide_id": "new1", "revision_id": 11},
},
})
reg.Register(&httpmock.Stub{
Method: "DELETE",
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_abc/slide",
Body: map[string]interface{}{
"code": 3350001,
"msg": "invalid param",
"data": map[string]interface{}{},
},
})
pages := `[{"slide_id":"old1","content":"<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data></data></slide>"}]`
err := runSlidesShortcut(t, f, stdout, SlidesReplacePages, []string{
"+replace-pages",
"--presentation", "pres_abc",
"--pages", pages,
"--continue-on-error",
"--as", "user",
})
var pfErr *output.PartialFailureError
if !errors.As(err, &pfErr) {
t.Fatalf("err = %T %v, want *output.PartialFailureError", err, err)
}
env := decodeReplacePagesEnvelope(t, stdout)
if env.OK {
t.Fatalf("stdout ok = true, want false for partial failure")
}
results, _ := env.Data["results"].([]interface{})
if len(results) != 1 {
t.Fatalf("results len = %d, want 1", len(results))
}
first, _ := results[0].(map[string]interface{})
if first["status"] != "delete_failed" {
t.Fatalf("status = %v, want delete_failed", first["status"])
}
if first["new_slide_id"] != "new1" {
t.Fatalf("new_slide_id = %v, want new1", first["new_slide_id"])
}
}
func TestReplacePagesDryRunPlansOnly(t *testing.T) {
t.Parallel()
f, stdout, _, _ := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
pages := `[{"slide_id":"old2","content":"<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data></data></slide>"}]`
err := runSlidesShortcut(t, f, stdout, SlidesReplacePages, []string{
"+replace-pages",
"--presentation", "pres_abc",
"--pages", pages,
"--dry-run",
"--as", "user",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var out map[string]interface{}
if err := json.Unmarshal(stdout.Bytes(), &out); err != nil {
t.Fatalf("decode dry-run: %v\nraw=%s", err, stdout.String())
}
if out["xml_presentation_id"] != "pres_abc" {
t.Fatalf("xml_presentation_id = %v", out["xml_presentation_id"])
}
plan, _ := out["plan"].([]interface{})
if len(plan) != 1 {
t.Fatalf("plan len = %d, want 1", len(plan))
}
item, _ := plan[0].(map[string]interface{})
if item["old_slide_id"] != "old2" || item["action"] != "create_before_then_delete_old" {
t.Fatalf("plan item = %#v", item)
}
api, _ := out["api"].([]interface{})
if len(api) != 2 {
t.Fatalf("api len = %d, want create/delete plan", len(api))
}
}
func TestReplacePagesValidationParam(t *testing.T) {
t.Parallel()
tests := []struct {
name string
pages string
}{
{"empty pages", `[]`},
{"slide number no longer supported", `[{"slide_number":1,"content":"<slide/>"}]`},
{"no locator", `[{"content":"<slide/>"}]`},
{"empty content", `[{"slide_id":"s1","content":" "}]`},
{"not slide XML", `[{"slide_id":"s1","content":"<shape/>"}]`},
{"duplicate id", `[{"slide_id":"s1","content":"<slide/>"},{"slide_id":"s1","content":"<slide/>"}]`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
f, stdout, _, _ := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
err := runSlidesShortcut(t, f, stdout, SlidesReplacePages, []string{
"+replace-pages",
"--presentation", "pres_abc",
"--pages", tt.pages,
"--as", "user",
})
var ve *errs.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("err = %v, want *errs.ValidationError", err)
}
if ve.Param != "--pages" {
t.Fatalf("Param = %q, want --pages", ve.Param)
}
})
}
}
type replacePagesEnvelope struct {
OK bool `json:"ok"`
Data map[string]interface{} `json:"data"`
}
func decodeReplacePagesEnvelope(t *testing.T, stdout interface{ Bytes() []byte }) replacePagesEnvelope {
t.Helper()
var env replacePagesEnvelope
if err := json.Unmarshal(stdout.Bytes(), &env); err != nil {
t.Fatalf("decode output: %v\nraw=%s", err, string(stdout.Bytes()))
}
if env.Data == nil {
t.Fatalf("missing data: %#v", env)
}
return env
}

View File

@@ -34,8 +34,7 @@ var SlidesScreenshot = common.Shortcut{
Command: "+screenshot", Command: "+screenshot",
Description: "Save slide screenshots to local files without printing Base64 image data", Description: "Save slide screenshots to local files without printing Base64 image data",
Risk: "read", Risk: "read",
// The screenshot API is allowlist-gated for only a few apps, so do not Scopes: []string{"slides:presentation:screenshot"},
// advertise/preflight its scope. Let the API fail and let callers degrade.
// wiki:node:read is required only when --presentation is a wiki URL. // wiki:node:read is required only when --presentation is a wiki URL.
ConditionalScopes: []string{"wiki:node:read"}, ConditionalScopes: []string{"wiki:node:read"},
AuthTypes: []string{"user", "bot"}, AuthTypes: []string{"user", "bot"},

View File

@@ -17,23 +17,11 @@ import (
) )
func TestSlidesScreenshotDeclaredScopes(t *testing.T) { func TestSlidesScreenshotDeclaredScopes(t *testing.T) {
if got := SlidesScreenshot.ScopesForIdentity("user"); len(got) != 0 {
t.Fatalf("user preflight scopes = %#v, want empty", got)
}
if got := SlidesScreenshot.ScopesForIdentity("bot"); len(got) != 0 {
t.Fatalf("bot preflight scopes = %#v, want empty", got)
}
got := SlidesScreenshot.DeclaredScopesForIdentity("user") got := SlidesScreenshot.DeclaredScopesForIdentity("user")
want := []string{"wiki:node:read"} want := []string{"slides:presentation:screenshot", "wiki:node:read"}
if len(got) != len(want) || got[0] != want[0] { if len(got) != len(want) || got[0] != want[0] || got[1] != want[1] {
t.Fatalf("declared scopes = %#v, want %#v", got, want) t.Fatalf("declared scopes = %#v, want %#v", got, want)
} }
for _, scope := range got {
if scope == "slides:presentation:screenshot" {
t.Fatalf("declared scopes must not advertise screenshot scope: %#v", got)
}
}
} }
func TestSlidesScreenshotWritesFilesAndSuppressesBase64(t *testing.T) { func TestSlidesScreenshotWritesFilesAndSuppressesBase64(t *testing.T) {

View File

@@ -1,147 +0,0 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package slides
import (
"bytes"
"context"
"fmt"
"strings"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/validate"
"github.com/larksuite/cli/shortcuts/common"
)
// SlidesXMLGet fetches the full XML presentation content and writes it to a
// local file, keeping the terminal output small for large decks.
var SlidesXMLGet = common.Shortcut{
Service: "slides",
Command: "+xml-get",
Description: "Fetch full presentation XML and save it to a local file",
Risk: "read",
Scopes: []string{"slides:presentation:read"},
// wiki:node:read is required only when --presentation is a wiki URL.
ConditionalScopes: []string{"wiki:node:read"},
AuthTypes: []string{"user", "bot"},
Flags: []common.Flag{
{Name: "presentation", Desc: "xml_presentation_id, slides URL, or wiki URL that resolves to slides", Required: true},
{Name: "output", Desc: "local XML output path; existing file is overwritten", Required: true},
{Name: "revision-id", Type: "int", Default: "-1", Desc: "presentation revision_id; -1 means latest"},
{Name: "remove-attr-id", Type: "bool", Desc: "remove XML id attributes in the returned content; useful for read-only inspection, not precise block editing"},
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
ref, err := parsePresentationRef(runtime.Str("presentation"))
if err != nil {
return err
}
if ref.Kind == "wiki" {
if err := runtime.EnsureScopes([]string{"wiki:node:read"}); err != nil {
return err
}
}
if strings.TrimSpace(runtime.Str("output")) == "" {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output cannot be empty").WithParam("--output")
}
if _, err := runtime.ResolveSavePath(runtime.Str("output")); err != nil {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output invalid: %v", err).WithParam("--output").WithCause(err)
}
if runtime.Int("revision-id") < -1 {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--revision-id must be -1 or a non-negative integer").WithParam("--revision-id")
}
return nil
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
ref, err := parsePresentationRef(runtime.Str("presentation"))
if err != nil {
return common.NewDryRunAPI().Set("error", err.Error())
}
presentationID := ref.Token
dry := common.NewDryRunAPI()
if ref.Kind == "wiki" {
presentationID = "<resolved_slides_token>"
dry.Desc("2-step orchestration: resolve wiki → fetch full presentation XML").
GET("/open-apis/wiki/v2/spaces/get_node").
Desc("[1] Resolve wiki node to slides presentation").
Params(map[string]interface{}{"token": ref.Token})
} else {
dry.Desc("Fetch full presentation XML and save it to a local file")
}
params := map[string]interface{}{
"revision_id": runtime.Int("revision-id"),
}
if runtime.Bool("remove-attr-id") {
params["remove_attr_id"] = true
}
dry.GET(fmt.Sprintf(
"/open-apis/slides_ai/v1/xml_presentations/%s",
validate.EncodePathSegment(presentationID),
)).
Params(params)
return dry.Set("output", runtime.Str("output")).Set("stdout_content", "suppressed; XML content is saved to --output during execution")
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
ref, err := parsePresentationRef(runtime.Str("presentation"))
if err != nil {
return err
}
presentationID, err := resolvePresentationID(runtime, ref)
if err != nil {
return err
}
params := map[string]interface{}{
"revision_id": runtime.Int("revision-id"),
}
if runtime.Bool("remove-attr-id") {
params["remove_attr_id"] = true
}
data, err := runtime.CallAPITyped(
"GET",
fmt.Sprintf("/open-apis/slides_ai/v1/xml_presentations/%s", validate.EncodePathSegment(presentationID)),
params,
nil,
)
if err != nil {
return err
}
presentation := common.GetMap(data, "xml_presentation")
content := common.GetString(presentation, "content")
if content == "" {
return errs.NewInternalError(errs.SubtypeInvalidResponse, "slides xml get returned empty xml_presentation.content")
}
outputPath := runtime.Str("output")
result, err := runtime.FileIO().Save(outputPath, fileio.SaveOptions{
ContentType: "application/xml",
ContentLength: int64(len(content)),
}, bytes.NewReader([]byte(content)))
if err != nil {
return common.WrapSaveErrorTyped(err)
}
resolvedPath, err := runtime.ResolveSavePath(outputPath)
if err != nil {
return errs.NewInternalError(errs.SubtypeFileIO, "resolve saved XML path %s: %v", outputPath, err).WithCause(err)
}
out := map[string]interface{}{
"xml_presentation_id": presentationID,
"path": resolvedPath,
"size": result.Size(),
"content_saved": true,
}
if revisionID := common.GetFloat(presentation, "revision_id"); revisionID > 0 {
out["revision_id"] = int(revisionID)
}
if url := common.GetString(presentation, "url"); url != "" {
out["url"] = url
}
if runtime.Bool("remove-attr-id") {
out["remove_attr_id"] = true
}
runtime.Out(out, nil)
return nil
},
}

View File

@@ -1,161 +0,0 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package slides
import (
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/internal/httpmock"
)
func TestSlidesXMLGetWritesContentToFileAndSuppressesXML(t *testing.T) {
dir := t.TempDir()
withSlidesTestWorkingDir(t, dir)
xml := `<presentation><slide id="s1"><shape id="a">hello</shape></slide></presentation>`
var capturedQuery url.Values
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
reg.Register(&httpmock.Stub{
Method: "GET",
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_abc",
Body: map[string]interface{}{
"code": 0,
"data": map[string]interface{}{
"xml_presentation": map[string]interface{}{
"presentation_id": "pres_abc",
"revision_id": 7,
"url": "https://example.feishu.cn/slides/pres_abc",
"content": xml,
},
},
},
OnMatch: func(req *http.Request) {
capturedQuery = req.URL.Query()
},
})
err := runSlidesShortcut(t, f, stdout, SlidesXMLGet, []string{
"+xml-get",
"--presentation", "pres_abc",
"--output", "readback.xml",
"--revision-id", "7",
"--remove-attr-id",
"--as", "user",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
path := filepath.Join(dir, "readback.xml")
got, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read saved XML: %v", err)
}
if string(got) != xml {
t.Fatalf("saved XML = %q, want %q", got, xml)
}
if strings.Contains(stdout.String(), xml) {
t.Fatalf("stdout leaked full XML content: %s", stdout.String())
}
if got := capturedQuery.Get("revision_id"); got != "7" {
t.Fatalf("revision_id query = %q, want 7", got)
}
if got := capturedQuery.Get("remove_attr_id"); got != "true" {
t.Fatalf("remove_attr_id query = %q, want true", got)
}
data := decodeShortcutData(t, stdout)
if data["xml_presentation_id"] != "pres_abc" {
t.Fatalf("xml_presentation_id = %v, want pres_abc", data["xml_presentation_id"])
}
if data["revision_id"] != float64(7) {
t.Fatalf("revision_id = %v, want 7", data["revision_id"])
}
if data["url"] != "https://example.feishu.cn/slides/pres_abc" {
t.Fatalf("url = %v, want presentation URL", data["url"])
}
if data["size"] != float64(len(xml)) {
t.Fatalf("size = %v, want %d", data["size"], len(xml))
}
gotPath, _ := data["path"].(string)
if !filepath.IsAbs(gotPath) {
t.Fatalf("path = %v, want absolute path", gotPath)
}
if !strings.HasSuffix(gotPath, "readback.xml") {
t.Fatalf("path = %v, want readback.xml suffix", gotPath)
}
}
func TestSlidesXMLGetResolvesWikiPresentation(t *testing.T) {
dir := t.TempDir()
withSlidesTestWorkingDir(t, dir)
f, stdout, _, reg := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
reg.Register(&httpmock.Stub{
Method: "GET",
URL: "/open-apis/wiki/v2/spaces/get_node",
Body: map[string]interface{}{
"code": 0,
"data": map[string]interface{}{
"node": map[string]interface{}{
"obj_type": "slides",
"obj_token": "pres_real",
},
},
},
})
reg.Register(&httpmock.Stub{
Method: "GET",
URL: "/open-apis/slides_ai/v1/xml_presentations/pres_real",
Body: map[string]interface{}{
"code": 0,
"data": map[string]interface{}{
"xml_presentation": map[string]interface{}{
"content": `<presentation/>`,
},
},
},
})
err := runSlidesShortcut(t, f, stdout, SlidesXMLGet, []string{
"+xml-get",
"--presentation", "https://example.feishu.cn/wiki/wikcn123",
"--output", "wiki.xml",
"--as", "user",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
data := decodeShortcutData(t, stdout)
if data["xml_presentation_id"] != "pres_real" {
t.Fatalf("xml_presentation_id = %v, want pres_real", data["xml_presentation_id"])
}
}
func TestSlidesXMLGetRejectsUnsafeOutputPath(t *testing.T) {
f, stdout, _, _ := cmdutil.TestFactory(t, slidesTestConfig(t, ""))
err := runSlidesShortcut(t, f, stdout, SlidesXMLGet, []string{
"+xml-get",
"--presentation", "pres_abc",
"--output", "../readback.xml",
"--as", "user",
})
if err == nil {
t.Fatal("expected unsafe output path error, got nil")
}
problem, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("expected typed error, got %T %v", err, err)
}
if problem.Param != "--output" {
t.Fatalf("param = %q, want --output", problem.Param)
}
}

View File

@@ -242,7 +242,6 @@ func Shortcuts() []common.Shortcut {
GetMyTasks, GetMyTasks,
GetRelatedTasks, GetRelatedTasks,
SearchTask, SearchTask,
SubscribeTaskEvent,
UploadAttachmentTask, UploadAttachmentTask,
CreateTasklist, CreateTasklist,
SearchTasklist, SearchTasklist,

View File

@@ -1,40 +0,0 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package task
import (
"context"
"fmt"
"io"
"net/http"
"github.com/larksuite/cli/shortcuts/common"
)
var SubscribeTaskEvent = common.Shortcut{
Service: "task",
Command: "+subscribe-event",
Description: "subscribe to task events",
Risk: "write",
Scopes: []string{"task:task:read"},
AuthTypes: []string{"user", "bot"},
HasFormat: true,
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
return common.NewDryRunAPI().
POST("/open-apis/task/v2/task_v2/task_subscription").
Params(map[string]interface{}{"user_id_type": "open_id"})
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
params := map[string]interface{}{"user_id_type": "open_id"}
if _, err := callTaskAPITyped(runtime, http.MethodPost, "/open-apis/task/v2/task_v2/task_subscription", params, nil); err != nil {
return err
}
outData := map[string]interface{}{"ok": true}
runtime.OutFormat(outData, nil, func(w io.Writer) {
fmt.Fprintln(w, "✅ Task event subscription created successfully!")
})
return nil
},
}

View File

@@ -1,163 +0,0 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package task
import (
"errors"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/httpmock"
"github.com/larksuite/cli/internal/output"
"github.com/larksuite/cli/shortcuts/common"
)
func TestSubscribeTaskEvent(t *testing.T) {
tests := []struct {
name string
mode string
args []string
register func(*httpmock.Registry)
wantErr bool
wantParts []string
}{
{
name: "execute json (user identity)",
mode: "execute",
args: []string{"+subscribe-event", "--as", "user", "--format", "json"},
register: func(reg *httpmock.Registry) {
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/task/v2/task_v2/task_subscription",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{},
},
})
},
wantParts: []string{`"ok": true`},
},
{
name: "execute json (bot identity)",
mode: "execute",
args: []string{"+subscribe-event", "--as", "bot", "--format", "json"},
register: func(reg *httpmock.Registry) {
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/task/v2/task_v2/task_subscription",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{},
},
})
},
wantParts: []string{`"ok": true`},
},
{
name: "execute api error",
mode: "execute",
args: []string{"+subscribe-event", "--as", "bot", "--format", "json"},
register: func(reg *httpmock.Registry) {
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/task/v2/task_v2/task_subscription",
Body: map[string]interface{}{
"code": 401,
"msg": "Unauthorized",
"error": map[string]interface{}{
"log_id": "test-log-id",
},
},
})
},
wantErr: true,
wantParts: []string{"Unauthorized"},
},
{
name: "dry run",
mode: "dryrun",
wantParts: []string{"POST /open-apis/task/v2/task_v2/task_subscription"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
switch tt.mode {
case "execute":
f, stdout, _, reg := taskShortcutTestFactory(t)
warmTenantToken(t, f, reg)
if tt.register != nil {
tt.register(reg)
}
err := runMountedTaskShortcut(t, SubscribeTaskEvent, tt.args, f, stdout)
if tt.wantErr {
if err == nil {
t.Fatal("expected error, got nil")
}
out := err.Error()
for _, want := range tt.wantParts {
if !strings.Contains(out, want) {
t.Fatalf("error missing %q: %s", want, out)
}
}
return
}
if err != nil {
t.Fatalf("runMountedTaskShortcut() error = %v", err)
}
out := stdout.String()
outNorm := strings.ReplaceAll(out, `":"`, `": "`)
for _, want := range tt.wantParts {
if !strings.Contains(out, want) && !strings.Contains(outNorm, want) {
t.Fatalf("output missing %q: %s", want, out)
}
}
case "dryrun":
runtime := common.TestNewRuntimeContextWithIdentity(&cobra.Command{Use: "test"}, taskTestConfig(t), "user")
out := SubscribeTaskEvent.DryRun(nil, runtime).Format()
for _, want := range tt.wantParts {
if !strings.Contains(out, want) {
t.Fatalf("dry run output missing %q: %s", want, out)
}
}
}
})
}
}
// TestSubscribeTaskEvent_MalformedResponse covers the parse-response arm: a 200
// with an unparseable body surfaces a typed internal invalid_response error
// (exit 5).
func TestSubscribeTaskEvent_MalformedResponse(t *testing.T) {
f, stdout, _, reg := taskShortcutTestFactory(t)
warmTenantToken(t, f, reg)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/task/v2/task_v2/task_subscription",
Status: 200,
RawBody: []byte("{not-json"),
})
args := []string{"+subscribe-event", "--as", "bot", "--format", "json"}
err := runMountedTaskShortcut(t, SubscribeTaskEvent, args, f, stdout)
var ie *errs.InternalError
if !errors.As(err, &ie) {
t.Fatalf("err = %T, want *errs.InternalError; err = %v", err, err)
}
if ie.Subtype != errs.SubtypeInvalidResponse {
t.Errorf("subtype = %q, want %q", ie.Subtype, errs.SubtypeInvalidResponse)
}
if got := output.ExitCodeOf(err); got != output.ExitInternal {
t.Errorf("exit code = %d, want %d", got, output.ExitInternal)
}
}

View File

@@ -5,6 +5,7 @@ package whiteboard
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@@ -21,40 +22,54 @@ import (
) )
const ( const (
// WhiteboardQueryAsImage exports a whiteboard preview image.
WhiteboardQueryAsImage = "image" WhiteboardQueryAsImage = "image"
WhiteboardQueryAsCode = "code" // WhiteboardQueryAsSvg exports a whiteboard as SVG.
WhiteboardQueryAsRaw = "raw" WhiteboardQueryAsSvg = "svg"
// WhiteboardQueryAsCode exports Mermaid or PlantUML source extracted from the whiteboard.
WhiteboardQueryAsCode = "code"
// WhiteboardQueryAsRaw exports the raw whiteboard node payload.
WhiteboardQueryAsRaw = "raw"
) )
// SyntaxType identifies the diagram syntax extracted from whiteboard code blocks.
type SyntaxType int type SyntaxType int
const ( const (
// SyntaxTypePlantUML marks PlantUML code blocks.
SyntaxTypePlantUML SyntaxType = 1 SyntaxTypePlantUML SyntaxType = 1
SyntaxTypeMermaid SyntaxType = 2 // SyntaxTypeMermaid marks Mermaid code blocks.
SyntaxTypeMermaid SyntaxType = 2
) )
// SyntaxTypeNameMap maps whiteboard syntax types to their CLI output names.
var SyntaxTypeNameMap = map[SyntaxType]string{ var SyntaxTypeNameMap = map[SyntaxType]string{
SyntaxTypePlantUML: "plantuml", SyntaxTypePlantUML: "plantuml",
SyntaxTypeMermaid: "mermaid", SyntaxTypeMermaid: "mermaid",
} }
// SyntaxTypeExtensionMap maps whiteboard syntax types to their default file extensions.
var SyntaxTypeExtensionMap = map[SyntaxType]string{ var SyntaxTypeExtensionMap = map[SyntaxType]string{
SyntaxTypePlantUML: ".puml", SyntaxTypePlantUML: ".puml",
SyntaxTypeMermaid: ".mmd", SyntaxTypeMermaid: ".mmd",
} }
// String returns the CLI-facing name for the syntax type.
func (s SyntaxType) String() string { func (s SyntaxType) String() string {
return SyntaxTypeNameMap[s] return SyntaxTypeNameMap[s]
} }
// ExtensionName returns the default file extension for the syntax type.
func (s SyntaxType) ExtensionName() string { func (s SyntaxType) ExtensionName() string {
return SyntaxTypeExtensionMap[s] return SyntaxTypeExtensionMap[s]
} }
// IsValid reports whether the syntax type is one of the supported whiteboard code syntaxes.
func (s SyntaxType) IsValid() bool { func (s SyntaxType) IsValid() bool {
return s == SyntaxTypePlantUML || s == SyntaxTypeMermaid return s == SyntaxTypePlantUML || s == SyntaxTypeMermaid
} }
// WhiteboardQuery registers the `whiteboard +query` shortcut.
var WhiteboardQuery = common.Shortcut{ var WhiteboardQuery = common.Shortcut{
Service: "whiteboard", Service: "whiteboard",
Command: "+query", Command: "+query",
@@ -64,8 +79,8 @@ var WhiteboardQuery = common.Shortcut{
AuthTypes: []string{"user", "bot"}, AuthTypes: []string{"user", "bot"},
Flags: []common.Flag{ Flags: []common.Flag{
{Name: "whiteboard-token", Desc: "whiteboard token of the whiteboard. You will need read permission to download preview image.", Required: true}, {Name: "whiteboard-token", Desc: "whiteboard token of the whiteboard. You will need read permission to download preview image.", Required: true},
{Name: "output_as", Desc: "output whiteboard as: image | code | raw.", Required: true}, {Name: "output_as", Desc: "output whiteboard as: image | svg | code | raw.", Required: true},
{Name: "output", Desc: "output directory. It is required when output as image. If not specified when --output_as code/raw, it will output directly.", Required: false}, {Name: "output", Desc: "output directory. It is required when output as image. If not specified when --output_as svg/code/raw, it will output directly.", Required: false},
{Name: "overwrite", Desc: "overwrite existing file if it exists", Required: false, Type: "bool"}, {Name: "overwrite", Desc: "overwrite existing file if it exists", Required: false, Type: "bool"},
}, },
HasFormat: true, HasFormat: true,
@@ -86,8 +101,8 @@ var WhiteboardQuery = common.Shortcut{
} }
as := runtime.Str("output_as") as := runtime.Str("output_as")
if as != WhiteboardQueryAsImage && as != WhiteboardQueryAsCode && as != WhiteboardQueryAsRaw { if as != WhiteboardQueryAsImage && as != WhiteboardQueryAsSvg && as != WhiteboardQueryAsCode && as != WhiteboardQueryAsRaw {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output_as flag must be one of: image | code | raw").WithParam("--output_as") return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output_as flag must be one of: image | svg | code | raw").WithParam("--output_as")
} }
return nil return nil
}, },
@@ -107,8 +122,13 @@ var WhiteboardQuery = common.Shortcut{
return common.NewDryRunAPI(). return common.NewDryRunAPI().
GET(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/nodes", common.MaskToken(url.PathEscape(token)))). GET(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/nodes", common.MaskToken(url.PathEscape(token)))).
Desc("Extract raw nodes structure from given whiteboard") Desc("Extract raw nodes structure from given whiteboard")
case WhiteboardQueryAsSvg:
return common.NewDryRunAPI().
POST(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/export", common.MaskToken(url.PathEscape(token)))).
Body(map[string]string{"export_type": "svg"}).
Desc("Export SVG of given whiteboard")
default: default:
return common.NewDryRunAPI().Desc("invalid --output_as flag, must be one of: image | code | raw") return common.NewDryRunAPI().Desc("invalid --output_as flag, must be one of: image | svg | code | raw")
} }
}, },
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error { Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
@@ -119,17 +139,110 @@ var WhiteboardQuery = common.Shortcut{
switch as { switch as {
case WhiteboardQueryAsImage: case WhiteboardQueryAsImage:
return exportWhiteboardPreview(ctx, runtime, token, outDir) return exportWhiteboardPreview(ctx, runtime, token, outDir)
case WhiteboardQueryAsSvg:
return exportWhiteboardSvg(runtime, token, outDir)
case WhiteboardQueryAsCode: case WhiteboardQueryAsCode:
return exportWhiteboardCode(runtime, token, outDir) return exportWhiteboardCode(runtime, token, outDir)
case WhiteboardQueryAsRaw: case WhiteboardQueryAsRaw:
return exportWhiteboardRaw(runtime, token, outDir) return exportWhiteboardRaw(runtime, token, outDir)
default: default:
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output_as flag must be one of: image | code | raw").WithParam("--output_as") return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output_as flag must be one of: image | svg | code | raw").WithParam("--output_as")
} }
}, },
} }
// exportReq defines the request body for whiteboard export APIs.
type exportReq struct {
ExportType string `json:"export_type"`
}
// exportResp models the whiteboard export response envelope.
type exportResp struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data struct {
Content string `json:"content"`
MimeType string `json:"mime_type"`
} `json:"data"`
}
// exportWhiteboardSvg exports a whiteboard as SVG and writes the result to stdout or a file.
// It requests the SVG export for the given whiteboard token and saves the decoded content when an output path is provided.
func exportWhiteboardSvg(runtime *common.RuntimeContext, wbToken, outDir string) error {
reqBody := exportReq{ExportType: "svg"}
req := &larkcore.ApiReq{
HttpMethod: http.MethodPost,
ApiPath: fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/export", url.PathEscape(wbToken)),
Body: reqBody,
}
resp, err := runtime.DoAPI(req)
if err != nil {
return wrapWbNetworkErr(err, "export whiteboard svg failed: %v", err)
}
var exportData exportResp
if err := json.Unmarshal(resp.RawBody, &exportData); err == nil {
if exportData.Code != 0 {
subtype := errs.SubtypeUnknown
if resp.StatusCode == http.StatusNotFound {
subtype = errs.SubtypeNotFound
}
return errs.NewAPIError(subtype, "export whiteboard svg failed: %s", exportData.Msg).WithCode(exportData.Code)
}
} else if resp.StatusCode == http.StatusOK {
return errs.NewInternalError(errs.SubtypeInvalidResponse, "parse export response failed: %v", err).WithCause(err)
}
if resp.StatusCode != http.StatusOK {
body := common.TruncateStr(strings.TrimSpace(string(resp.RawBody)), 500)
if resp.StatusCode >= 500 {
return errs.NewNetworkError(errs.SubtypeNetworkServer, "export whiteboard svg failed: HTTP %d: %s", resp.StatusCode, body).
WithCode(resp.StatusCode).
WithRetryable()
}
subtype := errs.SubtypeUnknown
if resp.StatusCode == http.StatusNotFound {
subtype = errs.SubtypeNotFound
}
return errs.NewAPIError(subtype, "export whiteboard svg failed: HTTP %d: %s", resp.StatusCode, body).
WithCode(resp.StatusCode)
}
svgBytes, err := base64.StdEncoding.DecodeString(exportData.Data.Content)
if err != nil {
return errs.NewInternalError(errs.SubtypeInvalidResponse, "decode svg base64 failed: %v", err).WithCause(err)
}
if outDir == "" {
runtime.OutFormat(map[string]interface{}{
"svg_content": string(svgBytes),
}, nil, func(w io.Writer) {
fmt.Fprintf(w, "%s\n", string(svgBytes))
})
return nil
}
finalPath, size, err := saveOutputFile(outDir, ".svg", wbToken, runtime, bytes.NewReader(svgBytes))
if err != nil {
return err
}
runtime.OutFormat(map[string]interface{}{
"svg_path": finalPath,
"size_bytes": size,
}, nil, func(w io.Writer) {
fmt.Fprintf(w, "SVG saved to %s\n", finalPath)
fmt.Fprintf(w, "File size: %d bytes", size)
})
return nil
}
// exportWhiteboardPreview downloads a whiteboard preview image and saves it as a PNG file.
//
// It reports the saved file path and image size on success.
// Returns an error if the API request fails, the response is rejected, or the file cannot be saved.
func exportWhiteboardPreview(ctx context.Context, runtime *common.RuntimeContext, wbToken, outDir string) error { func exportWhiteboardPreview(ctx context.Context, runtime *common.RuntimeContext, wbToken, outDir string) error {
req := &larkcore.ApiReq{ req := &larkcore.ApiReq{
HttpMethod: http.MethodGet, HttpMethod: http.MethodGet,
@@ -331,6 +444,9 @@ func exportWhiteboardRaw(runtime *common.RuntimeContext, wbToken, outDir string)
return nil return nil
} }
// saveOutputFile writes exported content to a file or directory and returns the final path and written size.
// If outPath is a directory, it creates a file named whiteboard_<token><ext>. If outPath is a file path,
// it adjusts the file extension to ext, validates the path, and respects the overwrite flag.
func saveOutputFile(outPath, ext, token string, runtime *common.RuntimeContext, data io.Reader) (string, int64, error) { func saveOutputFile(outPath, ext, token string, runtime *common.RuntimeContext, data io.Reader) (string, int64, error) {
// Step 1: Get final output path // Step 1: Get final output path
info, err := runtime.FileIO().Stat(outPath) info, err := runtime.FileIO().Stat(outPath)
@@ -367,6 +483,8 @@ func saveOutputFile(outPath, ext, token string, runtime *common.RuntimeContext,
switch ext { switch ext {
case ".png": case ".png":
contentType = "image/png" contentType = "image/png"
case ".svg":
contentType = "image/svg+xml"
case ".json": case ".json":
contentType = "application/json" contentType = "application/json"
case ".mmd", ".puml": case ".mmd", ".puml":

View File

@@ -6,6 +6,8 @@ package whiteboard
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/base64"
"encoding/json"
"errors" "errors"
"os" "os"
"path/filepath" "path/filepath"
@@ -13,6 +15,7 @@ import (
"testing" "testing"
"github.com/larksuite/cli/errs" "github.com/larksuite/cli/errs"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/cmdutil" "github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/internal/core" "github.com/larksuite/cli/internal/core"
"github.com/larksuite/cli/internal/httpmock" "github.com/larksuite/cli/internal/httpmock"
@@ -20,6 +23,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
// TestSyntaxType verifies syntax names, extensions, and validity checks.
func TestSyntaxType(t *testing.T) { func TestSyntaxType(t *testing.T) {
t.Parallel() t.Parallel()
@@ -75,6 +79,7 @@ func TestSyntaxType(t *testing.T) {
} }
} }
// TestWhiteboardQuery_Validate verifies query flag validation for supported output modes.
func TestWhiteboardQuery_Validate(t *testing.T) { func TestWhiteboardQuery_Validate(t *testing.T) {
ctx := context.Background() ctx := context.Background()
chdirTemp(t) chdirTemp(t)
@@ -199,6 +204,9 @@ func TestWhiteboardQuery_Validate_TypedErrors(t *testing.T) {
if p.Category != errs.CategoryValidation { if p.Category != errs.CategoryValidation {
t.Errorf("Category = %q, want %q", p.Category, errs.CategoryValidation) t.Errorf("Category = %q, want %q", p.Category, errs.CategoryValidation)
} }
if p.Subtype != errs.SubtypeInvalidArgument {
t.Errorf("Problem subtype = %q, want %q", p.Subtype, errs.SubtypeInvalidArgument)
}
}) })
} }
} }
@@ -232,6 +240,7 @@ func TestExportWhiteboardPreview_HTTPError(t *testing.T) {
} }
} }
// TestExportWhiteboardPreview_HTTPNotFoundIsAPIError verifies 404 preview downloads surface as typed API errors.
func TestExportWhiteboardPreview_HTTPNotFoundIsAPIError(t *testing.T) { func TestExportWhiteboardPreview_HTTPNotFoundIsAPIError(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
chdirTemp(t) chdirTemp(t)
@@ -255,6 +264,7 @@ func TestExportWhiteboardPreview_HTTPNotFoundIsAPIError(t *testing.T) {
} }
} }
// TestWhiteboardQuery_DryRun verifies dry-run output for the supported query modes.
func TestWhiteboardQuery_DryRun(t *testing.T) { func TestWhiteboardQuery_DryRun(t *testing.T) {
t.Parallel() t.Parallel()
@@ -307,6 +317,64 @@ func TestWhiteboardQuery_DryRun(t *testing.T) {
} }
} }
// TestWhiteboardQuery_DryRun_InvalidOutputAs verifies dry-run guidance for unsupported output modes.
func TestWhiteboardQuery_DryRun_InvalidOutputAs(t *testing.T) {
t.Parallel()
ctx := context.Background()
rt := newTestRuntime(map[string]string{
"whiteboard-token": "test-token-123",
"output_as": "invalid",
}, nil)
dryRun := WhiteboardQuery.DryRun(ctx, rt)
if dryRun == nil {
t.Fatal("WhiteboardQuery.DryRun() returned nil")
}
data, err := json.Marshal(dryRun)
if err != nil {
t.Fatalf("Marshal() error = %v", err)
}
if !strings.Contains(string(data), "image | svg | code | raw") {
t.Fatalf("dry run desc = %s, want invalid output_as guidance", string(data))
}
}
// TestWhiteboardQuery_Execute_InvalidOutputAs_TypedError verifies invalid output modes return typed validation errors.
func TestWhiteboardQuery_Execute_InvalidOutputAs_TypedError(t *testing.T) {
rt := newTestRuntime(map[string]string{
"whiteboard-token": "test-token-123",
"output_as": "invalid",
}, nil)
err := WhiteboardQuery.Execute(context.Background(), rt)
if err == nil {
t.Fatal("expected error, got nil")
}
var ve *errs.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("error is not *errs.ValidationError: %T (%v)", err, err)
}
if ve.Subtype != errs.SubtypeInvalidArgument {
t.Errorf("Subtype = %q, want %q", ve.Subtype, errs.SubtypeInvalidArgument)
}
if ve.Param != "--output_as" {
t.Errorf("Param = %q, want %q", ve.Param, "--output_as")
}
p, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("errs.ProblemOf returned false")
}
if p.Category != errs.CategoryValidation {
t.Errorf("Category = %q, want %q", p.Category, errs.CategoryValidation)
}
if p.Subtype != errs.SubtypeInvalidArgument {
t.Errorf("Problem subtype = %q, want %q", p.Subtype, errs.SubtypeInvalidArgument)
}
}
// TestWhiteboardQuery_ShortcutRegistration verifies the whiteboard query shortcut metadata.
func TestWhiteboardQuery_ShortcutRegistration(t *testing.T) { func TestWhiteboardQuery_ShortcutRegistration(t *testing.T) {
t.Parallel() t.Parallel()
@@ -325,6 +393,7 @@ func TestWhiteboardQuery_ShortcutRegistration(t *testing.T) {
} }
} }
// TestSaveOutputFile verifies output saving, overwrite handling, and extension-specific paths.
func TestSaveOutputFile(t *testing.T) { func TestSaveOutputFile(t *testing.T) {
t.Parallel() t.Parallel()
@@ -476,6 +545,7 @@ func TestSaveOutputFile(t *testing.T) {
} }
} }
// TestSaveOutputFile_InvalidFinalPathTypedError verifies invalid save paths return typed validation errors.
func TestSaveOutputFile_InvalidFinalPathTypedError(t *testing.T) { func TestSaveOutputFile_InvalidFinalPathTypedError(t *testing.T) {
chdirTemp(t) chdirTemp(t)
@@ -491,6 +561,19 @@ func TestSaveOutputFile_InvalidFinalPathTypedError(t *testing.T) {
if ve.Subtype != errs.SubtypeInvalidArgument || ve.Param != "--output" { if ve.Subtype != errs.SubtypeInvalidArgument || ve.Param != "--output" {
t.Fatalf("validation details = subtype %q param %q, want %q --output", ve.Subtype, ve.Param, errs.SubtypeInvalidArgument) t.Fatalf("validation details = subtype %q param %q, want %q --output", ve.Subtype, ve.Param, errs.SubtypeInvalidArgument)
} }
p, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("errs.ProblemOf returned false")
}
if p.Category != errs.CategoryValidation {
t.Errorf("Category = %q, want %q", p.Category, errs.CategoryValidation)
}
if p.Subtype != errs.SubtypeInvalidArgument {
t.Errorf("Problem subtype = %q, want %q", p.Subtype, errs.SubtypeInvalidArgument)
}
if !errors.Is(err, fileio.ErrPathValidation) {
t.Fatalf("expected path-validation cause to be preserved, err=%v", err)
}
} }
func newExecuteFactory(t *testing.T) (*cmdutil.Factory, *bytes.Buffer, *httpmock.Registry) { func newExecuteFactory(t *testing.T) (*cmdutil.Factory, *bytes.Buffer, *httpmock.Registry) {
@@ -525,6 +608,7 @@ func runShortcut(t *testing.T, shortcut common.Shortcut, args []string, factory
return err return err
} }
// TestWhiteboardQueryExecute_AsRaw verifies raw query execution emits the raw node payload.
func TestWhiteboardQueryExecute_AsRaw(t *testing.T) { func TestWhiteboardQueryExecute_AsRaw(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
@@ -553,6 +637,7 @@ func TestWhiteboardQueryExecute_AsRaw(t *testing.T) {
} }
} }
// TestWhiteboardQueryExecute_AsCode verifies code query execution emits extracted diagram source.
func TestWhiteboardQueryExecute_AsCode(t *testing.T) { func TestWhiteboardQueryExecute_AsCode(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
chdirTemp(t) chdirTemp(t)
@@ -583,6 +668,7 @@ func TestWhiteboardQueryExecute_AsCode(t *testing.T) {
} }
} }
// TestExportWhiteboardCode_EmptyNodes verifies code export handles empty whiteboards.
func TestExportWhiteboardCode_EmptyNodes(t *testing.T) { func TestExportWhiteboardCode_EmptyNodes(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
@@ -605,6 +691,7 @@ func TestExportWhiteboardCode_EmptyNodes(t *testing.T) {
} }
} }
// TestExportWhiteboardCode_NoCodeBlocks verifies code export reports whiteboards without code blocks.
func TestExportWhiteboardCode_NoCodeBlocks(t *testing.T) { func TestExportWhiteboardCode_NoCodeBlocks(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
@@ -629,6 +716,7 @@ func TestExportWhiteboardCode_NoCodeBlocks(t *testing.T) {
} }
} }
// TestExportWhiteboardCode_InvalidSyntaxType verifies unknown syntax types are rejected.
func TestExportWhiteboardCode_InvalidSyntaxType(t *testing.T) { func TestExportWhiteboardCode_InvalidSyntaxType(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
@@ -658,6 +746,7 @@ func TestExportWhiteboardCode_InvalidSyntaxType(t *testing.T) {
} }
} }
// TestExportWhiteboardCode_MultipleCodeBlocks verifies multiple code blocks are exported together.
func TestExportWhiteboardCode_MultipleCodeBlocks(t *testing.T) { func TestExportWhiteboardCode_MultipleCodeBlocks(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
@@ -697,6 +786,7 @@ func TestExportWhiteboardCode_MultipleCodeBlocks(t *testing.T) {
} }
} }
// TestExportWhiteboardCode_SingleBlock_PlantUML_DirectOutput verifies direct PlantUML output for a single code block.
func TestExportWhiteboardCode_SingleBlock_PlantUML_DirectOutput(t *testing.T) { func TestExportWhiteboardCode_SingleBlock_PlantUML_DirectOutput(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
@@ -730,6 +820,7 @@ func TestExportWhiteboardCode_SingleBlock_PlantUML_DirectOutput(t *testing.T) {
} }
} }
// TestExportWhiteboardCode_SingleBlock_Mermaid_DirectOutput verifies direct Mermaid output for a single code block.
func TestExportWhiteboardCode_SingleBlock_Mermaid_DirectOutput(t *testing.T) { func TestExportWhiteboardCode_SingleBlock_Mermaid_DirectOutput(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
@@ -763,6 +854,7 @@ func TestExportWhiteboardCode_SingleBlock_Mermaid_DirectOutput(t *testing.T) {
} }
} }
// TestExportWhiteboardPreview verifies preview downloads can be written to disk.
func TestExportWhiteboardPreview(t *testing.T) { func TestExportWhiteboardPreview(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
@@ -791,6 +883,7 @@ func TestExportWhiteboardPreview(t *testing.T) {
} }
} }
// TestExportWhiteboardRaw_EmptyNodes verifies raw export reports empty whiteboards.
func TestExportWhiteboardRaw_EmptyNodes(t *testing.T) { func TestExportWhiteboardRaw_EmptyNodes(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
@@ -813,6 +906,7 @@ func TestExportWhiteboardRaw_EmptyNodes(t *testing.T) {
} }
} }
// TestFetchWhiteboardNodes_APIError verifies node fetch failures preserve typed API errors.
func TestFetchWhiteboardNodes_APIError(t *testing.T) { func TestFetchWhiteboardNodes_APIError(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t) factory, stdout, reg := newExecuteFactory(t)
@@ -842,6 +936,7 @@ func TestFetchWhiteboardNodes_APIError(t *testing.T) {
} }
} }
// TestFetchWhiteboardNodes_InvalidResponseTypedError verifies malformed node responses become typed invalid-response errors.
func TestFetchWhiteboardNodes_InvalidResponseTypedError(t *testing.T) { func TestFetchWhiteboardNodes_InvalidResponseTypedError(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
@@ -901,6 +996,474 @@ func TestFetchWhiteboardNodes_MissingNodesIsEmpty(t *testing.T) {
} }
} }
// TestExportWhiteboardSvg_DirectOutput verifies SVG export is printed when no output path is provided.
func TestExportWhiteboardSvg_DirectOutput(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
svgContent := `<svg xmlns="http://www.w3.org/2000/svg"><rect width="100" height="100"/></svg>`
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg/export",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{
"content": base64.StdEncoding.EncodeToString([]byte(svgContent)),
"mime_type": "image/svg+xml",
},
},
})
args := []string{"+query", "--whiteboard-token", "test-token-svg", "--output_as", "svg"}
if err := runShortcut(t, WhiteboardQuery, args, factory, stdout); err != nil {
t.Fatalf("err=%v", err)
}
if !strings.Contains(stdout.String(), "svg_content") {
t.Fatalf("stdout missing svg_content key: %s", stdout.String())
}
}
// TestExportWhiteboardSvg_SaveToFile verifies SVG export is written to the requested file.
func TestExportWhiteboardSvg_SaveToFile(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
chdirTemp(t)
svgContent := `<svg xmlns="http://www.w3.org/2000/svg"><circle cx="50" cy="50" r="40"/></svg>`
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-file/export",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{
"content": base64.StdEncoding.EncodeToString([]byte(svgContent)),
"mime_type": "image/svg+xml",
},
},
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-file", "--output_as", "svg", "--output", "output", "--overwrite"}
if err := runShortcut(t, WhiteboardQuery, args, factory, stdout); err != nil {
t.Fatalf("err=%v", err)
}
data, err := os.ReadFile("output.svg")
if err != nil {
t.Fatalf("ReadFile() error: %v", err)
}
if string(data) != svgContent {
t.Fatalf("svg content = %q, want %q", string(data), svgContent)
}
}
// TestExportWhiteboardSvg_PrettyOutput verifies pretty output includes inline SVG content.
func TestExportWhiteboardSvg_PrettyOutput(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
svgContent := `<svg xmlns="http://www.w3.org/2000/svg"><path d="M0 0L10 10"/></svg>`
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-pretty/export",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{
"content": base64.StdEncoding.EncodeToString([]byte(svgContent)),
"mime_type": "image/svg+xml",
},
},
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-pretty", "--output_as", "svg", "--format", "pretty"}
if err := runShortcut(t, WhiteboardQuery, args, factory, stdout); err != nil {
t.Fatalf("err=%v", err)
}
if got := stdout.String(); !strings.Contains(got, svgContent) {
t.Fatalf("stdout = %q, want svg content", got)
}
}
// TestExportWhiteboardSvg_SaveToFile_PrettyOutput verifies pretty output reports the saved SVG path and size.
func TestExportWhiteboardSvg_SaveToFile_PrettyOutput(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
chdirTemp(t)
svgContent := `<svg xmlns="http://www.w3.org/2000/svg"><ellipse cx="60" cy="40" rx="50" ry="30"/></svg>`
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-file-pretty/export",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{
"content": base64.StdEncoding.EncodeToString([]byte(svgContent)),
"mime_type": "image/svg+xml",
},
},
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-file-pretty", "--output_as", "svg", "--output", "output", "--overwrite", "--format", "pretty"}
if err := runShortcut(t, WhiteboardQuery, args, factory, stdout); err != nil {
t.Fatalf("err=%v", err)
}
if got := stdout.String(); !strings.Contains(got, "SVG saved to output.svg") || !strings.Contains(got, "File size:") {
t.Fatalf("stdout = %q, want save summary", got)
}
}
// TestExportWhiteboardSvg_SaveToFile_ExistingFileWithoutOverwrite verifies existing SVG outputs require --overwrite.
func TestExportWhiteboardSvg_SaveToFile_ExistingFileWithoutOverwrite(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
chdirTemp(t)
if err := os.WriteFile("output.svg", []byte("existing content"), 0644); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
svgContent := `<svg xmlns="http://www.w3.org/2000/svg"><line x1="0" y1="0" x2="1" y2="1"/></svg>`
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-existing/export",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{
"content": base64.StdEncoding.EncodeToString([]byte(svgContent)),
"mime_type": "image/svg+xml",
},
},
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-existing", "--output_as", "svg", "--output", "output"}
err := runShortcut(t, WhiteboardQuery, args, factory, stdout)
if err == nil {
t.Fatal("expected error for existing output without overwrite")
}
var ve *errs.ValidationError
if !errors.As(err, &ve) {
t.Fatalf("error is not *errs.ValidationError: %T (%v)", err, err)
}
if ve.Subtype != errs.SubtypeInvalidArgument {
t.Errorf("Subtype = %q, want %q", ve.Subtype, errs.SubtypeInvalidArgument)
}
if ve.Param != "--overwrite" {
t.Errorf("Param = %q, want %q", ve.Param, "--overwrite")
}
}
// TestExportWhiteboardSvg_HTTP5xx verifies plain HTTP 5xx failures are classified as retryable network errors.
func TestExportWhiteboardSvg_HTTP5xx(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-5xx/export",
Status: 502,
RawBody: []byte("bad gateway"),
ContentType: "text/plain",
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-5xx", "--output_as", "svg"}
err := runShortcut(t, WhiteboardQuery, args, factory, stdout)
if err == nil {
t.Fatal("expected error for HTTP 502")
}
var ne *errs.NetworkError
if !errors.As(err, &ne) {
t.Fatalf("error is not *errs.NetworkError: %T (%v)", err, err)
}
if ne.Subtype != errs.SubtypeNetworkServer {
t.Errorf("Subtype = %q, want %q", ne.Subtype, errs.SubtypeNetworkServer)
}
if ne.Code != 502 {
t.Errorf("Code = %d, want 502", ne.Code)
}
if !ne.Retryable {
t.Error("expected Retryable = true")
}
}
// TestExportWhiteboardSvg_HTTP5xxJSONEnvelopeReturnsAPIError verifies API envelopes take precedence over generic 5xx handling.
func TestExportWhiteboardSvg_HTTP5xxJSONEnvelopeReturnsAPIError(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-5xx-json/export",
Status: 502,
ContentType: "application/json",
RawBody: []byte(`{"code":99002,"msg":"export task failed"}`),
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-5xx-json", "--output_as", "svg"}
err := runShortcut(t, WhiteboardQuery, args, factory, stdout)
if err == nil {
t.Fatal("expected error for HTTP 502 JSON envelope")
}
var apiErr *errs.APIError
if !errors.As(err, &apiErr) {
t.Fatalf("error is not *errs.APIError: %T (%v)", err, err)
}
var ne *errs.NetworkError
if errors.As(err, &ne) {
t.Fatalf("expected JSON envelope to win over HTTP 5xx fallback, got *errs.NetworkError: %v", err)
}
if apiErr.Subtype != errs.SubtypeUnknown {
t.Errorf("Subtype = %q, want %q", apiErr.Subtype, errs.SubtypeUnknown)
}
if apiErr.Code != 99002 {
t.Errorf("Code = %d, want 99002", apiErr.Code)
}
}
// TestExportWhiteboardSvg_HTTP4xx verifies plain HTTP 4xx failures are surfaced as API errors.
func TestExportWhiteboardSvg_HTTP4xx(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-403/export",
Status: 403,
RawBody: []byte("forbidden"),
ContentType: "text/plain",
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-403", "--output_as", "svg"}
err := runShortcut(t, WhiteboardQuery, args, factory, stdout)
if err == nil {
t.Fatal("expected error for HTTP 403")
}
var apiErr *errs.APIError
if !errors.As(err, &apiErr) {
t.Fatalf("error is not *errs.APIError: %T (%v)", err, err)
}
if apiErr.Subtype != errs.SubtypeUnknown {
t.Errorf("Subtype = %q, want %q", apiErr.Subtype, errs.SubtypeUnknown)
}
if apiErr.Code != 403 {
t.Errorf("Code = %d, want 403", apiErr.Code)
}
}
// TestExportWhiteboardSvg_HTTPNotFoundJSONEnvelopeIsAPIError verifies not-found envelopes preserve the typed API error classification.
func TestExportWhiteboardSvg_HTTPNotFoundJSONEnvelopeIsAPIError(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/missing-token-svg/export",
Status: 404,
ContentType: "application/json",
RawBody: []byte(`{"code":99001,"msg":"whiteboard not found"}`),
})
args := []string{"+query", "--whiteboard-token", "missing-token-svg", "--output_as", "svg"}
err := runShortcut(t, WhiteboardQuery, args, factory, stdout)
if err == nil {
t.Fatal("expected error for HTTP 404 JSON envelope")
}
var apiErr *errs.APIError
if !errors.As(err, &apiErr) {
t.Fatalf("error is not *errs.APIError: %T (%v)", err, err)
}
if apiErr.Subtype != errs.SubtypeNotFound {
t.Errorf("Subtype = %q, want %q", apiErr.Subtype, errs.SubtypeNotFound)
}
if apiErr.Code != 99001 {
t.Errorf("Code = %d, want 99001", apiErr.Code)
}
}
// TestExportWhiteboardSvg_HTTPNotFoundPlainText verifies plain-text 404 responses surface as not-found API errors.
func TestExportWhiteboardSvg_HTTPNotFoundPlainText(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/missing-token-svg-plain/export",
Status: 404,
ContentType: "text/plain",
RawBody: []byte("whiteboard not found"),
})
args := []string{"+query", "--whiteboard-token", "missing-token-svg-plain", "--output_as", "svg"}
err := runShortcut(t, WhiteboardQuery, args, factory, stdout)
if err == nil {
t.Fatal("expected error for HTTP 404 plain text response")
}
var apiErr *errs.APIError
if !errors.As(err, &apiErr) {
t.Fatalf("error is not *errs.APIError: %T (%v)", err, err)
}
if apiErr.Subtype != errs.SubtypeNotFound {
t.Errorf("Subtype = %q, want %q", apiErr.Subtype, errs.SubtypeNotFound)
}
if apiErr.Code != 404 {
t.Errorf("Code = %d, want 404", apiErr.Code)
}
}
// TestExportWhiteboardSvg_InvalidJSON verifies malformed success responses are rejected as invalid responses.
func TestExportWhiteboardSvg_InvalidJSON(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-badjson/export",
Status: 200,
RawBody: []byte("not json at all"),
ContentType: "application/json",
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-badjson", "--output_as", "svg"}
err := runShortcut(t, WhiteboardQuery, args, factory, stdout)
if err == nil {
t.Fatal("expected error for invalid JSON")
}
assertInvalidResponse(t, err)
}
// TestExportWhiteboardSvg_InvalidBody200PlainText verifies plain-text 200 responses are rejected as invalid export responses.
func TestExportWhiteboardSvg_InvalidBody200PlainText(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-plain-200/export",
Status: 200,
RawBody: []byte("not json at all"),
ContentType: "text/plain",
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-plain-200", "--output_as", "svg"}
err := runShortcut(t, WhiteboardQuery, args, factory, stdout)
if err == nil {
t.Fatal("expected error for plain text success response")
}
assertInvalidResponse(t, err)
}
// TestExportWhiteboardSvg_NonZeroCode verifies non-zero API codes are returned as typed API errors.
func TestExportWhiteboardSvg_NonZeroCode(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-apierr/export",
Body: map[string]interface{}{
"code": 99001,
"msg": "whiteboard not found",
"data": map[string]interface{}{},
},
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-apierr", "--output_as", "svg"}
err := runShortcut(t, WhiteboardQuery, args, factory, stdout)
if err == nil {
t.Fatal("expected error for non-zero code")
}
var apiErr *errs.APIError
if !errors.As(err, &apiErr) {
t.Fatalf("error is not *errs.APIError: %T (%v)", err, err)
}
if apiErr.Code != 99001 {
t.Errorf("Code = %d, want 99001", apiErr.Code)
}
}
// TestExportWhiteboardSvg_InvalidBase64 verifies invalid SVG payload encoding is rejected.
func TestExportWhiteboardSvg_InvalidBase64(t *testing.T) {
factory, stdout, reg := newExecuteFactory(t)
reg.Register(&httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg-badbase64/export",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{
"content": "!!!not-valid-base64!!!",
"mime_type": "image/svg+xml",
},
},
})
args := []string{"+query", "--whiteboard-token", "test-token-svg-badbase64", "--output_as", "svg"}
err := runShortcut(t, WhiteboardQuery, args, factory, stdout)
if err == nil {
t.Fatal("expected error for invalid base64")
}
assertInvalidResponse(t, err)
}
// TestWhiteboardQuery_Validate_SvgValid verifies svg is accepted as a valid query output format.
func TestWhiteboardQuery_Validate_SvgValid(t *testing.T) {
ctx := context.Background()
chdirTemp(t)
rt := newTestRuntime(map[string]string{
"whiteboard-token": "test-token-123",
"output_as": "svg",
}, nil)
if err := WhiteboardQuery.Validate(ctx, rt); err != nil {
t.Fatalf("expected svg to be valid, got err=%v", err)
}
}
// TestWhiteboardQuery_DryRun_Svg verifies the svg dry-run request uses the export endpoint and body.
func TestWhiteboardQuery_DryRun_Svg(t *testing.T) {
t.Parallel()
ctx := context.Background()
rt := newTestRuntime(map[string]string{
"whiteboard-token": "test-token-123",
"output_as": "svg",
}, nil)
dryRun := WhiteboardQuery.DryRun(ctx, rt)
if dryRun == nil {
t.Fatal("DryRun() returned nil for svg")
}
data, err := json.Marshal(dryRun)
if err != nil {
t.Fatalf("Marshal() error = %v", err)
}
var got struct {
API []struct {
Method string `json:"method"`
URL string `json:"url"`
Params map[string]interface{} `json:"params"`
Body map[string]interface{} `json:"body"`
} `json:"api"`
}
if err := json.Unmarshal(data, &got); err != nil {
t.Fatalf("Unmarshal() error = %v", err)
}
if len(got.API) != 1 {
t.Fatalf("len(api) = %d, want 1", len(got.API))
}
if got.API[0].Method != "POST" {
t.Fatalf("method = %q, want POST", got.API[0].Method)
}
if got.API[0].URL != "/open-apis/board/v1/whiteboards/test...-123/export" {
t.Fatalf("url = %q", got.API[0].URL)
}
if got.API[0].Body["export_type"] != "svg" {
t.Fatalf("body = %#v, want export_type=svg", got.API[0].Body)
}
if _, ok := got.API[0].Params["export_type"]; ok {
t.Fatalf("params should not include export_type, got %#v", got.API[0].Params)
}
}
// assertInvalidResponse verifies an error is classified as a typed invalid-response failure.
func assertInvalidResponse(t *testing.T, err error) { func assertInvalidResponse(t *testing.T, err error) {
t.Helper() t.Helper()
if err == nil { if err == nil {

View File

@@ -17,15 +17,21 @@ import (
) )
const ( const (
FormatRaw = "raw" // FormatRaw sends raw whiteboard node JSON to the create-nodes API.
FormatRaw = "raw"
// FormatPlantUML sends PlantUML source through the diagram import API.
FormatPlantUML = "plantuml" FormatPlantUML = "plantuml"
FormatMermaid = "mermaid" // FormatMermaid sends Mermaid source through the diagram import API.
FormatMermaid = "mermaid"
// FormatSVG sends SVG source through the diagram import API.
FormatSVG = "svg"
) )
var formatCodeMap = map[string]int{ var formatCodeMap = map[string]int{
FormatRaw: 0, FormatRaw: 0,
FormatPlantUML: 1, FormatPlantUML: 1,
FormatMermaid: 2, FormatMermaid: 2,
FormatSVG: 3,
} }
var wbUpdateScopes = []string{"board:whiteboard:node:create"} var wbUpdateScopes = []string{"board:whiteboard:node:create"}
@@ -35,9 +41,14 @@ var wbUpdateFlags = []common.Flag{
{Name: "whiteboard-token", Desc: "whiteboard token of the whiteboard to update. You will need edit permission to update the whiteboard.", Required: true}, {Name: "whiteboard-token", Desc: "whiteboard token of the whiteboard to update. You will need edit permission to update the whiteboard.", Required: true},
{Name: "overwrite", Desc: "overwrite the whiteboard content, delete all existing content before update. Default is false.", Required: false, Type: "bool"}, {Name: "overwrite", Desc: "overwrite the whiteboard content, delete all existing content before update. Default is false.", Required: false, Type: "bool"},
{Name: "source", Desc: "Input whiteboard data.", Required: true, Input: []string{common.Stdin, common.File}}, {Name: "source", Desc: "Input whiteboard data.", Required: true, Input: []string{common.Stdin, common.File}},
{Name: "input_format", Desc: "format of input data: raw | plantuml | mermaid. Default is raw.", Required: false}, {Name: "input_format", Desc: "format of input data: raw | plantuml | mermaid | svg. Default is raw.", Required: false},
} }
// wbUpdateValidate validates the whiteboard update command arguments.
//
// It checks the whiteboard token and idempotent token for dangerous control
// characters, enforces a minimum length for a non-empty idempotent token, and
// ensures the input format is one of raw, plantuml, mermaid, or svg.
func wbUpdateValidate(ctx context.Context, runtime *common.RuntimeContext) error { func wbUpdateValidate(ctx context.Context, runtime *common.RuntimeContext) error {
// 检查 token 是否包含控制字符(空字符串下自动跳过了) // 检查 token 是否包含控制字符(空字符串下自动跳过了)
if err := common.RejectDangerousCharsTyped("--whiteboard-token", runtime.Str("whiteboard-token")); err != nil { if err := common.RejectDangerousCharsTyped("--whiteboard-token", runtime.Str("whiteboard-token")); err != nil {
@@ -53,8 +64,8 @@ func wbUpdateValidate(ctx context.Context, runtime *common.RuntimeContext) error
// 检查 --input_format 标志 // 检查 --input_format 标志
format := getFormat(runtime) format := getFormat(runtime)
if format != FormatRaw && format != FormatPlantUML && format != FormatMermaid { if format != FormatRaw && format != FormatPlantUML && format != FormatMermaid && format != FormatSVG {
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--input_format must be one of: raw | plantuml | mermaid").WithParam("--input_format") return errs.NewValidationError(errs.SubtypeInvalidArgument, "--input_format must be one of: raw | plantuml | mermaid | svg").WithParam("--input_format")
} }
return nil return nil
} }
@@ -68,6 +79,8 @@ func getFormat(runtime *common.RuntimeContext) string {
return format return format
} }
// wbUpdateDryRun describes the HTTP request used to update a whiteboard.
// It returns a failure description when source is missing or cannot be parsed.
func wbUpdateDryRun(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI { func wbUpdateDryRun(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
// 读取输入内容 // 读取输入内容
input := runtime.Str("source") input := runtime.Str("source")
@@ -91,7 +104,7 @@ func wbUpdateDryRun(ctx context.Context, runtime *common.RuntimeContext) *common
Overwrite: overwrite, Overwrite: overwrite,
} }
desc.POST(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/nodes", common.MaskToken(url.PathEscape(token)))).Body(reqBody).Desc("create all nodes of the whiteboard.") desc.POST(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/nodes", common.MaskToken(url.PathEscape(token)))).Body(reqBody).Desc("create all nodes of the whiteboard.")
case FormatPlantUML, FormatMermaid: case FormatPlantUML, FormatMermaid, FormatSVG:
syntaxType := formatCodeMap[format] syntaxType := formatCodeMap[format]
reqBody := plantumlCreateReq{ reqBody := plantumlCreateReq{
PlantUmlCode: input, PlantUmlCode: input,
@@ -106,6 +119,10 @@ func wbUpdateDryRun(ctx context.Context, runtime *common.RuntimeContext) *common
return desc return desc
} }
// wbUpdateExecute updates a whiteboard from the supplied source input.
// It requires --source and dispatches to the raw node update path for raw input
// or the diagram import path for PlantUML, Mermaid, and SVG input.
// It returns an error if the source is missing or the input format is unsupported.
func wbUpdateExecute(ctx context.Context, runtime *common.RuntimeContext) error { func wbUpdateExecute(ctx context.Context, runtime *common.RuntimeContext) error {
token := runtime.Str("whiteboard-token") token := runtime.Str("whiteboard-token")
overwrite := runtime.Bool("overwrite") overwrite := runtime.Bool("overwrite")
@@ -120,15 +137,17 @@ func wbUpdateExecute(ctx context.Context, runtime *common.RuntimeContext) error
switch format { switch format {
case FormatRaw: case FormatRaw:
return updateWhiteboardByRawNodes(ctx, runtime, token, []byte(input), overwrite, idempotentToken) return updateWhiteboardByRawNodes(ctx, runtime, token, []byte(input), overwrite, idempotentToken)
case FormatPlantUML, FormatMermaid: case FormatPlantUML, FormatMermaid, FormatSVG:
return updateWhiteboardByCode(ctx, runtime, token, []byte(input), format, overwrite, idempotentToken) return updateWhiteboardByCode(ctx, runtime, token, []byte(input), format, overwrite, idempotentToken)
default: default:
return errs.NewValidationError(errs.SubtypeInvalidArgument, "unsupported format: %s", format).WithParam("--input_format") return errs.NewValidationError(errs.SubtypeInvalidArgument, "unsupported format: %s", format).WithParam("--input_format")
} }
} }
// WhiteboardUpdateDescription describes the whiteboard update shortcut.
const WhiteboardUpdateDescription = "Update an existing whiteboard in lark document with mermaid, plantuml or whiteboard dsl. refer to lark-whiteboard skill for more details." const WhiteboardUpdateDescription = "Update an existing whiteboard in lark document with mermaid, plantuml or whiteboard dsl. refer to lark-whiteboard skill for more details."
// WhiteboardUpdate registers the `whiteboard +update` shortcut.
var WhiteboardUpdate = common.Shortcut{ var WhiteboardUpdate = common.Shortcut{
Service: "whiteboard", Service: "whiteboard",
Command: "+update", Command: "+update",

View File

@@ -6,6 +6,7 @@ package whiteboard
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/json"
"errors" "errors"
"strings" "strings"
"testing" "testing"
@@ -18,6 +19,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
// TestWhiteboardUpdate_Validate verifies update flag validation for supported input formats.
func TestWhiteboardUpdate_Validate(t *testing.T) { func TestWhiteboardUpdate_Validate(t *testing.T) {
ctx := context.Background() ctx := context.Background()
@@ -53,6 +55,15 @@ func TestWhiteboardUpdate_Validate(t *testing.T) {
}, },
wantErr: false, wantErr: false,
}, },
{
name: "valid: svg format",
flags: map[string]string{
"whiteboard-token": "test-token-123",
"input_format": "svg",
"source": "<svg/>",
},
wantErr: false,
},
{ {
name: "valid: with idempotent-token", name: "valid: with idempotent-token",
flags: map[string]string{ flags: map[string]string{
@@ -117,25 +128,26 @@ func TestWhiteboardUpdate_Validate_TypedErrors(t *testing.T) {
"idempotent-token": "short", "idempotent-token": "short",
"source": "{}", "source": "{}",
}, nil) }, nil)
assertValidationParam(t, wbUpdateValidate(ctx, rt), "--idempotent-token") assertValidationParam(t, wbUpdateValidate(ctx, rt), "--idempotent-token", false)
}) })
t.Run("bad input_format", func(t *testing.T) { t.Run("bad input_format", func(t *testing.T) {
rt := newTestRuntime(map[string]string{ rt := newTestRuntime(map[string]string{
"whiteboard-token": "t", "whiteboard-token": "t",
"input_format": "svg", "input_format": "png",
"source": "{}", "source": "{}",
}, nil) }, nil)
assertValidationParam(t, wbUpdateValidate(ctx, rt), "--input_format") assertValidationParam(t, wbUpdateValidate(ctx, rt), "--input_format", false)
}) })
t.Run("malformed source json", func(t *testing.T) { t.Run("malformed source json", func(t *testing.T) {
_, err, _ := parseWBcliNodes([]byte("not-json")) _, err, _ := parseWBcliNodes([]byte("not-json"))
assertValidationParam(t, err, "--source") assertValidationParam(t, err, "--source", true)
}) })
} }
func assertValidationParam(t *testing.T, err error, wantParam string) { // assertValidationParam verifies a validation error carries the expected flag param.
func assertValidationParam(t *testing.T, err error, wantParam string, wantJSONCause bool) {
t.Helper() t.Helper()
if err == nil { if err == nil {
t.Fatalf("expected error, got nil") t.Fatalf("expected error, got nil")
@@ -150,8 +162,25 @@ func assertValidationParam(t *testing.T, err error, wantParam string) {
if ve.Param != wantParam { if ve.Param != wantParam {
t.Errorf("Param = %q, want %q", ve.Param, wantParam) t.Errorf("Param = %q, want %q", ve.Param, wantParam)
} }
p, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("errs.ProblemOf returned false")
}
if p.Category != errs.CategoryValidation {
t.Errorf("Category = %q, want %q", p.Category, errs.CategoryValidation)
}
if p.Subtype != errs.SubtypeInvalidArgument {
t.Errorf("Problem subtype = %q, want %q", p.Subtype, errs.SubtypeInvalidArgument)
}
if wantJSONCause {
var syntaxErr *json.SyntaxError
if !errors.As(err, &syntaxErr) {
t.Fatalf("expected json syntax cause to be preserved, err=%v", err)
}
}
} }
// TestGetFormat verifies input format defaults and explicit format selection.
func TestGetFormat(t *testing.T) { func TestGetFormat(t *testing.T) {
t.Parallel() t.Parallel()
@@ -180,6 +209,11 @@ func TestGetFormat(t *testing.T) {
flagVal: FormatMermaid, flagVal: FormatMermaid,
expected: FormatMermaid, expected: FormatMermaid,
}, },
{
name: "svg returns svg",
flagVal: FormatSVG,
expected: FormatSVG,
},
} }
for _, tt := range tests { for _, tt := range tests {
@@ -193,6 +227,7 @@ func TestGetFormat(t *testing.T) {
} }
} }
// TestWhiteboardUpdate_ShortcutRegistration verifies the shortcut metadata for update commands.
func TestWhiteboardUpdate_ShortcutRegistration(t *testing.T) { func TestWhiteboardUpdate_ShortcutRegistration(t *testing.T) {
t.Parallel() t.Parallel()
@@ -213,6 +248,7 @@ func TestWhiteboardUpdate_ShortcutRegistration(t *testing.T) {
} }
} }
// TestShortcutsIncludesExpectedCommands verifies the whiteboard shortcut registry includes query and update.
func TestShortcutsIncludesExpectedCommands(t *testing.T) { func TestShortcutsIncludesExpectedCommands(t *testing.T) {
t.Parallel() t.Parallel()
@@ -237,6 +273,7 @@ func TestShortcutsIncludesExpectedCommands(t *testing.T) {
} }
} }
// TestParseWBcliNodes verifies whiteboard CLI output parsing for raw and wrapped node payloads.
func TestParseWBcliNodes(t *testing.T) { func TestParseWBcliNodes(t *testing.T) {
t.Parallel() t.Parallel()
@@ -285,6 +322,7 @@ func TestParseWBcliNodes(t *testing.T) {
} }
} }
// TestWBUpdateDryRun verifies dry-run requests for the supported whiteboard update formats.
func TestWBUpdateDryRun(t *testing.T) { func TestWBUpdateDryRun(t *testing.T) {
ctx := context.Background() ctx := context.Background()
@@ -317,6 +355,14 @@ func TestWBUpdateDryRun(t *testing.T) {
"source": "graph TD\nA-->B", "source": "graph TD\nA-->B",
}, },
}, },
{
name: "dry run svg format",
flags: map[string]string{
"whiteboard-token": "test-token-123",
"input_format": "svg",
"source": "<svg/>",
},
},
} }
for _, tt := range tests { for _, tt := range tests {
@@ -362,6 +408,7 @@ func runUpdateShortcut(t *testing.T, shortcut common.Shortcut, args []string, fa
return err return err
} }
// TestWhiteboardUpdateExecute_RawFormat verifies raw node updates call the raw nodes endpoint.
func TestWhiteboardUpdateExecute_RawFormat(t *testing.T) { func TestWhiteboardUpdateExecute_RawFormat(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t) factory, stdout, reg := newUpdateExecuteFactory(t)
@@ -385,6 +432,7 @@ func TestWhiteboardUpdateExecute_RawFormat(t *testing.T) {
} }
} }
// TestWhiteboardUpdateExecute_PlantUMLFormat verifies PlantUML updates use the diagram import endpoint.
func TestWhiteboardUpdateExecute_PlantUMLFormat(t *testing.T) { func TestWhiteboardUpdateExecute_PlantUMLFormat(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t) factory, stdout, reg := newUpdateExecuteFactory(t)
@@ -410,6 +458,7 @@ Bob -> Alice : hello
} }
} }
// TestWhiteboardUpdateExecute_PlantUMLInvalidResponse verifies missing node IDs are treated as invalid responses.
func TestWhiteboardUpdateExecute_PlantUMLInvalidResponse(t *testing.T) { func TestWhiteboardUpdateExecute_PlantUMLInvalidResponse(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t) factory, stdout, reg := newUpdateExecuteFactory(t)
@@ -431,6 +480,7 @@ Bob -> Alice : hello
assertInvalidResponse(t, err) assertInvalidResponse(t, err)
} }
// TestWhiteboardUpdateExecute_MermaidFormat verifies Mermaid updates use the diagram import endpoint.
func TestWhiteboardUpdateExecute_MermaidFormat(t *testing.T) { func TestWhiteboardUpdateExecute_MermaidFormat(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t) factory, stdout, reg := newUpdateExecuteFactory(t)
@@ -455,6 +505,44 @@ A-->B`
} }
} }
// TestWhiteboardUpdateExecute_SVGFormat verifies svg update requests use syntax_type=3 and send the source payload.
func TestWhiteboardUpdateExecute_SVGFormat(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t)
// SVG shares the /nodes/plantuml endpoint with plantuml/mermaid via syntax_type=3.
stub := &httpmock.Stub{
Method: "POST",
URL: "/open-apis/board/v1/whiteboards/test-token-svg/nodes/plantuml",
Body: map[string]interface{}{
"code": 0,
"msg": "success",
"data": map[string]interface{}{
"node_id": "node1",
},
},
}
reg.Register(stub)
source := `<svg xmlns="http://www.w3.org/2000/svg"/>`
args := []string{"+update", "--whiteboard-token", "test-token-svg", "--input_format", "svg", "--source", source}
if err := runUpdateShortcut(t, WhiteboardUpdate, args, factory, stdout); err != nil {
t.Fatalf("err=%v", err)
}
var body map[string]interface{}
if err := json.Unmarshal(stub.CapturedBody, &body); err != nil {
t.Fatalf("unmarshal captured body: %v\nraw=%s", err, string(stub.CapturedBody))
}
if got := body["syntax_type"]; got != float64(3) {
t.Fatalf("syntax_type = %#v, want 3; body=%s", got, string(stub.CapturedBody))
}
if got := body["plant_uml_code"]; got != source {
t.Fatalf("plant_uml_code = %#v, want %q; body=%s", got, source, string(stub.CapturedBody))
}
}
// TestWhiteboardUpdateExecute_RawInvalidResponse verifies malformed raw update responses are rejected.
func TestWhiteboardUpdateExecute_RawInvalidResponse(t *testing.T) { func TestWhiteboardUpdateExecute_RawInvalidResponse(t *testing.T) {
tests := []struct { tests := []struct {
name string name string
@@ -494,6 +582,7 @@ func TestWhiteboardUpdateExecute_RawInvalidResponse(t *testing.T) {
} }
} }
// TestWhiteboardUpdateExecute_RawWithIdempotent verifies raw updates pass through the idempotency token.
func TestWhiteboardUpdateExecute_RawWithIdempotent(t *testing.T) { func TestWhiteboardUpdateExecute_RawWithIdempotent(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t) factory, stdout, reg := newUpdateExecuteFactory(t)
@@ -518,6 +607,7 @@ func TestWhiteboardUpdateExecute_RawWithIdempotent(t *testing.T) {
} }
} }
// TestWhiteboardUpdateExecute_RawFormatWithRawNodes verifies raw-node payloads are forwarded without DSL wrapping.
func TestWhiteboardUpdateExecute_RawFormatWithRawNodes(t *testing.T) { func TestWhiteboardUpdateExecute_RawFormatWithRawNodes(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t) factory, stdout, reg := newUpdateExecuteFactory(t)
@@ -541,6 +631,7 @@ func TestWhiteboardUpdateExecute_RawFormatWithRawNodes(t *testing.T) {
} }
} }
// TestWhiteboardUpdateExecute_RawAPIError verifies raw update API failures preserve typed error metadata and hints.
func TestWhiteboardUpdateExecute_RawAPIError(t *testing.T) { func TestWhiteboardUpdateExecute_RawAPIError(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t) factory, stdout, reg := newUpdateExecuteFactory(t)
@@ -577,6 +668,7 @@ func TestWhiteboardUpdateExecute_RawAPIError(t *testing.T) {
} }
} }
// TestWhiteboardUpdateExecute_PlantUMLAPIError verifies diagram update API failures preserve typed error metadata.
func TestWhiteboardUpdateExecute_PlantUMLAPIError(t *testing.T) { func TestWhiteboardUpdateExecute_PlantUMLAPIError(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t) factory, stdout, reg := newUpdateExecuteFactory(t)
@@ -607,6 +699,7 @@ invalid
} }
} }
// TestWhiteboardUpdateExecute_WithOverwrite verifies diagram updates send overwrite=true when requested.
func TestWhiteboardUpdateExecute_WithOverwrite(t *testing.T) { func TestWhiteboardUpdateExecute_WithOverwrite(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t) factory, stdout, reg := newUpdateExecuteFactory(t)
@@ -631,6 +724,7 @@ A-->B`
} }
} }
// TestWhiteboardUpdateExecute_RawWithOverwrite verifies raw updates send overwrite=true when requested.
func TestWhiteboardUpdateExecute_RawWithOverwrite(t *testing.T) { func TestWhiteboardUpdateExecute_RawWithOverwrite(t *testing.T) {
factory, stdout, reg := newUpdateExecuteFactory(t) factory, stdout, reg := newUpdateExecuteFactory(t)

View File

@@ -1,7 +1,7 @@
--- ---
name: lark-event name: lark-event
version: 1.0.0 version: 1.0.0
description: "Lark/Feishu real-time event listening / subscribing / consuming: stream events as NDJSON via `lark-cli event consume <EventKey>` (covers IM messages/reactions/chat changes, VC meeting ended, Minutes generated, Whiteboard updated, etc.). Use for Lark bots, real-time message processing, long-running subscribers, streaming webhook/push handlers. Supports `--max-events` / `--timeout` bounded runs and a stderr ready-marker contract — designed for AI agents running as subprocesses." description: "Lark/Feishu real-time event listening / subscribing / consuming: stream events as NDJSON via `lark-cli event consume <EventKey>` (covers IM messages/reactions/chat changes, Task updates, VC meeting ended, Minutes generated, Whiteboard updated, etc.). Use for Lark bots, real-time message processing, long-running subscribers, streaming webhook/push handlers. Supports `--max-events` / `--timeout` bounded runs and a stderr ready-marker contract — designed for AI agents running as subprocesses."
metadata: metadata:
requires: requires:
bins: ["lark-cli"] bins: ["lark-cli"]
@@ -148,6 +148,7 @@ Lark-defined semantic tags (**not** JSON Schema's standard `format`). Common val
| Topic | Reference | Coverage | | Topic | Reference | Coverage |
|------------|------------------------------------------------------------------------------|---| |------------|------------------------------------------------------------------------------|---|
| IM | [`references/lark-event-im.md`](references/lark-event-im.md) | Catalog of 11 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) | | IM | [`references/lark-event-im.md`](references/lark-event-im.md) | Catalog of 11 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) |
| 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 |
| VC | [`references/lark-event-vc.md`](references/lark-event-vc.md) | Catalog of 2 VC EventKeys (`vc.meeting.participant_meeting_ended_v1`, `vc.note.generated_v1`) + field reference + source type semantics (meeting only) | | VC | [`references/lark-event-vc.md`](references/lark-event-vc.md) | Catalog of 2 VC EventKeys (`vc.meeting.participant_meeting_ended_v1`, `vc.note.generated_v1`) + field reference + source type semantics (meeting only) |
| Minutes | [`references/lark-event-minutes.md`](references/lark-event-minutes.md) | Catalog of 1 Minutes EventKey (`minutes.minute.generated_v1`) + field reference + source type semantics (meeting only) | | Minutes | [`references/lark-event-minutes.md`](references/lark-event-minutes.md) | Catalog of 1 Minutes EventKey (`minutes.minute.generated_v1`) + field reference + source type semantics (meeting only) |
| Whiteboard | [`references/lark-event-whiteboard.md`](references/lark-event-whiteboard.md) | Catalog of 1 Board EventKey (`board.whiteboard.updated_v1`) + per-whiteboard subscription model (requires `-p whiteboard_id=<token>`) + payload field reference (whiteboard_id / operator_ids triple-id) | | Whiteboard | [`references/lark-event-whiteboard.md`](references/lark-event-whiteboard.md) | Catalog of 1 Board EventKey (`board.whiteboard.updated_v1`) + per-whiteboard subscription model (requires `-p whiteboard_id=<token>`) + payload field reference (whiteboard_id / operator_ids triple-id) |

View File

@@ -0,0 +1,78 @@
# Task Events
> **Prerequisite:** Read [`../SKILL.md`](../SKILL.md) first for the `event consume` essentials (commands, subprocess contract, jq usage).
## Key catalog (1)
| EventKey | Purpose |
|---|---|
| `task.task.update_user_access_v2` | A visible task has been created, deleted, or updated |
This key uses a **Native schema** (V2 envelope; output rooted at `.event`) and carries a **PreConsume hook** that calls the Task event subscription API before listening.
## Scopes & auth
| EventKey | Scope | Auth |
|---|---|---|
| `task.task.update_user_access_v2` | `task:task:read` | user, bot |
Supports `--as user` or `--as bot`.
- `--as user`: receive task updates visible to the current user through authorship, assignment, following, or other access.
- `--as bot`: receive task updates for tasks the application is responsible for.
## `task.task.update_user_access_v2`
### Subscription behavior
On startup, `event consume` calls:
```text
POST /open-apis/task/v2/task_v2/task_subscription?user_id_type=open_id
```
The Task subscription API has no matching unsubscribe endpoint in the current CLI metadata, so graceful exit has no cleanup call for this EventKey. Re-running the consumer repeats the subscribe call for the selected identity.
This EventKey is single-consumer per local bus subscription: start one `event consume task.task.update_user_access_v2` process for a given app/profile/identity at a time.
### Output fields (V2 envelope; root path `.event`)
| Field | Type | Description |
|---|---|---|
| `.header.event_id` | string | Globally unique event ID; safe for deduplication |
| `.header.create_time` | string (timestamp_ms) | Event creation time in milliseconds |
| `.event.event_types[]` | string enum | Task commit types included in this event |
| `.event.task_guid` | string (kind=task_guid) | Task GUID that changed |
Commit types:
```text
task_assignees_update
task_completed_update
task_create
task_deleted
task_desc_update
task_followers_update
task_reminders_update
task_start_due_update
task_summary_update
```
### Example
```bash
# Stream task update events for the current user
lark-cli event consume task.task.update_user_access_v2 --as user
# Sample one event for payload inspection
lark-cli event consume task.task.update_user_access_v2 \
--as user --max-events 1 --timeout 2m
# Project to a compact task-update record
lark-cli event consume task.task.update_user_access_v2 \
--as user \
--jq '{event_id: .header.event_id, task_guid: .event.task_guid, event_types: .event.event_types, timestamp: .header.create_time}'
# Consume as the app identity
lark-cli event consume task.task.update_user_access_v2 --as bot
```

View File

@@ -61,6 +61,10 @@ The four message-pulling shortcuts (`+messages-mget`, `+chat-messages-list`, `+m
Card messages (`interactive` type) are not yet supported for compact conversion in event subscriptions. The raw event data will be returned instead, with a hint printed to stderr. Card messages (`interactive` type) are not yet supported for compact conversion in event subscriptions. The raw event data will be returned instead, with a hint printed to stderr.
### Audio Messages
`--audio` sends a voice message and supports only Opus audio files, for example `.opus` files or Ogg Opus (`.ogg`) files. For `mp3`, `wav`, or other non-Opus audio, either convert to `.opus` first and keep using `--audio`, or send the original file as an attachment with `--file`.
### Flag Types ### Flag Types
Flags support two layers: Flags support two layers:

View File

@@ -147,6 +147,9 @@ lark-cli im +messages-reply --message-id om_xxx --file ./report.pdf
# Reply with a local video (--video-cover is required as the video cover) # Reply with a local video (--video-cover is required as the video cover)
lark-cli im +messages-reply --message-id om_xxx --video ./demo.mp4 --video-cover ./cover.png lark-cli im +messages-reply --message-id om_xxx --video ./demo.mp4 --video-cover ./cover.png
# Reply with a voice message
lark-cli im +messages-reply --message-id om_xxx --audio ./voice.opus
# With an idempotency key # With an idempotency key
lark-cli im +messages-reply --message-id om_xxx --text "Received" --idempotency-key my-unique-id lark-cli im +messages-reply --message-id om_xxx --text "Received" --idempotency-key my-unique-id
@@ -159,6 +162,7 @@ lark-cli im +messages-reply --message-id om_xxx --markdown $'## Test\n\nhello' -
- Media flags accept an existing key (`img_xxx` / `file_xxx`), an `http://` or `https://` URL, or a local file path. - Media flags accept an existing key (`img_xxx` / `file_xxx`), an `http://` or `https://` URL, or a local file path.
- Local paths must be relative to the current working directory and stay within it after resolving `..` and symlinks. - Local paths must be relative to the current working directory and stay within it after resolving `..` and symlinks.
- Absolute paths such as `/tmp/photo.png` are rejected. Run the command from the file's directory and pass `./photo.png`, or copy the file into the current directory first. - Absolute paths such as `/tmp/photo.png` are rejected. Run the command from the file's directory and pass `./photo.png`, or copy the file into the current directory first.
- `--audio` sends a voice message and accepts only Opus audio (`.opus` or Ogg Opus `.ogg`) for local paths and URLs. For `mp3`, `wav`, or other non-Opus audio, convert to `.opus` before using `--audio`, or use `--file` to send the original audio as an attachment.
## Parameters ## Parameters
@@ -173,7 +177,7 @@ lark-cli im +messages-reply --message-id om_xxx --markdown $'## Test\n\nhello' -
| `--file <path\|url\|key>` | One content option | Cwd-relative local file path, URL, or `file_key` (`file_xxx`) | | `--file <path\|url\|key>` | One content option | Cwd-relative local file path, URL, or `file_key` (`file_xxx`) |
| `--video <path\|url\|key>` | One content option | Cwd-relative local video path, URL, or `file_key` (`file_xxx`); **must be used together with `--video-cover`** | | `--video <path\|url\|key>` | One content option | Cwd-relative local video path, URL, or `file_key` (`file_xxx`); **must be used together with `--video-cover`** |
| `--video-cover <path\|url\|key>` | **Required with `--video`** | Cwd-relative local cover image path, URL, or `image_key` (`img_xxx`) | | `--video-cover <path\|url\|key>` | **Required with `--video`** | Cwd-relative local cover image path, URL, or `image_key` (`img_xxx`) |
| `--audio <path\|url\|key>` | One content option | Cwd-relative local audio path, URL, or `file_key` (`file_xxx`) | | `--audio <path\|url\|key>` | One content option | Voice-message audio key, URL, or cwd-relative local path. Local paths and URLs must be Opus (`.opus` or Ogg Opus `.ogg`) |
| `--reply-in-thread` | No | Reply inside the thread. The reply appears in the target message's thread instead of the main chat stream | | `--reply-in-thread` | No | Reply inside the thread. The reply appears in the target message's thread instead of the main chat stream |
| `--idempotency-key <key>` | No | Idempotency key; the same key sends only one reply within 1 hour | | `--idempotency-key <key>` | No | Idempotency key; the same key sends only one reply within 1 hour |
| `--as <identity>` | No | Identity type: `bot` or `user` (default `bot`) | | `--as <identity>` | No | Identity type: `bot` or `user` (default `bot`) |

View File

@@ -150,7 +150,7 @@ lark-cli im +messages-send --chat-id oc_xxx --file ./report.pdf
lark-cli im +messages-send --chat-id oc_xxx --video ./demo.mp4 --video-cover ./cover.png lark-cli im +messages-send --chat-id oc_xxx --video ./demo.mp4 --video-cover ./cover.png
lark-cli im +messages-send --chat-id oc_xxx --video ./demo.mp4 --video-cover img_xxx lark-cli im +messages-send --chat-id oc_xxx --video ./demo.mp4 --video-cover img_xxx
# Send audio # Send a voice message
lark-cli im +messages-send --chat-id oc_xxx --audio ./voice.opus lark-cli im +messages-send --chat-id oc_xxx --audio ./voice.opus
# Use an idempotency key (same key sends only once within 1 hour) # Use an idempotency key (same key sends only once within 1 hour)
@@ -165,6 +165,7 @@ lark-cli im +messages-send --chat-id oc_xxx --markdown $'## Test\n\nhello' --dry
- Media flags accept an existing key (`img_xxx` / `file_xxx`), an `http://` or `https://` URL, or a local file path. - Media flags accept an existing key (`img_xxx` / `file_xxx`), an `http://` or `https://` URL, or a local file path.
- Local paths must be relative to the current working directory and stay within it after resolving `..` and symlinks. - Local paths must be relative to the current working directory and stay within it after resolving `..` and symlinks.
- Absolute paths such as `/tmp/photo.png` are rejected. Run the command from the file's directory and pass `./photo.png`, or copy the file into the current directory first. - Absolute paths such as `/tmp/photo.png` are rejected. Run the command from the file's directory and pass `./photo.png`, or copy the file into the current directory first.
- `--audio` sends a voice message and accepts only Opus audio (`.opus` or Ogg Opus `.ogg`) for local paths and URLs. For `mp3`, `wav`, or other non-Opus audio, convert to `.opus` before using `--audio`, or use `--file` to send the original audio as an attachment.
## Parameters ## Parameters
@@ -179,7 +180,7 @@ lark-cli im +messages-send --chat-id oc_xxx --markdown $'## Test\n\nhello' --dry
| `--file <path\|url\|key>` | One content option | Cwd-relative local file path, URL, or `file_key` (`file_xxx`). Local paths and URLs are uploaded automatically | | `--file <path\|url\|key>` | One content option | Cwd-relative local file path, URL, or `file_key` (`file_xxx`). Local paths and URLs are uploaded automatically |
| `--video <path\|url\|key>` | One content option | Cwd-relative local video path, URL, or `file_key` (`file_xxx`). Local paths and URLs are uploaded automatically. **Must be paired with `--video-cover`** | | `--video <path\|url\|key>` | One content option | Cwd-relative local video path, URL, or `file_key` (`file_xxx`). Local paths and URLs are uploaded automatically. **Must be paired with `--video-cover`** |
| `--video-cover <path\|url\|key>` | **Required with `--video`** | Cwd-relative local cover image path, URL, or `image_key` (`img_xxx`). Local paths and URLs are uploaded automatically | | `--video-cover <path\|url\|key>` | **Required with `--video`** | Cwd-relative local cover image path, URL, or `image_key` (`img_xxx`). Local paths and URLs are uploaded automatically |
| `--audio <path\|url\|key>` | One content option | Cwd-relative local audio path, URL, or `file_key` (`file_xxx`). Local paths and URLs are uploaded automatically | | `--audio <path\|url\|key>` | One content option | Voice-message audio key, URL, or cwd-relative local path. Local paths and URLs must be Opus (`.opus` or Ogg Opus `.ogg`) |
| `--msg-type <type>` | No | Message type (default `text`). If you use `--text` / `--markdown` / media flags, the effective type is inferred automatically. Explicitly setting a conflicting `--msg-type` fails validation | | `--msg-type <type>` | No | Message type (default `text`). If you use `--text` / `--markdown` / media flags, the effective type is inferred automatically. Explicitly setting a conflicting `--msg-type` fails validation |
| `--idempotency-key <key>` | No | Idempotency key; the same key sends only one message within 1 hour | | `--idempotency-key <key>` | No | Idempotency key; the same key sends only one message within 1 hour |
| `--as <identity>` | No | Identity type: `bot` or `user` (default `bot`) | | `--as <identity>` | No | Identity type: `bot` or `user` (default `bot`) |

View File

@@ -15,7 +15,7 @@ metadata:
| 用户需求 | 优先动作 | 关键文档 / 命令 | | 用户需求 | 优先动作 | 关键文档 / 命令 |
|----------|----------|-----------------| |----------|----------|-----------------|
| 新建 PPT | 先规划 `slide_plan.json`,再按复杂度选择一步或两步创建 | `planning-layer.md``visual-planning.md``asset-planning.md``slides +create` | | 新建 PPT | 先规划 `slide_plan.json`,再按复杂度选择一步或两步创建 | `planning-layer.md``visual-planning.md``asset-planning.md``slides +create` |
| 已有 PPT 大幅改写 | 多页整页重建用 `+replace-pages`,单页局部编辑用 `+replace-slide` | `xml_presentations.get``lark-slides-replace-pages.md``lark-slides-edit-workflows.md` | | 大幅改写页面 | 先回读现有 XML写入新 plan再替换或重建相关页面 | `xml_presentations.get``+replace-slide``lark-slides-edit-workflows.md` |
| 编辑单个标题、文本块、图片或局部元素 | 优先块级替换/插入,不改页序 | `slides +replace-slide``lark-slides-replace-slide.md` | | 编辑单个标题、文本块、图片或局部元素 | 优先块级替换/插入,不改页序 | `slides +replace-slide``lark-slides-replace-slide.md` |
| 读取或分析已有 PPT | 解析 slides/wiki token回读全文或单页 XML保存 `xml_presentation_id``slide_id``revision_id` | `xml_presentations.get``xml_presentation.slide.get` | | 读取或分析已有 PPT | 解析 slides/wiki token回读全文或单页 XML保存 `xml_presentation_id``slide_id``revision_id` | `xml_presentations.get``xml_presentation.slide.get` |
| 获取幻灯片页面截图 | 用 `slide_id` 或页号指定页面 | `slides +screenshot``lark-slides-screenshot.md` | | 获取幻灯片页面截图 | 用 `slide_id` 或页号指定页面 | `slides +screenshot``lark-slides-screenshot.md` |
@@ -36,7 +36,7 @@ metadata:
**CRITICAL — 新建演示文稿或大幅改写页面时,规划 `asset_need` MUST 遵循 [asset-planning.md](references/asset-planning.md):只做元数据规划,必须有 `fallback_if_missing`,不得要求真实搜索、下载或上传素材。** **CRITICAL — 新建演示文稿或大幅改写页面时,规划 `asset_need` MUST 遵循 [asset-planning.md](references/asset-planning.md):只做元数据规划,必须有 `fallback_if_missing`,不得要求真实搜索、下载或上传素材。**
**CRITICAL — 创建或大幅改写后MUST 按 [validation-checklist.md](references/validation-checklist.md) 做显式验证:回读全文 XML、核对页数和关键元素、检查空白/破损页、明显溢出、布局风险XML 语法和文本重叠静态检查优先使用 [`scripts/xml_text_overlap_lint.py`](scripts/xml_text_overlap_lint.py),不得交付 `double_escaped_entity` 问题** **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 和布局风险。** **CRITICAL — 创建前自检或失败排障时MUST 按 [troubleshooting.md](references/troubleshooting.md) 检查 XML 转义、结构、shell 截断、图片 token、3350001 和布局风险。**
@@ -47,7 +47,7 @@ metadata:
**CRITICAL — 使用模板生成或改写页面时MUST 先 `summarize` 目标页型;只有需要具体布局骨架时才 `extract`。** **CRITICAL — 使用模板生成或改写页面时MUST 先 `summarize` 目标页型;只有需要具体布局骨架时才 `extract`。**
**编辑已有幻灯片页面**单个标题、文本块、图片或局部元素优先用 [`+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)。 **编辑已有幻灯片页面**:优先用 [`+replace-slide`](references/lark-slides-replace-slide.md)(块级替换/插入,不动页序);选择 action 和完整读-改-写流程见 [`lark-slides-edit-workflows.md`](references/lark-slides-edit-workflows.md)。
## 身份选择 ## 身份选择
@@ -82,7 +82,7 @@ lark-cli auth login --domain slides
按需再读: 按需再读:
- 创建:[`lark-slides-create.md`](references/lark-slides-create.md) - 创建:[`lark-slides-create.md`](references/lark-slides-create.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-edit-workflows.md`](references/lark-slides-edit-workflows.md)、[`lark-slides-replace-slide.md`](references/lark-slides-replace-slide.md)
- 截图:[`lark-slides-screenshot.md`](references/lark-slides-screenshot.md) - 截图:[`lark-slides-screenshot.md`](references/lark-slides-screenshot.md)
- 图片:[`lark-slides-media-upload.md`](references/lark-slides-media-upload.md) - 图片:[`lark-slides-media-upload.md`](references/lark-slides-media-upload.md)
- 流程图 / 时序图 / 架构图 / 装饰图案:[`lark-slides-whiteboard.md`](references/lark-slides-whiteboard.md) - 流程图 / 时序图 / 架构图 / 装饰图案:[`lark-slides-whiteboard.md`](references/lark-slides-whiteboard.md)
@@ -268,7 +268,6 @@ Shortcut 是对常用操作的高级封装(`lark-cli slides +<verb> [flags]`
| [`+create`](references/lark-slides-create.md) | 创建 PPT可选 `--slides` 一步添加页面,支持 `<img src="@./local.png">` 占位符自动上传) | | [`+create`](references/lark-slides-create.md) | 创建 PPT可选 `--slides` 一步添加页面,支持 `<img src="@./local.png">` 占位符自动上传) |
| [`+media-upload`](references/lark-slides-media-upload.md) | 上传本地图片到指定演示文稿,返回 `file_token`(用作 `<img src="...">`),最大 20 MB | | [`+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-slide`](references/lark-slides-replace-slide.md) | 对已有幻灯片页面进行块级替换/插入(`block_replace` / `block_insert`),自动注入 id 和 `<content/>`,不改变页序 |
| [`+replace-pages`](references/lark-slides-replace-pages.md) | 在原演示文稿内批量重建多个页面:先创建新页到旧页前,再删除旧页;适合已有 Slides 的多页大改,不新建链接 |
没有 Shortcut 覆盖时使用原生 API。高频资源`xml_presentations.get` 读取全文;`xml_presentation.slide.create/delete/get/replace` 管理单页。 没有 Shortcut 覆盖时使用原生 API。高频资源`xml_presentations.get` 读取全文;`xml_presentation.slide.create/delete/get/replace` 管理单页。
@@ -287,7 +286,7 @@ lark-cli slides <resource> <method> [flags] # 调用 API
4. **文本通过 `<content>` 表达**:必须用 `<content><p>...</p></content>`,不能把文字直接写在 shape 内 4. **文本通过 `<content>` 表达**:必须用 `<content><p>...</p></content>`,不能把文字直接写在 shape 内
5. **保存关键 ID**:后续操作需要 `xml_presentation_id``slide_id``revision_id` 5. **保存关键 ID**:后续操作需要 `xml_presentation_id``slide_id``revision_id`
6. **删除谨慎**:删除操作不可逆,且至少保留一页幻灯片 6. **删除谨慎**:删除操作不可逆,且至少保留一页幻灯片
7. **编辑已有页面优先原链接更新**:修改单个 shape/img 用 `+replace-slide``block_replace` / `block_insert`),不要整页重建;已有 Slides 的多页整页重建用 `+replace-pages`,不要用 `slides +create` 新建整份 PPT只有没有 shortcut 覆盖的特殊单页整页操作才手动 `slide.create` + `slide.delete` 7. **编辑已有页面优先块级替换**:修改单个 shape/img 用 `+replace-slide``block_replace` / `block_insert`),不要整页重建;只有需要替换整页结构时才用 `slide.delete` + `slide.create`
8. **`<img src>` 只能用上传到飞书 drive 的 `file_token`,禁止使用 http(s) 外链 URL**:飞书 slides 渲染端不会代理外链图片,外链 src 在 PPT 里通常不显示或显示破图。流程必须是「先把图存到本地 → 用 `slides +media-upload` 上传或 `+create --slides``@./path` 占位符自动上传 → 拿 `file_token` 写进 `<img src>`」。如果用户给了网图链接,先 `curl`/下载到 CWD 内再走上传流程,不要直接把外链 URL 塞进 `src`。**图片最大 20 MB**slides upload API 不支持分片上传)。 8. **`<img src>` 只能用上传到飞书 drive 的 `file_token`,禁止使用 http(s) 外链 URL**:飞书 slides 渲染端不会代理外链图片,外链 src 在 PPT 里通常不显示或显示破图。流程必须是「先把图存到本地 → 用 `slides +media-upload` 上传或 `+create --slides``@./path` 占位符自动上传 → 拿 `file_token` 写进 `<img src>`」。如果用户给了网图链接,先 `curl`/下载到 CWD 内再走上传流程,不要直接把外链 URL 塞进 `src`。**图片最大 20 MB**slides upload API 不支持分片上传)。
> **注意**:如果 md 内容与 `slides_xml_schema_definition.xml` 或 `lark-cli schema slides.<resource>.<method>` 输出不一致,以后两者为准。 > **注意**:如果 md 内容与 `slides_xml_schema_definition.xml` 或 `lark-cli schema slides.<resource>.<method>` 输出不一致,以后两者为准。

View File

@@ -1,6 +1,6 @@
# 编辑已有 PPT读-改-写闭环 # 编辑已有 PPT读-改-写闭环
局部编辑走 **shortcut [`+replace-slide`](lark-slides-replace-slide.md)**(块级替换 / 插入),配合 `xml_presentation.slide.get` 读原页拿 `block_id`已有 Slides 的多页整页重建走 **[`+replace-pages`](lark-slides-replace-pages.md)**,保持原 presentation 链接不变。 编辑走 **shortcut [`+replace-slide`](lark-slides-replace-slide.md)**(块级替换 / 插入),配合 `xml_presentation.slide.get` 读原页拿 `block_id`
> 生成 XML 前**必读** [xml-schema-quick-ref.md](xml-schema-quick-ref.md)。 > 生成 XML 前**必读** [xml-schema-quick-ref.md](xml-schema-quick-ref.md)。
@@ -11,7 +11,6 @@
| 已知某块的 `block_id`,要换这块内容(改标题、换图、挪坐标) | `block_replace` | 精准替换,原子性好;`replacement``id` 由 CLI 自动注入为 `block_id` | | 已知某块的 `block_id`,要换这块内容(改标题、换图、挪坐标) | `block_replace` | 精准替换,原子性好;`replacement``id` 由 CLI 自动注入为 `block_id` |
| 只加 1~N 个元素、不动现有布局 | `block_insert` | 新增不覆盖,可选 `insert_before_block_id` 指定位置 | | 只加 1~N 个元素、不动现有布局 | `block_insert` | 新增不覆盖,可选 `insert_before_block_id` 指定位置 |
| 一次动多个元素(如:换标题 + 加图) | 单次 `--parts` 里拼多条 | 整批作为原子事务,任一失败整批不生效;`block_replace``block_insert` 可混用 | | 一次动多个元素(如:换标题 + 加图) | 单次 `--parts` 里拼多条 | 整批作为原子事务,任一失败整批不生效;`block_replace``block_insert` 可混用 |
| 多页版式重建、整页坐标重排 | `+replace-pages` | 原 presentation 内批量 create-before/delete-old不生成新 Slides 链接 |
> **没有字段级 patch**:即便只想改一个 `shape` 的 `topLeftX`,也得把整个块的新 XML 写出来用 `block_replace`。这不是"微调",是块级重写。 > **没有字段级 patch**:即便只想改一个 `shape` 的 `topLeftX`,也得把整个块的新 XML 写出来用 `block_replace`。这不是"微调",是块级重写。
@@ -46,7 +45,7 @@ REV=$(lark-cli slides xml_presentation.slide get --as user \
# 写时传该版本号,服务端以此为 base # 写时传该版本号,服务端以此为 base
lark-cli slides +replace-slide --as user \ lark-cli slides +replace-slide --as user \
--presentation "$PID" --slide-id "$SID" --revision-id "$REV" \ --presentation "$PID" --slide-id "$SID" --revision-id "$REV" \
--parts '[{"action":"block_replace","block_id":"bUn","replacement":"<shape type=\"rect\" topLeftX=\"100\" topLeftY=\"100\" width=\"200\" height=\"100\"><content/></shape>"}]' --parts '[{"action":"block_replace","block_id":"bUn","replacement":"<shape type=\"rect\" topLeftX=\"100\" topLeftY=\"100\" width=\"200\" height=\"100\"/>"}]'
``` ```
注意:传不存在的版本号(超过当前 revision会返回 3350002 not found不确定时用 `-1` 即可。 注意:传不存在的版本号(超过当前 revision会返回 3350002 not found不确定时用 `-1` 即可。
@@ -137,7 +136,6 @@ cat parts.json | lark-cli slides +replace-slide --as user --presentation "$PID"
## 相关文档 ## 相关文档
- [lark-slides-replace-slide.md](lark-slides-replace-slide.md) — +replace-slide shortcut 参数详情 - [lark-slides-replace-slide.md](lark-slides-replace-slide.md) — +replace-slide shortcut 参数详情
- [lark-slides-replace-pages.md](lark-slides-replace-pages.md) — 多页整页重建 shortcut
- [lark-slides-xml-presentation-slide-get.md](lark-slides-xml-presentation-slide-get.md) — slide.get 参考(拿 `block_id` / `revision_id` - [lark-slides-xml-presentation-slide-get.md](lark-slides-xml-presentation-slide-get.md) — slide.get 参考(拿 `block_id` / `revision_id`
- [lark-slides-xml-presentation-slide-replace.md](lark-slides-xml-presentation-slide-replace.md) — 底层 replace API 参考(一般直接用 shortcut 即可) - [lark-slides-xml-presentation-slide-replace.md](lark-slides-xml-presentation-slide-replace.md) — 底层 replace API 参考(一般直接用 shortcut 即可)
- [lark-slides-media-upload.md](lark-slides-media-upload.md) — 上传图片拿 file_token - [lark-slides-media-upload.md](lark-slides-media-upload.md) — 上传图片拿 file_token

View File

@@ -1,95 +0,0 @@
# slides +replace-pages多页整页重建
批量替换已有演示文稿里的多个页面,保持原 `xml_presentation_id` 和原 Slides 链接不变。适合多页版式大改、坐标重排、整页视觉重建;单个文本框、图片或 shape 的局部编辑仍优先用 [`+replace-slide`](lark-slides-replace-slide.md)。
> 重要这是多步编排不是后端原子事务。CLI 对每页执行“先创建新页到旧页前,再删除旧页”;创建失败时旧页会保留。删除失败时可能出现新旧页同时存在,需要按返回结果继续处理。
## 命令
```bash
lark-cli slides +replace-pages \
--as user \
--presentation <slides_url_or_xml_presentation_id> \
--pages @pages.json
```
## 参数
| 参数 | 必需 | 说明 |
|------|------|------|
| `--presentation` | 是 | `xml_presentation_id``/slides/` URL 或 `/wiki/` URL |
| `--pages` | 是 | JSON 数组,每项包含 `slide_id``content`;支持 literal、`@file`、stdin `-` |
| `--dry-run` | 否 | 基于 `slide_id` 输入输出替换计划,不执行 create/delete |
| `--continue-on-error` | 否 | 默认失败即停;开启后继续处理后续页,并在结果中标记失败项 |
| `--validate-only` | 否 | 只校验输入并生成替换计划,不执行 Slides get/create/delete |
## pages.json
```json
[
{
"slide_id": "slide_short_id_1",
"content": "<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data></data></slide>"
},
{
"slide_id": "slide_short_id_2",
"content": "<slide xmlns=\"http://www.larkoffice.com/sml/2.0\"><data></data></slide>"
}
]
```
规则:
- 每项必须提供 `slide_id`;不支持 `slide_number`
- `content` 必须是完整 `<slide>...</slide>` XML。
- 同一批次不能重复 `slide_id`
- CLI 不会回读整份 presentation如果 `slide_id` 已失效create/delete 阶段会返回对应错误。
## Dry Run
```bash
lark-cli slides +replace-pages --as user \
--presentation "$PID" \
--pages @pages.json \
--dry-run
```
输出包含 `xml_presentation_id``pages_count``plan`,以及每页的 `old_slide_id``insert_before_slide_id` 和动作 `create_before_then_delete_old`。Dry-run 只基于输入的 `slide_id` 构造计划,不会调用 `xml_presentations.get`,也不会执行 create/delete。
## 成功输出
```json
{
"xml_presentation_id": "xxx",
"pages_count": 2,
"status": "completed",
"summary": {
"replaced": 2,
"failed": 0,
"total": 2
},
"results": [
{
"old_slide_id": "old3",
"new_slide_id": "new3",
"status": "replaced"
}
],
"revision_id": 123
}
```
如果使用 `--continue-on-error` 且任一页面失败CLI 会继续处理后续页,但最终以 partial failure 非零退出stdout 仍保留完整 `results`,顶层 `ok``false``status``partial_failure`
`status` 可能为:
- `replaced`:新页创建成功,旧页删除成功。
- `create_failed`:新页创建失败,旧页保留。
- `delete_failed`:新页已创建,但旧页删除失败。
## 使用建议
1. 大幅改写前先 `xml_presentations.get` 保存当前 XML并记录要替换页面的 `slide_id`
2. 生成只含 `slide_id``pages.json` 后先跑 `--dry-run``--validate-only`
3. 默认不要开 `--continue-on-error`,除非能接受部分页面已替换。
4. 替换后再回读全文 XML 并截图检查,确认页序、视觉和文本没有破损。

View File

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

View File

@@ -103,7 +103,7 @@ lark-cli slides xml_presentation.slide create --as user --params '{
"xml_presentation_id": "slides_example_presentation_id" "xml_presentation_id": "slides_example_presentation_id"
}' --data '{ }' --data '{
"slide": { "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><content/></shape></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>"
} }
}' }'
``` ```

View File

@@ -61,7 +61,6 @@ lark-cli slides xml_presentations get --as user --params '{"xml_presentation_id"
"xml_presentation": { "xml_presentation": {
"presentation_id": "slides_example_presentation_id", "presentation_id": "slides_example_presentation_id",
"revision_id": 1, "revision_id": 1,
"url": "https://example.feishu.cn/slides/slides_example_presentation_id",
"content": "<presentation xmlns=\"http://www.larkoffice.com/sml/2.0\" height=\"540\" width=\"960\">...</presentation>" "content": "<presentation xmlns=\"http://www.larkoffice.com/sml/2.0\" height=\"540\" width=\"960\">...</presentation>"
} }
}, },
@@ -75,7 +74,6 @@ lark-cli slides xml_presentations get --as user --params '{"xml_presentation_id"
|------|------|------| |------|------|------|
| `data.xml_presentation.presentation_id` | string | 演示文稿唯一标识 | | `data.xml_presentation.presentation_id` | string | 演示文稿唯一标识 |
| `data.xml_presentation.revision_id` | integer | 版本号 | | `data.xml_presentation.revision_id` | integer | 版本号 |
| `data.xml_presentation.url` | string | 对应 Slides 的访问地址 |
| `data.xml_presentation.content` | string | XML 格式的完整内容 | | `data.xml_presentation.content` | string | XML 格式的完整内容 |
## 常见错误 ## 常见错误

View File

@@ -7,7 +7,6 @@
在真正创建或替换前,至少检查: 在真正创建或替换前,至少检查:
- 特殊字符已转义:正文和标题里的 `&``<``>` 不能裸写;属性值里的裸 `&` 也必须写成 `&amp;` - 特殊字符已转义:正文和标题里的 `&``<``>` 不能裸写;属性值里的裸 `&` 也必须写成 `&amp;`
- 普通可见符号直接写 Unicode不要输出 HTML/XML entity 后再转义:`«姓名»``●``✓` 是正确文本;`&amp;#171;姓名&amp;#187;``&amp;#9679;``&amp;nbsp;` 会在页面中泄漏成字面量。
- 属性引号安全XML 属性、shell 引号、JSON 字符串包装之间没有互相打断。 - 属性引号安全XML 属性、shell 引号、JSON 字符串包装之间没有互相打断。
- 结构合法:`<slide>` 下只放 `<style>``<data>``<note>`,文本都在 `<content>` 内。 - 结构合法:`<slide>` 下只放 `<style>``<data>``<note>`,文本都在 `<content>` 内。
- 图片路径正确:`<img src="@...">` 只在 `+create --slides` 的支持链路中使用;直接调用 `xml_presentation.slide.create` 必须先拿到 `file_token` - 图片路径正确:`<img src="@...">` 只在 `+create --slides` 的支持链路中使用;直接调用 `xml_presentation.slide.create` 必须先拿到 `file_token`
@@ -18,9 +17,9 @@
1. 记录 `xml_presentation_id`,不要假设失败代表什么都没创建。 1. 记录 `xml_presentation_id`,不要假设失败代表什么都没创建。
2.`xml_presentations.get` 回读,确认是否已有部分页面写入。 2.`xml_presentations.get` 回读,确认是否已有部分页面写入。
3. 检查失败页是否含未转义字符:`Q&A -> Q&amp;A`,文本 `<` / `>` 写成 `&lt;` / `&gt;`,属性 URL `a=1&b=2 -> a=1&amp;b=2`;同时检查是否有 `double_escaped_entity`,如 `&amp;#9679;``&amp;nbsp;``&amp;lt;` 3. 检查失败页是否含未转义字符:`Q&A -> Q&amp;A`,文本 `<` / `>` 写成 `&lt;` / `&gt;`,属性 URL `a=1&b=2 -> a=1&amp;b=2`
4. 检查标签闭合、属性引号、`<content>` 结构,以及 `<slide>` 直接子元素。 4. 检查标签闭合、属性引号、`<content>` 结构,以及 `<slide>` 直接子元素。
5. 页面空白、溢出、重叠、乱码或越界时,按 [validation-checklist.md](validation-checklist.md) 运行 XML 文本重叠检查,并人工核对越界、截断、图文压盖等视觉风险;工具会报告 XML 语法、二次转义实体、文本重叠和部分异常换行风险 5. 页面空白、溢出、重叠或越界时,按 [validation-checklist.md](validation-checklist.md) 运行 XML 文本重叠检查,并人工核对越界、截断、图文压盖等视觉风险;工具当前只会报告 `xml_not_well_formed` / `bbox_overlap`
6. 如果使用 `--slides '[...]'`,怀疑 shell 截断时直接切到两步创建:先 `slides +create`,再用 `xml_presentation.slide.create` 逐页添加。 6. 如果使用 `--slides '[...]'`,怀疑 shell 截断时直接切到两步创建:先 `slides +create`,再用 `xml_presentation.slide.create` 逐页添加。
7. 局部问题用 `+replace-slide` 块级修正;整页结构要改时再用 `slide.delete` 旧页 + `slide.create` 新页。 7. 局部问题用 `+replace-slide` 块级修正;整页结构要改时再用 `slide.delete` 旧页 + `slide.create` 新页。
@@ -53,7 +52,7 @@
| 400 无法删除唯一幻灯片 | 演示文稿至少保留一页 | 先创建新页,再删除旧页 | | 400 无法删除唯一幻灯片 | 演示文稿至少保留一页 | 先创建新页,再删除旧页 |
| 1061002 媒体上传 params error | slides 媒体上传参数不符合约定 | 用 `slides +media-upload`,不要手拼原生 `medias/upload_all`slides 唯一可用 `parent_type``slide_file` | | 1061002 媒体上传 params error | slides 媒体上传参数不符合约定 | 用 `slides +media-upload`,不要手拼原生 `medias/upload_all`slides 唯一可用 `parent_type``slide_file` |
| 1061004 forbidden | 当前身份对演示文稿无编辑权限 | 确认 user/bot 对目标 PPT 有编辑权限bot 常见于 PPT 非该 bot 创建 | | 1061004 forbidden | 当前身份对演示文稿无编辑权限 | 确认 user/bot 对目标 PPT 有编辑权限bot 常见于 PPT 非该 bot 创建 |
| 3350001 | XML 非 well-formed、XML 结构不符合服务端要求,或 replace 片段问题 | 优先检查未转义字符和二次转义实体replace 场景再看 `block_id``<content/>` | | 3350001 | XML 非 well-formed、XML 结构不符合服务端要求,或 replace 片段问题 | 优先检查未转义字符replace 场景再看 `block_id``<content/>` |
| 3350002 | `revision_id` 大于当前版本 | 用 `-1` 取当前版本,或重新读 `xml_presentations.get` 取最新 `revision_id` | | 3350002 | `revision_id` 大于当前版本 | 用 `-1` 取当前版本,或重新读 `xml_presentations.get` 取最新 `revision_id` |
| validation: unsafe file path | `--file` 给了绝对路径或上层路径 | `--file` 必须是 CWD 内相对路径;先 `cd` 到素材目录再执行 | | validation: unsafe file path | `--file` 给了绝对路径或上层路径 | `--file` 必须是 CWD 内相对路径;先 `cd` 到素材目录再执行 |

View File

@@ -1,6 +1,6 @@
# Validation Checklist # Validation Checklist
创建或大幅改写演示文稿后必须做一次显式验证。目标是发现空白页、XML 损坏、内容截断、异常换行、明显溢出、弱视觉层级和未验证输出。 创建或大幅改写演示文稿后必须做一次显式验证。目标是发现空白页、XML 损坏、内容截断、明显溢出、弱视觉层级和未验证输出。
小型已有页编辑也要做对应范围的验证:至少读取被改页面或全文 XML确认目标元素已更新且未破坏周边结构。 小型已有页编辑也要做对应范围的验证:至少读取被改页面或全文 XML确认目标元素已更新且未破坏周边结构。
@@ -13,7 +13,7 @@
5. 检查没有明显空白页、破损页、缺失标题或缺失主视觉。 5. 检查没有明显空白页、破损页、缺失标题或缺失主视觉。
6. 检查页面不是全部退化为标题加 bullet list。 6. 检查页面不是全部退化为标题加 bullet list。
7. 检查视觉层级:标题、主视觉、支撑信息三者可区分。 7. 检查视觉层级:标题、主视觉、支撑信息三者可区分。
8. 检查明显溢出和布局风险:重叠、越界、底部拥挤、长文本框、异常换行 8. 检查明显溢出和布局风险:重叠、越界、底部拥挤、长文本框。
9. 在最终回复中给出简短验证记录。 9. 在最终回复中给出简短验证记录。
回读命令: 回读命令:
@@ -34,9 +34,7 @@ python3 skills/lark-slides/scripts/xml_text_overlap_lint.py --input <presentatio
通过标准: 通过标准:
- `summary.error_count == 0`。任何 error 都必须先修复再交付。 - `summary.error_count == 0`。任何 error 都必须先修复再交付。
- `double_escaped_entity` warning 必须先修复再交付;它通常表示 HTML/XML 实体被二次转义,页面会显示 `&#...;` / `&nbsp;` / `&lt;` 这类字面量 - 当前工具只检查 XML well-formed 和文本元素之间的明显重叠;它不检查越界、文本高度不足、图文压盖、表格/图表压盖或底部拥挤
- 对异常换行、文本框高度不足等 wrap quality warning默认也应修复后再交付仅当它是普通正文的自然换行且用户明确允许时才可在验证记录中说明豁免原因。
- 当前工具检查 XML well-formed、文本元素之间的明显重叠以及部分规则化异常换行它不检查越界、图文压盖、表格/图表压盖或底部拥挤。
- 该工具不能替代页数核对、关键内容核对或真实视觉验收。 - 该工具不能替代页数核对、关键内容核对或真实视觉验收。
常见 code 的处理方向: 常见 code 的处理方向:
@@ -44,13 +42,7 @@ python3 skills/lark-slides/scripts/xml_text_overlap_lint.py --input <presentatio
| code | 含义 | 处理方式 | | code | 含义 | 处理方式 |
|------|------|----------| |------|------|----------|
| `xml_not_well_formed` | XML 语法错误或文本未转义 | 修复标签闭合、属性引号、`&` / `<` / `>` 转义 | | `xml_not_well_formed` | XML 语法错误或文本未转义 | 修复标签闭合、属性引号、`&` / `<` / `>` 转义 |
| `double_escaped_entity` | 文本中含二次转义实体,如 `&amp;#9679;``&amp;nbsp;``&amp;lt;` | 改成目标 Unicode 文本,如 `●`、空格、`<`;只对 XML 保留字符做一层必要转义 |
| `bbox_overlap` | 文本元素的估算绘制区域明显重叠 | 拉开文本坐标、缩小文本框/字号,或改成明确的分栏/分组结构 | | `bbox_overlap` | 文本元素的估算绘制区域明显重叠 | 拉开文本坐标、缩小文本框/字号,或改成明确的分栏/分组结构 |
| `text_word_split` / `text_phrase_split` | 中文词语或高频短语被异常拆行 | 增宽文本框、降低字号、改写短语或调整换行点,避免把词语/短语拆开 |
| `text_orphan_line` | 最后一行只有极短中文尾巴 | 增宽文本框、缩小字号或重排文本,让尾行形成可读短句 |
| `text_unnecessary_wrap` | 短标题或强调文本本应单行却换行 | 增宽文本框或缩小字号,优先保持单行 |
| `text_center_wrapped` | 非封面/金句场景的多行文本居中 | 改为左对齐,或调整为真正的封面/金句元素 |
| `text_box_too_short` | 文本框高度低于字号所需高度 | 增加文本框高度、降低字号或减少文本量 |
## Page Count And Structure ## Page Count And Structure
@@ -97,7 +89,6 @@ python3 skills/lark-slides/scripts/xml_text_overlap_lint.py --input <presentatio
优先修复这些明显风险: 优先修复这些明显风险:
- 正文或标签框高度不足,文本很可能被截断。 - 正文或标签框高度不足,文本很可能被截断。
- 标题、标签、卡片标题或强调文本出现异常换行,例如拆词、拆短语、短尾行或本应单行却换行。
- 多个主体元素在同一区域重叠,而不是有意叠加背景。 - 多个主体元素在同一区域重叠,而不是有意叠加背景。
- 重要内容越过画布边界,或贴近底部超过 `y=500` - 重要内容越过画布边界,或贴近底部超过 `y=500`
- 高密度页使用单个长 bullet list没有分栏、表格或分组。 - 高密度页使用单个长 bullet list没有分栏、表格或分组。

View File

@@ -9,7 +9,6 @@ import re
import sys import sys
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
from difflib import SequenceMatcher from difflib import SequenceMatcher
from html import unescape
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
@@ -18,13 +17,6 @@ class XmlTextOverlapLintError(Exception):
pass pass
TITLE_LIKE_TEXT_TYPES = {"title", "headline", "sub-headline", "card_title", "callout"}
CENTER_ALLOWED_TEXT_TYPES = {"title", "quote", "hero"}
DOUBLE_ESCAPED_ENTITY_PATTERN = re.compile(
r"&#(?:[0-9]+|x[0-9A-Fa-f]+);|&(?:lt|gt|quot|apos|nbsp);"
)
def fail(message: str) -> None: def fail(message: str) -> None:
raise XmlTextOverlapLintError(message) raise XmlTextOverlapLintError(message)
@@ -79,95 +71,10 @@ def strip_xml(value: str) -> str:
return re.sub(r"\s+", " ", stripped).strip() return re.sub(r"\s+", " ", stripped).strip()
def collapse_space(value: str) -> str:
return re.sub(r"\s+", " ", value).strip()
def chinese_char_count(value: str) -> int:
return len(re.findall(r"[\u4e00-\u9fff]", value))
def chinese_text(value: str) -> str:
return "".join(re.findall(r"[\u4e00-\u9fff]", value))
def xml_local_name(tag: str) -> str: def xml_local_name(tag: str) -> str:
return tag.rsplit("}", 1)[-1] if tag.startswith("{") else tag return tag.rsplit("}", 1)[-1] if tag.startswith("{") else tag
def preview_double_escaped_entity(text: str) -> str:
return unescape(text).replace("\xa0", " ")
def lint_double_escaped_entities(slide_xml: str) -> list[dict[str, Any]]:
try:
root = ET.fromstring(slide_xml)
except ET.ParseError:
return []
issues: list[dict[str, Any]] = []
seen: set[tuple[str, str]] = set()
for node in root.iter():
if xml_local_name(node.tag) != "content":
continue
for text in node.itertext():
if not text:
continue
for match in DOUBLE_ESCAPED_ENTITY_PATTERN.finditer(text):
entity = match.group(0)
context = collapse_space(text)
key = (entity, context)
if key in seen:
continue
seen.add(key)
is_numeric = entity.startswith("&#")
raw_entity = entity.replace("&", "&amp;", 1)
issues.append(
{
"level": "warning",
"code": "double_escaped_entity",
"message": f"Text contains a likely double-escaped XML/HTML entity: {raw_entity}",
"entity": raw_entity,
"context": context,
"preview": preview_double_escaped_entity(text),
"confidence": "high" if is_numeric else "medium",
"hint": (
"Use the intended literal Unicode text in slide XML, and only XML-escape reserved "
"characters once. For example, write «姓名», ●, or ✓ directly instead of "
"&amp;#171;姓名&amp;#187;, &amp;#9679;, or &amp;#10003;."
),
}
)
return issues
def extract_content_lines(content_xml: str) -> list[str]:
try:
root = ET.fromstring(f"<root>{content_xml}</root>")
except ET.ParseError:
text = strip_xml(content_xml)
return [text] if text else []
lines: list[str] = []
for content_node in root.iter():
if xml_local_name(content_node.tag) != "content":
continue
paragraph_lines: list[str] = []
for node in content_node.iter():
if xml_local_name(node.tag) != "p":
continue
line = collapse_space("".join(node.itertext()))
if line:
paragraph_lines.append(line)
if paragraph_lines:
lines.extend(paragraph_lines)
else:
line = collapse_space("".join(content_node.itertext()))
if line:
lines.append(line)
return lines
def extract_error_context(xml: str, line: int | None, column: int | None, radius: int = 40) -> str | None: def extract_error_context(xml: str, line: int | None, column: int | None, radius: int = 40) -> str | None:
if line is None or column is None: if line is None or column is None:
return None return None
@@ -232,23 +139,18 @@ def extract_elements(slide_xml: str) -> list[dict[str, Any]]:
height = extract_numeric_attribute(attrs, "height") height = extract_numeric_attribute(attrs, "height")
if all(value is not None for value in [x, y, width, height]): if all(value is not None for value in [x, y, width, height]):
font_size = float(extract_attribute(content, "fontSize") or extract_attribute(attrs, "fontSize") or 16) font_size = float(extract_attribute(content, "fontSize") or extract_attribute(attrs, "fontSize") or 16)
lines = extract_content_lines(content)
raw_text = "\n".join(lines)
elements.append( elements.append(
{ {
"id": f"shape-{len(elements) + 1}", "id": f"shape-{len(elements) + 1}",
"kind": "shape", "kind": "shape",
"type": extract_attribute(attrs, "type") or "shape", "type": extract_attribute(attrs, "type") or "shape",
"textType": extract_attribute(content, "textType"), "textType": extract_attribute(content, "textType"),
"textAlign": extract_attribute(content, "textAlign") or extract_attribute(attrs, "textAlign"),
"x": x, "x": x,
"y": y, "y": y,
"width": width, "width": width,
"height": height, "height": height,
"fontSize": font_size, "fontSize": font_size,
"text": strip_xml(content), "text": strip_xml(content),
"rawText": raw_text,
"lines": lines,
} }
) )
@@ -392,222 +294,9 @@ def should_flag_overlap(left: dict[str, Any], right: dict[str, Any]) -> bool:
return False return False
def estimate_text_width(text: str, font_size: float) -> float:
width = 0.0
for char in text:
if re.match(r"[\u4e00-\u9fff]", char):
width += font_size
elif char.isspace():
width += font_size * 0.32
else:
width += font_size * 0.55
return width
def estimated_rendered_line_count(element: dict[str, Any]) -> int:
return len(estimate_rendered_lines(element))
def estimate_rendered_lines(element: dict[str, Any]) -> list[str]:
lines = [line for line in element.get("lines", []) if line]
if not lines:
return []
font_size = float(element.get("fontSize") or 16)
usable_width = max(float(element["width"]) - 6, 1)
rendered_lines: list[str] = []
for line in lines:
current = ""
current_width = 0.0
for char in line:
char_width = estimate_text_width(char, font_size)
if current and current_width + char_width > usable_width:
rendered_lines.append(current)
current = char
current_width = char_width
continue
current += char
current_width += char_width
if current:
rendered_lines.append(current)
return rendered_lines
def has_insufficient_height_for_estimated_wrap(element: dict[str, Any], estimated_line_count: int) -> bool:
if estimated_line_count < 2:
return False
font_size = float(element.get("fontSize") or 16)
required_height = estimated_line_count * font_size * 1.12
return float(element["height"]) < required_height
def has_too_short_text_box(element: dict[str, Any]) -> bool:
text = element.get("text") or ""
if chinese_char_count(text) < 6:
return False
font_size = float(element.get("fontSize") or 16)
return float(element["height"]) < font_size * 0.95
def is_slash_separated_short_label(text: str) -> bool:
if "/" not in text:
return False
parts = [part.strip() for part in text.split("/") if part.strip()]
if len(parts) < 2:
return False
return chinese_char_count(text) <= 14 and all(chinese_char_count(part) <= 4 for part in parts)
def is_short_display_text_auto_wrapped(element: dict[str, Any], rendered_lines: list[str]) -> bool:
if len(element.get("lines", [])) != 1 or len(rendered_lines) != 2:
return False
if element.get("textType") in {"title", "caption"}:
return False
text = element.get("text") or ""
chinese_count = chinese_char_count(text)
if not (4 <= chinese_count <= 20):
return False
font_size = float(element.get("fontSize") or 16)
if font_size < 20:
return False
if not has_insufficient_height_for_estimated_wrap(element, len(rendered_lines)):
return False
return chinese_count / max(len(text), 1) >= 0.6
def build_wrap_issue(
code: str,
element: dict[str, Any],
message: str,
reason: str,
) -> dict[str, Any]:
return {
"level": "warning",
"code": code,
"element": element["id"],
"message": message,
"reason": reason,
"repair": {
"prefer_single_line": True,
"allow_font_shrink": True,
"max_shrink_ratio": 0.9,
"avoid_center_align": True,
},
}
def is_probable_cover_center_title(element: dict[str, Any]) -> bool:
text_type = element.get("textType")
if text_type == "quote":
return True
if text_type not in CENTER_ALLOWED_TEXT_TYPES:
return False
return element["x"] >= 120 and element["y"] >= 150 and element["width"] >= 300 and element["height"] >= 80
def lint_wrap_quality(element: dict[str, Any]) -> list[dict[str, Any]]:
if not is_text_element(element) or not has_text_content(element):
return []
lines = [line for line in element.get("lines", []) if line]
rendered_lines = estimate_rendered_lines(element)
estimated_line_count = len(rendered_lines)
if len(lines) < 2 and estimated_line_count < 2 and not has_too_short_text_box(element):
return []
issues: list[dict[str, Any]] = []
raw_text = element.get("rawText") or "\n".join(lines)
joined_chinese = chinese_text("".join(lines))
joined_chinese_count = chinese_char_count(joined_chinese)
font_size = float(element.get("fontSize") or 16)
last_line_chinese_count = chinese_char_count(lines[-1])
previous_text_chinese_count = chinese_char_count("".join(lines[:-1]))
if (
len(lines) == 2
and 1 <= last_line_chinese_count <= 3
and previous_text_chinese_count >= 10
):
issues.append(
build_wrap_issue(
"text_orphan_line",
element,
f"Last line is very short: {lines[-1]}",
"最后一行是过短尾行",
)
)
if has_too_short_text_box(element):
issues.append(
build_wrap_issue(
"text_box_too_short",
element,
f"Text box height is too short for font size: height={element['height']}, fontSize={font_size:g}",
"文本框高度低于字号所需高度,渲染后容易截断或压缩显示",
)
)
text_type = element.get("textType")
estimated_single_line_width = joined_chinese_count * font_size * 0.62
if (
text_type in TITLE_LIKE_TEXT_TYPES
and len(lines) >= 2
and 1 <= joined_chinese_count <= 20
and font_size >= 20
and font_size < 40
and chinese_char_count("".join(lines)) == len("".join(lines))
and element["width"] >= estimated_single_line_width
):
issues.append(
build_wrap_issue(
"text_unnecessary_wrap",
element,
f"Short title-like text wraps unnecessarily: {joined_chinese}",
"短标题或强调文本不超过 20 个中文字符却出现换行",
)
)
if is_short_display_text_auto_wrapped(element, rendered_lines):
issues.append(
build_wrap_issue(
"text_unnecessary_wrap",
element,
f"Short display text is likely to wrap in a one-line box: {strip_xml(raw_text)}",
"短展示文本被放入过窄且只够一行高度的文本框,渲染后容易异常换行",
)
)
if (
(element.get("textAlign") or "").lower() == "center"
and (
(len(lines) >= 2 and font_size >= 22)
or (
len(lines) == 1
and joined_chinese_count >= 8
and has_insufficient_height_for_estimated_wrap(element, estimated_line_count)
)
)
and text_type not in {"title", "sub-headline", "quote", "hero"}
and not is_probable_cover_center_title(element)
and not is_slash_separated_short_label(raw_text)
):
issues.append(
build_wrap_issue(
"text_center_wrapped",
element,
f"Centered multi-line text is hard to scan: {strip_xml(raw_text)}",
"非封面、非金句场景的多行文本使用居中对齐",
)
)
return issues
def lint_slide(slide_xml: str, slide_number: int) -> dict[str, Any]: def lint_slide(slide_xml: str, slide_number: int) -> dict[str, Any]:
elements = extract_elements(slide_xml) elements = extract_elements(slide_xml)
issues: list[dict[str, Any]] = lint_double_escaped_entities(slide_xml) issues: list[dict[str, Any]] = []
for element in elements:
issues.extend(lint_wrap_quality(element))
for index, left in enumerate(elements): for index, left in enumerate(elements):
for right in elements[index + 1 :]: for right in elements[index + 1 :]:

View File

@@ -96,65 +96,6 @@ class XmlTextOverlapLintTest(unittest.TestCase):
self.assertEqual(result["summary"]["error_count"], 0) self.assertEqual(result["summary"]["error_count"], 0)
self.assertNotIn("issues", result) self.assertNotIn("issues", result)
def test_lint_xml_reports_double_escaped_numeric_entities(self) -> None:
result = xml_text_overlap_lint.lint_xml(
"""
<slide xmlns="http://www.larkoffice.com/sml/2.0">
<data>
<shape type="text" topLeftX="80" topLeftY="80" width="420" height="90">
<content textType="body"><p>&amp;#171;姓名&amp;#187;</p><p>&amp;#9679; 占位符</p></content>
</shape>
</data>
</slide>
"""
)
issues = result["slides"][0]["issues"]
self.assertEqual(result["summary"]["warning_count"], 3)
self.assertTrue(all(issue["code"] == "double_escaped_entity" for issue in issues))
self.assertEqual(issues[0]["entity"], "&amp;#171;")
self.assertEqual(issues[0]["preview"], "«姓名»")
self.assertEqual(issues[0]["confidence"], "high")
self.assertEqual(issues[2]["entity"], "&amp;#9679;")
self.assertEqual(issues[2]["preview"], "● 占位符")
def test_lint_xml_reports_double_escaped_named_entities(self) -> None:
result = xml_text_overlap_lint.lint_xml(
"""
<slide xmlns="http://www.larkoffice.com/sml/2.0">
<data>
<shape type="text" topLeftX="80" topLeftY="80" width="420" height="90">
<content textType="body"><p>&amp;lt;字段&amp;gt;</p><p>A&amp;nbsp;B</p></content>
</shape>
</data>
</slide>
"""
)
issues = result["slides"][0]["issues"]
self.assertEqual(result["summary"]["warning_count"], 3)
self.assertEqual([issue["entity"] for issue in issues], ["&amp;lt;", "&amp;gt;", "&amp;nbsp;"])
self.assertEqual(issues[0]["preview"], "<字段>")
self.assertEqual(issues[2]["preview"], "A B")
self.assertEqual(issues[0]["confidence"], "medium")
def test_lint_xml_does_not_report_regular_ampersands_urls_or_space_entities(self) -> None:
result = xml_text_overlap_lint.lint_xml(
"""
<slide xmlns="http://www.larkoffice.com/sml/2.0">
<data>
<shape type="text" topLeftX="80" topLeftY="80" width="640" height="120">
<content textType="body">
<p>Q&amp;A</p>
<p><a href="https://example.com/?a=1&amp;b=2">link</a></p>
<p>A&#32;B&#9;C</p>
</content>
</shape>
</data>
</slide>
"""
)
self.assertEqual(result["summary"]["error_count"], 0)
self.assertEqual(result["summary"]["warning_count"], 0)
def test_lint_xml_accepts_chinese_full_width_punctuation(self) -> None: def test_lint_xml_accepts_chinese_full_width_punctuation(self) -> None:
result = xml_text_overlap_lint.lint_xml( result = xml_text_overlap_lint.lint_xml(
""" """

View File

@@ -1,230 +0,0 @@
# Copyright (c) 2026 Lark Technologies Pte. Ltd.
# SPDX-License-Identifier: MIT
from __future__ import annotations
import unittest
import xml_text_overlap_lint
def make_slide(shapes: str) -> str:
return f"""
<presentation xmlns="http://www.larkoffice.com/sml/2.0" width="960" height="540">
<slide xmlns="http://www.larkoffice.com/sml/2.0">
<data>{shapes}</data>
</slide>
</presentation>
"""
def text_shape(
lines: list[str],
*,
text_type: str = "body",
align: str = "left",
x: int = 120,
y: int = 120,
width: int = 360,
height: int = 120,
font_size: int = 28,
) -> str:
paragraphs = "".join(f"<p>{line}</p>" for line in lines)
return f"""
<shape type="text" topLeftX="{x}" topLeftY="{y}" width="{width}" height="{height}">
<content textType="{text_type}" textAlign="{align}" fontSize="{font_size}">
{paragraphs}
</content>
</shape>
"""
class XmlTextOverlapWrapLintTest(unittest.TestCase):
def lint_one(self, shape_xml: str) -> dict:
result = xml_text_overlap_lint.lint_xml(make_slide(shape_xml))
self.assertEqual(result["summary"]["error_count"], 0)
return result
def issue_codes(self, result: dict) -> list[str]:
return [
issue["code"]
for slide in result["slides"]
for issue in slide["issues"]
]
def assertWarnsCode(self, shape_xml: str, code: str) -> None:
result = self.lint_one(shape_xml)
self.assertIn(code, self.issue_codes(result))
self.assertGreaterEqual(result["summary"]["warning_count"], 1)
def assertDoesNotWarnCode(self, shape_xml: str, code: str) -> None:
result = self.lint_one(shape_xml)
self.assertNotIn(code, self.issue_codes(result))
def test_wrap_lint_detects_orphan_line(self) -> None:
cases = [
["把排版看成一套可维护的规则", "系统"],
["为什么大多数企业知识库最终都会", "失效"],
["让内容生产流程持续保持稳定的", "质量"],
["复杂协作权限需要清晰可读的继承", "边界"],
["自动化检查应该优先发现低级排版", "问题"],
]
for lines in cases:
with self.subTest(lines=lines):
self.assertWarnsCode(text_shape(lines, width=520), "text_orphan_line")
def test_wrap_lint_allows_orphan_line_controls(self) -> None:
cases = [
["把排版看成", "一套可维护的规则系统"],
["为什么大多数企业知识库", "最终都会失效"],
["复杂协作权限需要", "清晰可读的继承边界"],
["自动化检查应该", "优先发现低级排版问题"],
["标题换行质量", "直接影响读者理解效率"],
]
for lines in cases:
with self.subTest(lines=lines):
self.assertDoesNotWarnCode(text_shape(lines, width=520), "text_orphan_line")
def test_wrap_lint_allows_multiline_body_with_short_final_line(self) -> None:
shape_xml = text_shape(
["按行业、阶段、投资年份分层;剔除信息不可得或标签不完整样本。"],
align="left",
width=146,
height=42,
font_size=10,
)
self.assertDoesNotWarnCode(shape_xml, "text_orphan_line")
def test_wrap_lint_detects_unnecessary_wrap_in_title_like_text(self) -> None:
cases = [
["减少手工", "格式"],
["内容", "生产"],
["智能", "生成"],
["质量", "检查"],
["边界", "规则"],
]
for lines in cases:
with self.subTest(lines=lines):
self.assertWarnsCode(text_shape(lines, text_type="headline", width=420), "text_unnecessary_wrap")
def test_wrap_lint_allows_unnecessary_wrap_controls(self) -> None:
cases = [
["减少手工格式"],
["内容生产"],
["智能生成"],
["质量检查"],
["边界规则"],
]
for lines in cases:
with self.subTest(lines=lines):
self.assertDoesNotWarnCode(text_shape(lines, text_type="headline", width=420), "text_unnecessary_wrap")
def test_wrap_lint_detects_short_display_text_that_will_auto_wrap(self) -> None:
cases = [
"模型、平台、数据、研究",
"产业协同能力研究",
"接口边界安全研究",
"投后监测策略研究",
"评分稳定性复盘研究",
]
for text in cases:
with self.subTest(text=text):
self.assertWarnsCode(
text_shape([text], width=190, height=26, font_size=26),
"text_unnecessary_wrap",
)
def test_wrap_lint_allows_body_text_that_will_auto_wrap(self) -> None:
shape_xml = text_shape(
["按行业、阶段、投资年份分层;剔除信息不可得或标签不完整样本。"],
width=146,
height=42,
font_size=10,
)
self.assertDoesNotWarnCode(shape_xml, "text_unnecessary_wrap")
def test_wrap_lint_detects_center_wrapped_text(self) -> None:
cases = [
["下一代智能", "办公系统"],
["企业知识库", "治理方案"],
["自动化排版", "质量基线"],
["协作权限", "继承模型"],
["内容生产", "智能流程"],
]
for lines in cases:
with self.subTest(lines=lines):
self.assertWarnsCode(text_shape(lines, align="center", y=150), "text_center_wrapped")
def test_wrap_lint_detects_center_text_that_will_auto_wrap(self) -> None:
shape_xml = text_shape(
["平台价值:让数据、模型和流程在同一界面被调用、解释和追踪。"],
align="center",
width=248,
height=12,
font_size=10,
)
self.assertWarnsCode(shape_xml, "text_center_wrapped")
def test_wrap_lint_allows_center_wrapped_controls(self) -> None:
cases = [
text_shape(["下一代智能办公系统"], align="center"),
text_shape(["企业知识库治理方案"], align="center"),
text_shape(["自动化排版质量基线"], align="left"),
text_shape(["封面主标题", "副标题"], text_type="title", align="center", y=210),
text_shape(["金句内容", "保持居中"], text_type="quote", align="center"),
text_shape(["企业筛选 / 排序 / 尽调建议"], align="center", width=132, height=20, font_size=10),
text_shape(["经营异动 / 风险预警 / 里程碑"], align="center", width=136, height=12, font_size=10),
text_shape(
["建议采用 Top-N 命中率、风险预警召回率和评分稳定性三类指标,不只看单一准确率。"],
align="left",
width=146,
height=42,
font_size=10,
),
]
for shape_xml in cases:
with self.subTest(shape=shape_xml):
self.assertDoesNotWarnCode(shape_xml, "text_center_wrapped")
def test_wrap_lint_detects_text_box_too_short(self) -> None:
cases = [
"REST API / 批量文件 / 定时同步",
"鉴权、审计、脱敏与最小权限",
"优先适配现有系统,减少重复建设",
"服务化部署、权限隔离、日志留痕",
"试运行三个月,终验后三年维保",
]
for text in cases:
with self.subTest(text=text):
self.assertWarnsCode(
text_shape([text], width=280, height=2, font_size=18),
"text_box_too_short",
)
def test_wrap_lint_allows_text_box_with_sufficient_height(self) -> None:
cases = [
"REST API / 批量文件 / 定时同步",
"鉴权、审计、脱敏与最小权限",
"优先适配现有系统,减少重复建设",
"11",
"KR1",
]
for text in cases:
with self.subTest(text=text):
self.assertDoesNotWarnCode(
text_shape([text], width=450, height=48, font_size=18),
"text_box_too_short",
)
def test_wrap_lint_keeps_bbox_overlap_detection(self) -> None:
result = xml_text_overlap_lint.lint_xml(
make_slide(
text_shape(["Title"], text_type="title", x=80, y=80, width=300, height=60)
+ text_shape(["Body"], text_type="body", x=80, y=80, width=300, height=80)
)
)
self.assertEqual(result["summary"]["error_count"], 1)
self.assertIn("bbox_overlap", self.issue_codes(result))
if __name__ == "__main__":
unittest.main()

View File

@@ -51,7 +51,6 @@ metadata:
| [`+get-my-tasks`](references/lark-task-get-my-tasks.md) | List tasks assigned to me | | [`+get-my-tasks`](references/lark-task-get-my-tasks.md) | List tasks assigned to me |
| [`+get-related-tasks`](references/lark-task-get-related-tasks.md) | list tasks related to me | | [`+get-related-tasks`](references/lark-task-get-related-tasks.md) | list tasks related to me |
| [`+search`](references/lark-task-search.md) | search tasks | | [`+search`](references/lark-task-search.md) | search tasks |
| [`+subscribe-event`](references/lark-task-subscribe-event.md) | subscribe to task events |
| [`+upload-attachment`](references/lark-task-upload-attachment.md) | upload a local file as an attachment to a task | | [`+upload-attachment`](references/lark-task-upload-attachment.md) | upload a local file as an attachment to a task |
| [`+tasklist-create`](references/lark-task-tasklist-create.md) | create a tasklist and optionally add tasks | | [`+tasklist-create`](references/lark-task-tasklist-create.md) | create a tasklist and optionally add tasks |
| [`+tasklist-search`](references/lark-task-tasklist-search.md) | search tasklists | | [`+tasklist-search`](references/lark-task-tasklist-search.md) | search tasklists |

View File

@@ -1,86 +0,0 @@
# task +subscribe-event
> **Prerequisites:** Please read `../lark-shared/SKILL.md` to understand authentication, global parameters, and security rules.
>
> **⚠️ Note:** This API supports both `user` and `bot` identities. Use `user` to subscribe the current user's accessible tasks; use `bot` to subscribe tasks the **application is responsible for**.
Subscribe task update events with the current identity.
This shortcut is different from `event +subscribe`:
- `task +subscribe-event` registers task-event access for the **current identity**
- with `--as user`, it subscribes the **current user** to task events for tasks they created, are responsible for, or follow
- with `--as bot`, it subscribes using the **application identity** for tasks the application is responsible for
The task event type is:
```text
task.task.update_user_access_v2
```
Within this event, task changes are represented by commit types (string values). Deduped list:
```text
task_assignees_update
task_completed_update
task_create
task_deleted
task_desc_update
task_followers_update
task_reminders_update
task_start_due_update
task_summary_update
```
Event payload shape (example):
```json
{
"event_id": "evt_xxx",
"event_types": ["task_summary_update"],
"task_guid": "task_guid_xxx",
"timestamp": "1775793266152",
"type": "task.task.update_user_access_v2"
}
```
- `type`: event type, should be `task.task.update_user_access_v2`
- `event_id`: unique event id (useful for dedup)
- `event_types`: list of commit types (see the deduped list above)
- `task_guid`: the task GUID that changed
- `timestamp`: event timestamp (ms)
In practice, this means:
- with `--as user`, the subscribed user can receive updates for tasks visible to them through authorship, assignment, or following
- with `--as bot`, the subscription covers tasks the application is responsible for
To actually receive the subscribed events, use the standard event WebSocket receiver:
```bash
lark-cli event +subscribe --event-types task.task.update_user_access_v2 --compact --quiet
```
The full flow is:
1. Register the subscription with `lark-cli task +subscribe-event [--as user|bot]`
2. Receive those events with `lark-cli event +subscribe --event-types task.task.update_user_access_v2 ...`
## Recommended Commands
```bash
lark-cli task +subscribe-event
```
# Subscribe with app identity
lark-cli task +subscribe-event --as bot
## Parameters
This shortcut has no additional parameters.
## Workflow
1. Confirm whether the user wants to subscribe with `user` identity or `bot` identity.
2. Execute `lark-cli task +subscribe-event`
3. Report whether the subscription succeeded, and clarify which identity the subscription applies to.
> [!CAUTION]
> This is a **Write Operation** -- You must confirm the user's intent before executing.

View File

@@ -12,7 +12,7 @@ metadata:
> [!IMPORTANT] > [!IMPORTANT]
> - 运行 `lark-cli --version`,确认可用,无需询问用户。 > - 运行 `lark-cli --version`,确认可用,无需询问用户。
> - 运行 `npx -y @larksuite/whiteboard-cli@^0.2.11 -v`,确认可用,无需询问用户。 > - 运行 `npx -y @larksuite/whiteboard-cli@^0.2.12 -v`,确认可用,无需询问用户。
**CRITICAL — 开始前 MUST 先用 Read 工具读取 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),其中包含认证、权限处理** **CRITICAL — 开始前 MUST 先用 Read 工具读取 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md),其中包含认证、权限处理**
@@ -24,11 +24,11 @@ metadata:
| 用户需求 | 行动 | | 用户需求 | 行动 |
|-----------------------------------------|-----------------------------------------------------------------------------------------------| |-----------------------------------------|-----------------------------------------------------------------------------------------------|
| 查看画板内容 / 导出图片 | [`+query --output_as image`](references/lark-whiteboard-query.md) | | 查看画板内容 / 导出图片 / 导出 SVG 矢量图 | [`+query --output_as image/svg`](references/lark-whiteboard-query.md) |
| 获取画板的 Mermaid/PlantUML 代码 | [`+query --output_as code`](references/lark-whiteboard-query.md) | | 获取画板的 Mermaid/PlantUML 代码 | [`+query --output_as code`](references/lark-whiteboard-query.md) |
| 检查画板是否由代码绘制 | [`+query --output_as code`](references/lark-whiteboard-query.md) | | 检查画板是否由代码绘制 | [`+query --output_as code`](references/lark-whiteboard-query.md) |
| 修改节点文字/颜色(简单改动) | `+query --output_as raw` → 手动改 JSON → `+update --input_format raw` | | 仅微调节点文字/颜色 | `+query --output_as raw` → 手动改 JSON → `+update --input_format raw` |
| 用户**已提供** Mermaid/PlantUML 代码,或明确指定用该格式 | 自己生成/使用代码 → [`+update --input_format mermaid/plantuml`](references/lark-whiteboard-update.md) | | 用户**已提供** Mermaid/PlantUML/SVG 代码,或明确指定用该格式 | 自己生成/使用代码 → [`+update --input_format mermaid/plantuml/svg`](references/lark-whiteboard-update.md) |
| 新建/创作复杂图表(架构/流程/组织等) | → **[§ 创作 Workflow](references/lark-whiteboard-workflow.md#创作-workflow)** | | 新建/创作复杂图表(架构/流程/组织等) | → **[§ 创作 Workflow](references/lark-whiteboard-workflow.md#创作-workflow)** |
| 修改/重绘已有画板 | → **[§ 修改 Workflow](references/lark-whiteboard-workflow.md#修改-workflow)** | | 修改/重绘已有画板 | → **[§ 修改 Workflow](references/lark-whiteboard-workflow.md#修改-workflow)** |
@@ -36,8 +36,8 @@ metadata:
| Shortcut | 说明 | | Shortcut | 说明 |
|---|---| |---|---|
| [`+query`](references/lark-whiteboard-query.md) | 查询画板,导出为预览图片、代码或原始节点结构 | | [`+query`](references/lark-whiteboard-query.md) | 查询画板,导出为预览图片、SVG 矢量图、代码或原始节点结构 |
| [`+update`](references/lark-whiteboard-update.md) | 更新画板,支持 PlantUML、Mermaid 或 OpenAPI 原生格式 | | [`+update`](references/lark-whiteboard-update.md) | 更新画板,支持 PlantUML、Mermaid、SVG 或 OpenAPI 原生格式 |
--- ---

View File

@@ -336,7 +336,7 @@ DSL 的语法是严格白名单,不能写原生 CSS 属性(不支持 `alignS
先出骨架图导出坐标,再基于坐标补充连线和注解: 先出骨架图导出坐标,再基于坐标补充连线和注解:
```bash ```bash
npx -y @larksuite/whiteboard-cli@^0.2.11 -i skeleton.json -o step1.png -l coords.json npx -y @larksuite/whiteboard-cli@^0.2.12 -i skeleton.json -o step1.png -l coords.json
``` ```
`coords.json` 包含每个带 id 节点的精确坐标absX, absY, width, height `coords.json` 包含每个带 id 节点的精确坐标absX, absY, width, height

View File

@@ -272,14 +272,14 @@ SVG 通过 `image/svg+xml` Blob 加载到画布,**不在 HTML DOM 中**,因
x?: number; y?: number; x?: number; y?: number;
width?: WBSizeValue; // 默认 48 width?: WBSizeValue; // 默认 48
height?: WBSizeValue; // 默认 48保持正方形 height?: WBSizeValue; // 默认 48保持正方形
name: string; // 图标名称,从 npx -y @larksuite/whiteboard-cli@^0.2.11 --icons 输出中选取 name: string; // 图标名称,从 npx -y @larksuite/whiteboard-cli@^0.2.12 --icons 输出中选取
color?: string; // 可选颜色覆盖hex 格式如 '#FF6600' color?: string; // 可选颜色覆盖hex 格式如 '#FF6600'
} }
``` ```
**获取可用图标**:规划好内容和布局后,运行以下命令查看所有可用图标名,从中选取: **获取可用图标**:规划好内容和布局后,运行以下命令查看所有可用图标名,从中选取:
```bash ```bash
npx -y @larksuite/whiteboard-cli@^0.2.11 --icons npx -y @larksuite/whiteboard-cli@^0.2.12 --icons
``` ```
用法: 用法:

View File

@@ -2,20 +2,21 @@
> **前置条件:** 先阅读 [`../../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 了解认证、全局参数和安全规则。 > **前置条件:** 先阅读 [`../../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 了解认证、全局参数和安全规则。
查询画板内容,支持导出为预览图片、提取 PlantUML/Mermaid 代码,或获取飞书 OpenAPI 原生画板节点格式。 查询画板内容,支持导出为预览图片、SVG 矢量图、提取 PlantUML/Mermaid 代码,或获取飞书 OpenAPI 原生画板节点格式。
## 参数 ## 参数
| 参数 | 必填 | 说明 | | 参数 | 必填 | 说明 |
|----------------------|----|------------------------------------------------------------------------| |----------------------|----|------------------------------------------------------------------------|
| `--whiteboard-token` | 是 | 画板 token需要拥有画板的读权限 | | `--whiteboard-token` | 是 | 画板 token需要拥有画板的读权限 |
| `--output_as` | 是 | 输出格式:`image`(预览图片)、`code`PlantUML/Mermaid 代码)、`raw`OpenAPI 原生画板节点格式) | | `--output_as` | 是 | 输出格式:`image`(预览图片)、`svg`SVG 矢量图)、`code`PlantUML/Mermaid 代码)、`raw`OpenAPI 原生画板节点格式) |
| `--output` | 否 | 输出路径。当 `--output_as image` 时必填;当 `--output_as code/raw` 时可选,不填则直接输出到终端 | | `--output` | 否 | 输出路径。当 `--output_as image` 时必填;当 `--output_as svg/code/raw` 时可选,不填则直接输出到终端 |
| `--overwrite` | 否 | 覆盖已存在的文件,默认为 false | | `--overwrite` | 否 | 覆盖已存在的文件,默认为 false |
## 输出格式 ## 输出格式
- `image`:预览图片 - `image`:预览图片
- `svg`:导出画板为标准 SVG 矢量图。可用于 SVG 编辑后回写画板(见 [`routes/svg-edit.md`](../routes/svg-edit.md))。注意:导出为纯视觉快照,思维导图层级、表格结构、连接器绑定等语义信息会丢失。
- `code`PlantUML/Mermaid 代码。仅限画板内有且仅有一个 PlantUML/Mermaid 图时,才可导出代码,否则会在返回值中告知不存在/有多个节点。 - `code`PlantUML/Mermaid 代码。仅限画板内有且仅有一个 PlantUML/Mermaid 图时,才可导出代码,否则会在返回值中告知不存在/有多个节点。
- `raw`:飞书 OpenAPI 原生画板节点格式。这一 json 格式不适合直接编辑复杂布局或内容,建议仅限于需要修改简单的文本内容/颜色等细节时使用。需要进行更复杂的设计/修改时,建议参考 [§ 渲染 & 写入画板](../SKILL.md#渲染--写入画板)。 - `raw`:飞书 OpenAPI 原生画板节点格式。这一 json 格式不适合直接编辑复杂布局或内容,建议仅限于需要修改简单的文本内容/颜色等细节时使用。需要进行更复杂的设计/修改时,建议参考 [§ 渲染 & 写入画板](../SKILL.md#渲染--写入画板)。
@@ -38,7 +39,17 @@ lark-cli whiteboard +query \
--output_as code --output_as code
``` ```
### 示例 3导出画板原始节点结构到文件 ### 示例 3导出画板为 SVG 矢量图
```bash
lark-cli whiteboard +query \
--whiteboard-token "wbcnxxxxxxxx" \
--output_as svg \
--output ./whiteboard.svg \
--as user
```
### 示例 4导出画板原始节点结构到文件
```bash ```bash
lark-cli whiteboard +query \ lark-cli whiteboard +query \

View File

@@ -2,11 +2,12 @@
> **前置条件:** 先阅读 [`../../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 了解认证、全局参数和安全规则。 > **前置条件:** 先阅读 [`../../lark-shared/SKILL.md`](../../lark-shared/SKILL.md) 了解认证、全局参数和安全规则。
更新画板内容,支持种输入格式: 更新画板内容,支持种输入格式:
- `raw`:飞书 OpenAPI 原生画板节点格式,不推荐直接编辑。 - `raw`:飞书 OpenAPI 原生画板节点格式,不推荐直接编辑。
- `plantuml`PlantUML 代码 - `plantuml`PlantUML 代码
- `mermaid`Mermaid 代码 - `mermaid`Mermaid 代码
- `svg`SVG 文本
输入内容可以通过管道从 stdin 读取,或通过 `--source` 指定文件。 输入内容可以通过管道从 stdin 读取,或通过 `--source` 指定文件。
@@ -18,7 +19,7 @@
| `--idempotent-token` | 否 | 幂等 token确保更新操作幂等最小长度 10 个字符 | | `--idempotent-token` | 否 | 幂等 token确保更新操作幂等最小长度 10 个字符 |
| `--overwrite` | 否 | 覆盖更新,在更新前删除所有现有内容,默认为 false | | `--overwrite` | 否 | 覆盖更新,在更新前删除所有现有内容,默认为 false |
| `--source` | 是 | 输入画板内容,支持使用 `@path` 从文件读取,或 `-` 从 stdin 读取 | | `--source` | 是 | 输入画板内容,支持使用 `@path` 从文件读取,或 `-` 从 stdin 读取 |
| `--input_format` | 否 | 输入格式:`raw``plantuml``mermaid`,默认为 `raw` | | `--input_format` | 否 | 输入格式:`raw``plantuml``mermaid``svg`,默认为 `raw` |
### 以 raw (OpenAPI 原生画板节点格式) 创作 ### 以 raw (OpenAPI 原生画板节点格式) 创作
@@ -74,7 +75,7 @@ whiteboard-cli 工具的具体用法请参考 [§ 渲染 & 写入画板](../SKIL
```bash ```bash
# 使用 whiteboard-cli 生成 OpenAPI 格式并通过管道传递 # 使用 whiteboard-cli 生成 OpenAPI 格式并通过管道传递
npx -y @larksuite/whiteboard-cli@^0.2.11 -i <产物文件> --to openapi --format json \ npx -y @larksuite/whiteboard-cli@^0.2.12 -i <产物文件> --to openapi --format json \
| lark-cli whiteboard +update \ | lark-cli whiteboard +update \
--whiteboard-token <画板Token> \ --whiteboard-token <画板Token> \
--source - --input_format raw \ --source - --input_format raw \
@@ -88,7 +89,7 @@ whiteboard-cli 工具的具体用法请参考 [§ 渲染 & 写入画板](../SKIL
```bash ```bash
# 生成 OpenAPI 格式到文件 # 生成 OpenAPI 格式到文件
npx -y @larksuite/whiteboard-cli@^0.2.11 -i <DSL 文件> --to openapi --format json -o ./temp.json npx -y @larksuite/whiteboard-cli@^0.2.12 -i <DSL 文件> --to openapi --format json -o ./temp.json
# 从文件读取并更新 # 从文件读取并更新
lark-cli whiteboard +update \ lark-cli whiteboard +update \
@@ -98,3 +99,24 @@ lark-cli whiteboard +update \
--source @./temp.json \ --source @./temp.json \
--overwrite --as user --overwrite --as user
``` ```
### 示例 5使用 SVG 写入画板(从文件读取)
适用于从零创建(直接写入 SVG和编辑现有画板编辑工作流详见 [`../routes/svg-edit.md`](../routes/svg-edit.md))。
```bash
# 编写或导出 SVG 文件
cat > diagram.svg << 'EOF'
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100">
<rect x="10" y="10" width="80" height="40" fill="#4A90E2"/>
<text x="50" y="35" text-anchor="middle" fill="#fff">Hello</text>
</svg>
EOF
# 从文件读取并更新
lark-cli whiteboard +update \
--whiteboard-token <画板Token> \
--input_format svg \
--source @./diagram.svg \
--overwrite --as user
```

View File

@@ -29,9 +29,11 @@
+query --output_as code +query --output_as code
├─ 返回 Mermaid/PlantUML 代码 ├─ 返回 Mermaid/PlantUML 代码
│ → 在原代码上修改 → +update --input_format mermaid/plantuml │ → 在原代码上修改 → +update --input_format mermaid/plantuml
├─ 无代码DSL 或其他方式绘制的画板) ├─ 无代码(SVG/DSL 或其他方式绘制的画板)
│ ├─ 只改文字/颜色 → +query --output_as raw → 手动改 JSON → +update --input_format raw │ ├─ 需纯新增(思维导图、流程图、时序图、类图、饼图、甘特图)图表节点
└─ 重绘/结构调整 → +query --output_as image → 看图后进入 [§ 渲染 & 写入画板] → +query --output_as image → 看图 → +query --output_as raw → 确定新节点坐标和层级 → [§ 渲染 & 写入画板]
│ └─ 其他改动(几何变动/增删元素/结构调整/混合编辑等)
│ → [`../routes/svg-edit.md`](../routes/svg-edit.md)(视觉高保真还原,大部分场景适用)
└─ 用户有明确要求 → 以用户要求优先 └─ 用户有明确要求 → 以用户要求优先
``` ```
@@ -79,7 +81,7 @@ diagram.png ← 渲染结果
> 因此,若需要整体更新画板内容,需携带 --overwrite flag 覆盖式更新。 > 因此,若需要整体更新画板内容,需携带 --overwrite flag 覆盖式更新。
```bash ```bash
npx -y @larksuite/whiteboard-cli@^0.2.11 -i <产物文件> --to openapi --format json \ npx -y @larksuite/whiteboard-cli@^0.2.12 -i <产物文件> --to openapi --format json \
| lark-cli whiteboard +update \ | lark-cli whiteboard +update \
--whiteboard-token <Token> \ --whiteboard-token <Token> \
--source - --input_format raw \ --source - --input_format raw \

View File

@@ -13,7 +13,7 @@ Step 1: 路由 & 读取知识
Step 2: 生成完整 DSL含颜色 Step 2: 生成完整 DSL含颜色
- 按 content.md 规划信息量和分组 - 按 content.md 规划信息量和分组
- 按 layout.md 选择布局模式和间距 - 按 layout.md 选择布局模式和间距
- 推荐使用图标让图表更直观,运行 `npx -y @larksuite/whiteboard-cli@^0.2.11 --icons` 查看可用图标 - 推荐使用图标让图表更直观,运行 `npx -y @larksuite/whiteboard-cli@^0.2.12 --icons` 查看可用图标
- 按 style.md 上色(用户没指定时用默认经典色板) - 按 style.md 上色(用户没指定时用默认经典色板)
- 按 schema.md 语法输出完整 JSON - 按 schema.md 语法输出完整 JSON
- 连线参考 connectors.md排版参考 typography.md - 连线参考 connectors.md排版参考 typography.md
@@ -25,12 +25,12 @@ Step 2: 生成完整 DSL含颜色
Step 3: 渲染 & 审查 → 交付 Step 3: 渲染 & 审查 → 交付
- 渲染前自查(见下方检查清单) - 渲染前自查(见下方检查清单)
- 渲染 PNG仅用于预览验证不是最终产物npx -y @larksuite/whiteboard-cli@^0.2.11 -i diagram.json -o diagram.png - 渲染 PNG仅用于预览验证不是最终产物npx -y @larksuite/whiteboard-cli@^0.2.12 -i diagram.json -o diagram.png
- 检查:信息完整?布局合理?配色协调?文字无截断?连线无交叉? - 检查:信息完整?布局合理?配色协调?文字无截断?连线无交叉?
- 有问题 → 按症状表修复 → 重新渲染(最多 2 轮) - 有问题 → 按症状表修复 → 重新渲染(最多 2 轮)
- 2 轮后仍有严重问题 → 考虑走 Mermaid 路径兜底 - 2 轮后仍有严重问题 → 考虑走 Mermaid 路径兜底
- 写入画板:用 whiteboard-cli 将 diagram.json 转换为 OpenAPI 格式并 pipe 给 +update - 写入画板:用 whiteboard-cli 将 diagram.json 转换为 OpenAPI 格式并 pipe 给 +update
npx -y @larksuite/whiteboard-cli@^0.2.11 -i diagram.json --to openapi --format json \ npx -y @larksuite/whiteboard-cli@^0.2.12 -i diagram.json --to openapi --format json \
| lark-cli whiteboard +update --whiteboard-token <board_token> \ | lark-cli whiteboard +update --whiteboard-token <board_token> \
--source - --input_format raw --idempotent-token <时间戳+标识> --as user --source - --input_format raw --idempotent-token <时间戳+标识> --as user
→ 完整 dry-run / 确认流程见 SKILL.md [§ 写入画板](../SKILL.md#写入画板) → 完整 dry-run / 确认流程见 SKILL.md [§ 写入画板](../SKILL.md#写入画板)

View File

@@ -16,10 +16,10 @@ Step 3: 渲染验证 & 写入画板 & 交付
1. 创建产物目录 ./diagrams/YYYY-MM-DDTHHMMSS/ 1. 创建产物目录 ./diagrams/YYYY-MM-DDTHHMMSS/
2. 保存为 diagram.mmd 2. 保存为 diagram.mmd
3. 渲染仅用于预览验证PNG 不是最终产物): 3. 渲染仅用于预览验证PNG 不是最终产物):
npx -y @larksuite/whiteboard-cli@^0.2.11 -i diagram.mmd -o diagram.png npx -y @larksuite/whiteboard-cli@^0.2.12 -i diagram.mmd -o diagram.png
4. 审查 PNG有问题修改后重新渲染最多 2 轮) 4. 审查 PNG有问题修改后重新渲染最多 2 轮)
5. 写入画板:用 whiteboard-cli 将 diagram.mmd 转换为 OpenAPI 格式并 pipe 给 +update 5. 写入画板:用 whiteboard-cli 将 diagram.mmd 转换为 OpenAPI 格式并 pipe 给 +update
npx -y @larksuite/whiteboard-cli@^0.2.11 -i diagram.mmd --to openapi --format json \ npx -y @larksuite/whiteboard-cli@^0.2.12 -i diagram.mmd --to openapi --format json \
| lark-cli whiteboard +update --whiteboard-token <board_token> \ | lark-cli whiteboard +update --whiteboard-token <board_token> \
--source - --input_format raw --idempotent-token <时间戳+标识> --as user --source - --input_format raw --idempotent-token <时间戳+标识> --as user
→ 完整 dry-run / 确认流程见 SKILL.md [§ 写入画板](../SKILL.md#写入画板) → 完整 dry-run / 确认流程见 SKILL.md [§ 写入画板](../SKILL.md#写入画板)

View File

@@ -0,0 +1,85 @@
# SVG 编辑路径
通过导出画板的 SVG → 编辑 SVG → 回写画板,实现对已有画板的可视化编辑。
---
## ⚠️ 有损性警告
SVG 导出是**纯视觉快照**,再次导入后画板语义(思维导图层级/表格结构/连线绑定/容器类型/mention/节点 ID/锁定/评论)会丢失。
**保留的信息**:形状几何(位置/大小/路径)、文本内容与基本格式(字号/粗体/斜体/对齐)、填充色/描边色/透明度(线性渐变降级为第一个 stop-color 纯色)、连接器路径形状与箭头样式、`<g>` 嵌套的基本分组关系≥2 子元素时重建为 DirectFocusGroup
---
## Workflow
### 0. 用户确认(强制)
在执行任何编辑前,**必须**向用户说明:
> SVG 编辑只保证视觉层面对齐,画板语义(层级/节点类型/思维导图结构/表格结构/连线绑定/容器类型/mention 等)将不可恢复,是否继续?
**用户未确认前不得执行后续步骤。**
### 1. 导出当前画板 SVG
```bash
lark-cli whiteboard +query \
--whiteboard-token <TOKEN> \
--output_as svg \
--output <dir>/original.svg \
--as user
```
### 2. 编辑 SVG
在导出的 SVG 上进行修改。参考 [`svg.md` § 画板怎么处理 SVG](./svg.md#画板怎么处理-svg) 了解可识别元素与不支持的装饰特性。
**技术约束**
- 新增文字必须用 `<text>`(不是 `<path>`容器宽度留够CJK ≈ 1em / Latin ≈ 0.6em
- 避免 `skewX` / `skewY` / `matrix(...)` 变换
- 禁止使用 `<radialGradient>` / `<filter>` / `<pattern>` / `<clipPath>` / `<mask>`
**编辑原则**(区别于从零创作):
- **风格一致**:新增/修改元素应匹配导出 SVG 中已有的配色、字号、线宽、间距风格,不引入突兀的视觉差异
- **最小改动**:只修改用户要求的部分,不主动"优化"或重排无关区域
- **结构稳定**:尽量保留原有 `<g>` 层级结构,避免不必要的重组导致分组关系变化
- **连线协调**:连接器端点绑定已丢失,若移动了形状,必须手动同步调整视觉上连接到该形状的 connector path 端点坐标,否则连线会"断开"
- **内部引用完整性**:不要随意删改 `<defs>` 中被 `url(#id)` 引用的元素(`<marker>`/`<linearGradient>` 等)或修改其 `id`,否则引用方会失效
### 3. 渲染审查
```bash
# 渲染 PNG 预览
npx -y @larksuite/whiteboard-cli@^0.2.12 -i <dir>/edited.svg -o <dir>/edited.png -f svg
# 几何检查text-overflow / node-overlap
npx -y @larksuite/whiteboard-cli@^0.2.12 -i <dir>/edited.svg -f svg --check
```
结合 PNG 视觉效果和 `--check` 报告进行调整,有问题则修改 SVG 后重新渲染(最多 2 轮)。
- SVG 本地渲染预览时,画板中的图片因 session 原因无法正常显示,属于预期内的行为。
### 4. 写回画板
`--overwrite` 会清空原画板内容,确认后再执行
```bash
# dry-run 探测
lark-cli whiteboard +update \
--whiteboard-token <TOKEN> \
--source @<dir>/edited.svg \
--input_format svg \
--idempotent-token <10+字符唯一串> \
--overwrite --dry-run --as user
# 用户确认后执行
lark-cli whiteboard +update \
--whiteboard-token <TOKEN> \
--source @<dir>/edited.svg \
--input_format svg \
--idempotent-token <10+字符唯一串> \
--overwrite --as user
```

View File

@@ -30,12 +30,12 @@
``` ```
建目录 ./diagrams/YYYY-MM-DDTHHMMSS/ (例:./diagrams/2026-04-15T143022/) 建目录 ./diagrams/YYYY-MM-DDTHHMMSS/ (例:./diagrams/2026-04-15T143022/)
写文件 <dir>/diagram.svg 写文件 <dir>/diagram.svg
渲染 npx -y @larksuite/whiteboard-cli@^0.2.11 -i <dir>/diagram.svg -o <dir>/diagram.png -f svg 渲染 npx -y @larksuite/whiteboard-cli@^0.2.12 -i <dir>/diagram.svg -o <dir>/diagram.png -f svg
检查 npx -y @larksuite/whiteboard-cli@^0.2.11 -i <dir>/diagram.svg -f svg --check 检查 npx -y @larksuite/whiteboard-cli@^0.2.12 -i <dir>/diagram.svg -f svg --check
导出 npx -y @larksuite/whiteboard-cli@^0.2.11 -i <dir>/diagram.svg -f svg --to openapi --format json > <dir>/diagram.json 导出 npx -y @larksuite/whiteboard-cli@^0.2.12 -i <dir>/diagram.svg -f svg --to openapi --format json > <dir>/diagram.json
``` ```
`npx -y @larksuite/whiteboard-cli@^0.2.11 --check` 检测 `text-overflow``node-overlap`, 并结合视觉效果(查看 PNG)进行调整 `npx -y @larksuite/whiteboard-cli@^0.2.12 --check` 检测 `text-overflow``node-overlap`, 并结合视觉效果(查看 PNG)进行调整
## 画板怎么处理 SVG ## 画板怎么处理 SVG

View File

@@ -8,7 +8,7 @@
## Layout 选型 ## Layout 选型
- **脚本生成坐标**(推荐):用 .cjs 脚本计算柱体位置和高度,脚本输出 JSON 文件后调用 `npx -y @larksuite/whiteboard-cli@^0.2.11` 渲染 - **脚本生成坐标**(推荐):用 .cjs 脚本计算柱体位置和高度,脚本输出 JSON 文件后调用 `npx -y @larksuite/whiteboard-cli@^0.2.12` 渲染
- **绝对定位手写**:简单柱状图(≤ 5 个柱)可手写坐标 - **绝对定位手写**:简单柱状图(≤ 5 个柱)可手写坐标
## Layout 规则 ## Layout 规则

View File

@@ -10,7 +10,7 @@
## Layout 选型 ## Layout 选型
- **脚本生成坐标**(必须):用 .cjs 脚本通过三角函数计算鱼骨坐标,脚本输出 JSON 文件后调用 `npx -y @larksuite/whiteboard-cli@^0.2.11` 渲染 - **脚本生成坐标**(必须):用 .cjs 脚本通过三角函数计算鱼骨坐标,脚本输出 JSON 文件后调用 `npx -y @larksuite/whiteboard-cli@^0.2.12` 渲染
## Layout 规则 ## Layout 规则

View File

@@ -9,7 +9,7 @@
## Layout 选型 ## Layout 选型
- **脚本生成坐标**(必须):用 .cjs 脚本极坐标计算阶段标签位置、SVG 圆环切割,脚本输出 JSON 文件后调用 `npx -y @larksuite/whiteboard-cli@^0.2.11` 渲染 - **脚本生成坐标**(必须):用 .cjs 脚本极坐标计算阶段标签位置、SVG 圆环切割,脚本输出 JSON 文件后调用 `npx -y @larksuite/whiteboard-cli@^0.2.12` 渲染
## Layout 规则 ## Layout 规则

View File

@@ -8,7 +8,7 @@
## Layout 选型 ## Layout 选型
- **脚本生成坐标**(推荐):用 .cjs 脚本计算数据点坐标和折线路径,脚本输出 JSON 文件后调用 `npx -y @larksuite/whiteboard-cli@^0.2.11` 渲染 - **脚本生成坐标**(推荐):用 .cjs 脚本计算数据点坐标和折线路径,脚本输出 JSON 文件后调用 `npx -y @larksuite/whiteboard-cli@^0.2.12` 渲染
## Layout 规则 ## Layout 规则

View File

@@ -8,7 +8,7 @@
## Layout 选型 ## Layout 选型
- **脚本生成坐标**推荐Treemap 需要精确的面积比例计算,用 .cjs 脚本递归切分矩形,脚本输出 JSON 文件后调用 `npx -y @larksuite/whiteboard-cli@^0.2.11` 渲染 - **脚本生成坐标**推荐Treemap 需要精确的面积比例计算,用 .cjs 脚本递归切分矩形,脚本输出 JSON 文件后调用 `npx -y @larksuite/whiteboard-cli@^0.2.12` 渲染
- 不适合手动心算坐标 - 不适合手动心算坐标
## Layout 规则 ## Layout 规则

View File

@@ -12,6 +12,7 @@
- TestIM_ChatMessageWorkflowAsUser: proves the user chat message flow through `create chat as user`, `send message as user`, and `list chat messages as user` with the created message ID and content asserted from read-after-write output. - TestIM_ChatMessageWorkflowAsUser: proves the user chat message flow through `create chat as user`, `send message as user`, and `list chat messages as user` with the created message ID and content asserted from read-after-write output.
- TestIM_MessageGetWorkflowAsUser: proves user message readback through `batch get message as user` after creating a fresh chat and sending a unique message. - TestIM_MessageGetWorkflowAsUser: proves user message readback through `batch get message as user` after creating a fresh chat and sending a unique message.
- TestIM_MessageReplyWorkflowAsBot: proves threaded reply flow through `reply to message in thread as bot` and `list thread replies as bot`, reading back the reply from `im +threads-messages-list`. - TestIM_MessageReplyWorkflowAsBot: proves threaded reply flow through `reply to message in thread as bot` and `list thread replies as bot`, reading back the reply from `im +threads-messages-list`.
- TestIM_MessagesSendAudioDryRunRejectsNonOpus: proves the `im +messages-send --audio` dry-run validation rejects non-Opus local audio before upload, with typed validation metadata and recovery guidance.
- TestIM_MessageForwardWorkflowAsUser: proves UAT-backed API forwarding through `im messages forward` and `im threads forward` using a fresh message/thread fixture; skips the forward assertions when the current test app/UAT lacks IM forward permission. - TestIM_MessageForwardWorkflowAsUser: proves UAT-backed API forwarding through `im messages forward` and `im threads forward` using a fresh message/thread fixture; skips the forward assertions when the current test app/UAT lacks IM forward permission.
- Blocked area: `im +chat-search` did not reliably return freshly created private chats in UAT, and `im +messages-search` did not reliably index freshly sent messages in time for a deterministic read-after-write assertion, so both remain uncovered. - Blocked area: `im +chat-search` did not reliably return freshly created private chats in UAT, and `im +messages-search` did not reliably index freshly sent messages in time for a deterministic read-after-write assertion, so both remain uncovered.
@@ -27,7 +28,7 @@
| ✓ | im +messages-reply | shortcut | im/message_reply_workflow_test.go::TestIM_MessageReplyWorkflowAsBot/reply to message in thread as bot | `--message-id`; `--text`; `--reply-in-thread` | reply is read back via thread list | | ✓ | im +messages-reply | shortcut | im/message_reply_workflow_test.go::TestIM_MessageReplyWorkflowAsBot/reply to message in thread as bot | `--message-id`; `--text`; `--reply-in-thread` | reply is read back via thread list |
| ✕ | im +messages-resources-download | shortcut | | none | needs a stable image/file message fixture plus file_key proof; left uncovered | | ✕ | im +messages-resources-download | shortcut | | none | needs a stable image/file message fixture plus file_key proof; left uncovered |
| ✕ | im +messages-search | shortcut | | none | freshly sent messages were not indexed deterministically in UAT time for a stable read-after-write proof | | ✕ | im +messages-search | shortcut | | none | freshly sent messages were not indexed deterministically in UAT time for a stable read-after-write proof |
| ✓ | im +messages-send | shortcut | im/chat_message_workflow_test.go::TestIM_ChatMessageWorkflowAsUser/send message as user; im/message_get_workflow_test.go::TestIM_MessageGetWorkflowAsUser; im/message_reply_workflow_test.go::TestIM_MessageReplyWorkflowAsBot | `--chat-id`; `--text` | covered where returned message IDs feed follow-up reads | | ✓ | im +messages-send | shortcut | im/chat_message_workflow_test.go::TestIM_ChatMessageWorkflowAsUser/send message as user; im/message_get_workflow_test.go::TestIM_MessageGetWorkflowAsUser; im/message_reply_workflow_test.go::TestIM_MessageReplyWorkflowAsBot; im/message_audio_dryrun_test.go::TestIM_MessagesSendAudioDryRunRejectsNonOpus | `--chat-id`; `--text`; `--audio ./voice.mp3 --dry-run` | live text sends feed follow-up reads; dry-run pins non-Opus audio validation before upload |
| ✓ | im +threads-messages-list | shortcut | im/message_reply_workflow_test.go::TestIM_MessageReplyWorkflowAsBot/list thread replies as bot | `--thread` | proves threaded reply is persisted | | ✓ | im +threads-messages-list | shortcut | im/message_reply_workflow_test.go::TestIM_MessageReplyWorkflowAsBot/list thread replies as bot | `--thread` | proves threaded reply is persisted |
| ✕ | im chat.members create | api | | none | no member mutation workflow yet | | ✕ | im chat.members create | api | | none | no member mutation workflow yet |
| ✕ | im chat.members get | api | | none | no member get workflow yet | | ✕ | im chat.members get | api | | none | no member get workflow yet |

View File

@@ -0,0 +1,62 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package im
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
clie2e "github.com/larksuite/cli/tests/cli_e2e"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func TestIM_MessagesSendAudioDryRunRejectsNonOpus(t *testing.T) {
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
t.Setenv("LARKSUITE_CLI_APP_ID", "im_audio_dryrun_test")
t.Setenv("LARKSUITE_CLI_APP_SECRET", "im_audio_dryrun_secret")
t.Setenv("LARKSUITE_CLI_BRAND", "feishu")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
workDir := t.TempDir()
audioPath := filepath.Join(workDir, "voice.mp3")
require.NoError(t, os.WriteFile(audioPath, []byte("not real mp3; validation checks extension before upload"), 0o600))
result, err := clie2e.RunCmd(ctx, clie2e.Request{
Args: []string{
"im", "+messages-send",
"--chat-id", "oc_123",
"--audio", "./voice.mp3",
"--dry-run",
},
DefaultAs: "bot",
WorkDir: workDir,
})
require.NoError(t, err)
result.AssertExitCode(t, 2)
if got := gjson.Get(result.Stderr, "error.type").String(); got != "validation" {
t.Fatalf("error.type = %q, want validation\nstderr:\n%s", got, result.Stderr)
}
if got := gjson.Get(result.Stderr, "error.subtype").String(); got != "invalid_argument" {
t.Fatalf("error.subtype = %q, want invalid_argument\nstderr:\n%s", got, result.Stderr)
}
if got := gjson.Get(result.Stderr, "error.param").String(); got != "--audio" {
t.Fatalf("error.param = %q, want --audio\nstderr:\n%s", got, result.Stderr)
}
message := gjson.Get(result.Stderr, "error.message").String()
if !strings.Contains(message, "--audio supports only Opus audio files") {
t.Fatalf("error.message = %q, want Opus guidance\nstderr:\n%s", message, result.Stderr)
}
hint := gjson.Get(result.Stderr, "error.hint").String()
if !strings.Contains(hint, "--file") || !strings.Contains(hint, "ffmpeg") {
t.Fatalf("error.hint = %q, want --file and ffmpeg guidance\nstderr:\n%s", hint, result.Stderr)
}
}