Skip to content

feat(doc): add --width/--height flags to docs +media-insert#832

Merged
fangshuyu-768 merged 14 commits into
larksuite:mainfrom
songyoung77:feat/doc-media-insert-width-height
May 15, 2026
Merged

feat(doc): add --width/--height flags to docs +media-insert#832
fangshuyu-768 merged 14 commits into
larksuite:mainfrom
songyoung77:feat/doc-media-insert-width-height

Conversation

@songyoung77
Copy link
Copy Markdown
Contributor

@songyoung77 songyoung77 commented May 11, 2026

Summary

Add --width and --height flags to docs +media-insert so users and AI agents can control the display size of inserted images. When only one dimension is specified, the other is auto-calculated from the image's native aspect ratio.

Changes

  • Add --width and --height int flags with validation in shortcuts/doc/doc_media_insert.go
  • Add computeMissingDimension() and detectImageDimensions() aspect-ratio helpers in shortcuts/doc/doc_media_insert.go
  • Wire dimension resolution into Execute (after upload, before batch_update) and DryRun (best-effort preview) in shortcuts/doc/doc_media_insert.go
  • Add 13 unit tests covering payload construction, validation, and aspect-ratio calculation in shortcuts/doc/doc_media_insert_test.go
  • Update SKILL.md with new flags and usage examples in skills/lark-doc/references/lark-doc-media-insert.md

Test Plan

  • make unit-test passed
  • make validate passed
  • local-eval passed (E2E 7/8 — 1 env-only failure: test app lacks space:document:delete scope for cleanup; skillave 6/6)
  • acceptance-reviewer passed (5/5 cases)
  • manual verification: lark-cli docs +media-insert --doc <token> --file img.png --width 600 --as bot — confirmed aspect-ratio auto-calc and output fields

Related Issues

Closes #489

Summary by CodeRabbit

  • New Features

    • Optional --width and --height for docs +media-insert (px); if only one is given, the missing dimension is auto-computed from image aspect ratio when detectable.
    • Execute and dry-run now surface resolved image dimensions; dry-run annotates clipboard-only inputs instead of decoding.
  • Bug Fixes / Validation

    • --width/--height rejected for non-image types; values must be positive. Execute fails if native dimension detection needed but unavailable.
  • Documentation

    • Command docs updated with sizing examples and supported formats (PNG/JPEG/GIF).
  • Tests

    • Added unit tests for validation, sizing, and aspect-ratio computation.

Review Change Stack

Extend buildBatchUpdateData signature with width and height int params.
When mediaType is "image" and either dimension is positive, the value is
included in the replace_image payload. Existing call sites pass 0, 0.
Add computeMissingDimension (pure ratio math) and detectImageDimensions
(header-only image.DecodeConfig) with PNG/JPEG/GIF blank-import decoders,
plus imageDimensions struct; drive with two new TDD tests.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 11, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds --width and --height int flags to docs +media-insert for images; validates usage and bounds; detects native image dimensions when one side is missing; computes the missing side by aspect ratio; includes resolved sizes in batch_update payloads and CLI output; updates tests and docs.

Changes

Image sizing feature

Layer / File(s) Summary
Flag definitions and imports
shortcuts/doc/doc_media_insert.go
Exports new --width and --height int flags on DocMediaInsert restricted to --type=image. Adds image decoder imports (GIF/JPEG/PNG).
Validation logic
shortcuts/doc/doc_media_insert.go
Rejects --width/--height unless --type=image, enforces positive integers, and caps values at 10,000.
Dry-run dimension resolution
shortcuts/doc/doc_media_insert.go
Dry-run: when exactly one dimension set and source is a file, decode native size and pass dryWidth/dryHeight into batch payload; for clipboard input, add a note deferring calculation.
Execute dimension resolution
shortcuts/doc/doc_media_insert.go
At runtime, use both provided values or decode native image size (clipboard bytes or file) and compute the missing dimension; error if decoding fails when only one dimension provided. Outputs resolved width/height when positive.
Helpers and payload wiring
shortcuts/doc/doc_media_insert.go
Adds imageDimensions, detectImageDimensions, detectImageDimensionsFromPath, and computeMissingDimension; extends buildBatchUpdateData to accept width/height and conditionally attach them to replace_image when positive.
Implementation tests
shortcuts/doc/doc_media_insert_test.go
Updates tests to pass width/height args, adds tests for image/file payload behavior with dimensions, validation rules, aspect-ratio completion, and a test helper for setting flags.
User documentation
skills/lark-doc/references/lark-doc-media-insert.md
Adds examples and parameter docs for --width and --height, explaining auto-computation and supported formats (PNG/JPEG/GIF).

Sequence Diagram

sequenceDiagram
  participant CLI as lark-cli (docs +media-insert)
  participant Input as Source (file or clipboard)
  participant Decoder as Image decoder
  participant API as Docs API (blocks.batch_update)

  CLI->>Input: read file path or clipboard bytes
  CLI->>Decoder: request native dimensions (when needed)
  Decoder-->>CLI: native width/height (or error)
  CLI->>CLI: compute missing dimension (aspect-ratio)
  CLI->>API: buildBatchUpdateData with replace_image (+width/+height)
  API-->>CLI: response (block_id, status)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

  • larksuite/cli#508: Adds clipboard image-reading support used for native dimension detection.

Suggested labels

size/L

Suggested reviewers

  • liujinkun2025
  • fangshuyu-768

Poem

A rabbit counts the pixels right,
One side given, the other's light,
It reads the bytes or opens files,
Computes the height with merry smiles,
And inserts images sized just right. 🐰🖼️

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.55% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely summarizes the main change: adding --width/--height flags to docs +media-insert.
Description check ✅ Passed The PR description covers all required template sections: Summary explains the motivation, Changes lists the main modifications, Test Plan documents verification steps, and Related Issues links the closing issue #489.
Linked Issues check ✅ Passed The PR fully addresses issue #489: implements --width/--height flags for image sizing, adds aspect-ratio auto-calculation, validates dimensions, and includes comprehensive unit tests and documentation updates.
Out of Scope Changes check ✅ Passed All changes are directly scoped to adding width/height image sizing functionality: implementation in doc_media_insert.go, comprehensive tests, and documentation updates are all on-topic.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added domain/ccm PR touches the ccm domain size/M Single-domain feat or fix with limited business impact labels May 11, 2026
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@shortcuts/doc/doc_media_insert.go`:
- Around line 565-571: detectImageDimensionsFromPath opens an untrusted filePath
directly; call validate.SafeInputPath(filePath) at the start of
detectImageDimensionsFromPath (before fio.Open) and return any validation error
to prevent reading unsafe paths. Keep the existing signature and behavior
otherwise (open via fio.Open, defer Close, call detectImageDimensions), and
ensure the validation error is propagated so callers (e.g., DryRun/Execute)
receive the failure.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c198a35c-11cf-45cc-a55e-7bbcbcbfef84

📥 Commits

Reviewing files that changed from the base of the PR and between 7c6abb3 and 9b2fe95.

📒 Files selected for processing (3)
  • shortcuts/doc/doc_media_insert.go
  • shortcuts/doc/doc_media_insert_test.go
  • skills/lark-doc/references/lark-doc-media-insert.md

Comment thread shortcuts/doc/doc_media_insert.go
@CLAassistant
Copy link
Copy Markdown

CLAassistant commented May 12, 2026

CLA assistant check
All committers have signed the CLA.

Copy link
Copy Markdown
Collaborator

@fangshuyu-768 fangshuyu-768 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! Overall the implementation is clean and well-structured. I have a few concerns below — the division-by-zero risk (#1) should be addressed before merge, the rest are suggestions.

Comment thread shortcuts/doc/doc_media_insert.go
Comment thread shortcuts/doc/doc_media_insert.go Outdated
Comment thread shortcuts/doc/doc_media_insert.go
Comment thread shortcuts/doc/doc_media_insert_test.go
Comment thread shortcuts/doc/doc_media_insert.go
Comment thread shortcuts/doc/doc_media_insert.go Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
shortcuts/doc/doc_media_insert_test.go (1)

715-748: ⚡ Quick win

Isolate config state in the new validate runtime helper

At Line 715, this helper is used by parallel tests but does not isolate LARKSUITE_CLI_CONFIG_DIR, which can leak ambient config state across tests.

Suggested patch
 func newMediaInsertValidateRuntimeWithSize(t *testing.T, doc, mediaType string, width, height int, setWidth, setHeight bool) *common.RuntimeContext {
 	t.Helper()
+	t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
 
 	cmd := &cobra.Command{Use: "docs +media-insert"}

As per coding guidelines, **/*_test.go: Use t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) to isolate config state in tests.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/doc/doc_media_insert_test.go` around lines 715 - 748, The helper
newMediaInsertValidateRuntimeWithSize doesn't isolate LARKSUITE_CLI_CONFIG_DIR
causing config leakage across parallel tests; add
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) at the top of
newMediaInsertValidateRuntimeWithSize (before creating the cobra.Command and
flags) so each test gets its own temporary config dir and environment isolation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@shortcuts/doc/doc_media_insert_test.go`:
- Around line 715-748: The helper newMediaInsertValidateRuntimeWithSize doesn't
isolate LARKSUITE_CLI_CONFIG_DIR causing config leakage across parallel tests;
add t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) at the top of
newMediaInsertValidateRuntimeWithSize (before creating the cobra.Command and
flags) so each test gets its own temporary config dir and environment isolation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6f6d89d0-9c7f-40b8-81d4-96dcfc8940c3

📥 Commits

Reviewing files that changed from the base of the PR and between 9386118 and bc9e52f.

📒 Files selected for processing (2)
  • shortcuts/doc/doc_media_insert.go
  • shortcuts/doc/doc_media_insert_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • shortcuts/doc/doc_media_insert.go

Comment thread shortcuts/doc/doc_media_insert.go Outdated
Comment thread shortcuts/doc/doc_media_insert.go
…cute

Dimension detection runs after the placeholder block is created (Step 2),
so failures must clean up the block to avoid leaving an empty placeholder
in the document.
@codecov
Copy link
Copy Markdown

codecov Bot commented May 15, 2026

Codecov Report

❌ Patch coverage is 41.48936% with 55 lines in your changes missing coverage. Please review.
✅ Project coverage is 65.90%. Comparing base (88d4e3b) to head (f9bc606).
⚠️ Report is 48 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/doc/doc_media_insert.go 41.48% 46 Missing and 9 partials ⚠️

❌ Your patch check has failed because the patch coverage (41.48%) is below the target coverage (60.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #832      +/-   ##
==========================================
+ Coverage   65.40%   65.90%   +0.50%     
==========================================
  Files         508      523      +15     
  Lines       46795    49679    +2884     
==========================================
+ Hits        30605    32742    +2137     
- Misses      13548    14136     +588     
- Partials     2642     2801     +159     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions
Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@f9bc6067d921279ef0754e1c1843f5476d423437

🧩 Skill update

npx skills add songyoung77/cli#feat/doc-media-insert-width-height -y -g

@fangshuyu-768 fangshuyu-768 merged commit 7400226 into larksuite:main May 15, 2026
17 of 18 checks passed
@liangshuo-1 liangshuo-1 mentioned this pull request May 15, 2026
3 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/ccm PR touches the ccm domain size/M Single-domain feat or fix with limited business impact

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[docs +media-insert] Support --width/--height for image display size

3 participants