Skip to content

feat(doc): add --file-view flag to +media-insert#419

Open
nickzhangcomes wants to merge 3 commits intolarksuite:mainfrom
nickzhangcomes:feat/docs-media-insert-view
Open

feat(doc): add --file-view flag to +media-insert#419
nickzhangcomes wants to merge 3 commits intolarksuite:mainfrom
nickzhangcomes:feat/docs-media-insert-view

Conversation

@nickzhangcomes
Copy link
Copy Markdown

@nickzhangcomes nickzhangcomes commented Apr 11, 2026

Summary

Add a --file-view flag to docs +media-insert so callers can choose how a file block is rendered: card (default, current behaviour), preview (inline player for audio/video), or inline. The value is plumbed into file.view_type when the block is created.

Motivation

Today docs +media-insert --type file always creates the file block with the default view_type=1 (card view). The docx open platform actually supports two other rendering modes for file blocks:

  • view_type=2 — preview view; renders audio/video files as an inline player
  • view_type=3 — inline view

These can only be set at block creation time — the PATCH replace_file endpoint does not accept view_type, so once the block is created with the default the caller cannot upgrade it afterwards. Without this flag, anyone who wants an inline audio/video player has to abandon the shortcut and manually re-implement the full 4-step orchestration (query root → create block → upload → bind + rollback) via lark-cli api calls.

Changes

  • shortcuts/doc/doc_media_insert.go
    • New fileViewMap (card/preview/inline1/2/3).
    • New --file-view flag on the shortcut, validated in Validate:
      • Unknown values rejected with a clear error.
      • --file-view + --type=image rejected (images have their own rendering).
    • buildCreateBlockData gains a fileViewType int parameter; when > 0 it sets file.view_type on the created child. 0 preserves the current behaviour (empty file: {} object), so servers still get exactly the same payload for existing callers.
    • Execute and DryRun thread the resolved view type through to buildCreateBlockData.
  • shortcuts/doc/doc_media_insert_test.go
    • Existing TestBuildCreateBlockDataUsesConcreteAppendIndex and TestBuildCreateBlockDataForFileIncludesFilePayload updated to pass the new 0 argument; expected payload unchanged.
    • New tests:
      • TestBuildCreateBlockDataForFileWithPreviewView
      • TestBuildCreateBlockDataForFileWithInlineView
      • TestBuildCreateBlockDataForImageIgnoresFileViewType (verifies view_type never leaks into image blocks)
      • TestFileViewMapCoversDocumentedValues (guards the public enum surface)

Usage

# Inline player rendering
lark-cli docs +media-insert --doc doxcnXXX --file ./audio.mp3 --type file --file-view preview

# Explicit card view (same as omitting --file-view)
lark-cli docs +media-insert --doc doxcnXXX --file ./report.pdf --type file --file-view card

# Inline view
lark-cli docs +media-insert --doc doxcnXXX --file ./data.csv --type file --file-view inline

Backward compatibility

Fully backward compatible:

  • New flag is optional with no default.
  • When --file-view is omitted, fileViewMap[""] == 0, which skips the new if fileViewType > 0 branch — the request body sent to the server is byte-for-byte identical to the current code.
  • Existing unit tests still pass (after the signature update), and the expected JSON payload for the default cases is unchanged.

Test plan

  • go test ./shortcuts/doc/... — all existing and new tests pass
  • go vet ./... — clean
  • gofmt -l — clean
  • Manual end-to-end: --file-view preview with an --type=file upload — confirmed the resulting file block is wrapped in a block_type=33 view with view.view_type=2, as expected by the open platform spec
  • Manual end-to-end: omitting --file-view — request body identical to current behaviour
  • --file-view bogus → validation error
  • --type image --file-view preview → validation error

Relationship to #335

#335 (feat(doc): add --selection-with-ellipsis position flag to +media-insert) also extends docs +media-insert with a new flag, but along an orthogonal axis — positioning (where to insert) vs. rendering (how it is displayed). The two changes do not overlap semantically. If #335 lands first I am happy to rebase; conflicts should be limited to the Flags slice and the Execute/DryRun local variable blocks.

Summary by CodeRabbit

  • New Features
    • Added a file view option when inserting files into documents—choose card, preview, or inline to control file rendering.
  • Bug Fixes
    • Validation enforces that file view options are only accepted for file inserts and ignored/blocked otherwise.
  • Tests
    • Added and updated tests verifying file view mappings, file vs. image behavior, and validation of allowed view options.

…ring

The docx File block supports three render modes via view_type
(1=card, 2=preview inline player, 3=inline), but --type=file today
always creates with the default card view. Because view_type can only
be set at creation time (PATCH replace_file ignores it), callers
wanting an inline audio/video player had to abandon the shortcut and
reimplement the full 4-step orchestration manually.

Add --file-view card|preview|inline that threads into file.view_type
on block creation. Omitting the flag preserves the exact request body
that the shortcut sends today, so existing users are unaffected.

--file-view is rejected when combined with --type=image (images have
their own rendering) and when an unknown value is passed.
@CLAassistant
Copy link
Copy Markdown

CLAassistant commented Apr 11, 2026

CLA assistant check
All committers have signed the CLA.

@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 Apr 11, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 11, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7e842e94-3112-4048-8fd9-23ca7d5249fa

📥 Commits

Reviewing files that changed from the base of the PR and between 7635a97 and 3669613.

📒 Files selected for processing (1)
  • shortcuts/doc/doc_media_insert_test.go

📝 Walkthrough

Walkthrough

Added a --file-view flag (card/preview/inline) for DOCX file blocks when --type=file. Validation enforces usage only with --type=file, maps inputs to DOCX enum ints, and threads a new fileViewType into buildCreateBlockData so file.view_type is set at block creation for file blocks.

Changes

Cohort / File(s) Summary
Media Insert Implementation
shortcuts/doc/doc_media_insert.go
Added --file-view flag and validation restricted to --type=file. Introduced fileViewMap mapping `card
Media Insert Tests
shortcuts/doc/doc_media_insert_test.go
Updated test calls to include third fileViewType arg; added tests asserting file.view_type is present with file blocks for card/preview/inline and absent for image blocks. Added runtime validation tests for --file-view acceptance/rejection and a test verifying fileViewMap contains documented keys.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • liujinkun2025
  • fangshuyu-768

Poem

🐰
A tiny flag I tuck away, card, preview, inline,
I map the words to numbers, neat as any line.
When files arrive I set their view with care,
Tests nibble at my edges, all set and fair. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding a new --file-view flag to the +media-insert shortcut for controlling file block rendering.
Description check ✅ Passed The pull request description is comprehensive and well-structured, covering all required template sections with detailed motivation, implementation details, usage examples, backward compatibility notes, and test coverage.

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

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

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

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 (2)
shortcuts/doc/doc_media_insert.go (1)

243-245: Defensively constrain view_type to known enums before writing payload.

fileViewType > 0 allows unexpected positives to pass if validation is bypassed by future call paths. Narrowing to known values prevents malformed API payloads.

Proposed hardening
-		if fileViewType > 0 {
+		if fileViewType == 1 || fileViewType == 2 || fileViewType == 3 {
 			fileData["view_type"] = fileViewType
 		}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/doc/doc_media_insert.go` around lines 243 - 245, Narrow the check
that writes fileData["view_type"] by validating fileViewType against the known
enum set instead of just fileViewType > 0; in the function that builds fileData,
replace the loose positive check with an explicit whitelist (e.g., switch or set
membership) of allowed view enum constants and only assign fileData["view_type"]
when fileViewType equals one of those known values (referencing the fileViewType
variable and the fileData map key "view_type"); this prevents unknown positive
integers from being emitted in the payload.
shortcuts/doc/doc_media_insert_test.go (1)

107-118: Consider asserting required mappings instead of full-map equality.

Exact equality can become brittle if additional valid aliases are introduced later; key-by-key assertions keep intent while allowing safe extension.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/doc/doc_media_insert_test.go` around lines 107 - 118, Replace the
brittle full-map equality in TestFileViewMapCoversDocumentedValues with explicit
assertions that the required keys exist and map to the expected ints: inside
TestFileViewMapCoversDocumentedValues (which currently compares fileViewMap to
want), iterate over the expected entries (e.g., keys "card","preview","inline"
with values 1,2,3) and for each assert that fileViewMap[key] exists and equals
the expected value (use t.Fatalf or t.Errorf on mismatch); do not assert that
fileViewMap has no extra keys so future aliases can be added safely.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@shortcuts/doc/doc_media_insert_test.go`:
- Around line 107-118: Replace the brittle full-map equality in
TestFileViewMapCoversDocumentedValues with explicit assertions that the required
keys exist and map to the expected ints: inside
TestFileViewMapCoversDocumentedValues (which currently compares fileViewMap to
want), iterate over the expected entries (e.g., keys "card","preview","inline"
with values 1,2,3) and for each assert that fileViewMap[key] exists and equals
the expected value (use t.Fatalf or t.Errorf on mismatch); do not assert that
fileViewMap has no extra keys so future aliases can be added safely.

In `@shortcuts/doc/doc_media_insert.go`:
- Around line 243-245: Narrow the check that writes fileData["view_type"] by
validating fileViewType against the known enum set instead of just fileViewType
> 0; in the function that builds fileData, replace the loose positive check with
an explicit whitelist (e.g., switch or set membership) of allowed view enum
constants and only assign fileData["view_type"] when fileViewType equals one of
those known values (referencing the fileViewType variable and the fileData map
key "view_type"); this prevents unknown positive integers from being emitted in
the payload.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 08412741-0c56-4e7e-a146-270e86f20523

📥 Commits

Reviewing files that changed from the base of the PR and between f6a31e0 and 30e71e6.

📒 Files selected for processing (2)
  • shortcuts/doc/doc_media_insert.go
  • shortcuts/doc/doc_media_insert_test.go

@greptile-apps
Copy link
Copy Markdown

greptile-apps bot commented Apr 11, 2026

Greptile Summary

This PR adds a --file-view flag to docs +media-insert allowing callers to control file block rendering mode (card, preview, or inline) via the docx view_type field, which can only be set at block creation time. Both concerns raised in prior review threads have been addressed: Validate is now covered by a table-driven test suite, and the card-vs-omit payload difference is explicitly pinned in TestBuildCreateBlockDataForFileWithCardView.

Confidence Score: 5/5

Safe to merge — clean, backward-compatible feature addition with thorough test coverage.

All findings from prior review threads are addressed. No new bugs found. The implementation is defensive (zero-value map miss → 0 → no view_type field), validation is correct, and new tests cover all branches including Validate edge cases previously missing.

No files require special attention.

Important Files Changed

Filename Overview
shortcuts/doc/doc_media_insert.go Adds fileViewMap, --file-view flag, validation guard, and threads fileViewType through buildCreateBlockData; backward-compatible and defensively coded.
shortcuts/doc/doc_media_insert_test.go Adds comprehensive tests for all new --file-view paths including buildCreateBlockData variants, Validate table-driven tests, and the fileViewMap enum guard.

Reviews (3): Last reviewed commit: "test(doc): cover --file-view Validate co..." | Re-trigger Greptile

Address review feedback from automated reviewers on larksuite#419:

- Replace `fileViewType > 0` with an explicit 1|2|3 whitelist inside
  buildCreateBlockData so a stray positive int cannot escape into the
  request payload if a future caller bypasses Validate.
- Relax TestFileViewMapCoversDocumentedValues to assert only the
  documented keys rather than full-map equality, so future aliases
  (e.g. a "player" synonym for preview) do not falsely break the test.

No behaviour change for any existing --file-view input.
if docRef.Kind == "doc" {
return output.ErrValidation("docs +media-insert only supports docx documents; use a docx token/URL or a wiki URL that resolves to docx")
}
if view := runtime.Str("file-view"); view != "" {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Nice addition overall. One gap I noticed is that the new tests only exercise buildCreateBlockData, but the main user-facing contract here lives in Validate: rejecting unknown --file-view values and rejecting --file-view when --type != file.

Could we add focused tests for those validation paths as well? Otherwise a future refactor could silently relax the CLI contract without any test catching it.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good call, that gap was bugging me too after you pointed it out. Pushed a table-driven test in 3669613 that runs Validate directly and covers the two rejection branches (unknown value like --file-view bogus, and --file-view preview with --type image), plus the accepted shapes as positive cases so the whole guard is locked down. Future Validate refactors will have to touch these explicitly.

}
}

func TestBuildCreateBlockDataForFileWithPreviewView(t *testing.T) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Could we add coverage for the explicit --file-view card path too?

Omitting --file-view keeps the legacy payload (file: {}), but --file-view card now sends file.view_type = 1. Those are different request shapes, even if they are intended to be semantically equivalent. A small unit test here would help lock down that public flag behavior.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Agreed, and the divergence is on purpose: omitting the flag keeps the legacy file: {} shape for backward compat, while --file-view card sends an explicit view_type: 1 because the user literally asked for card. I didn't want to silently drop the field and make the flag non-idempotent with its own echo. Added TestBuildCreateBlockDataForFileWithCardView in 3669613 so that expectation is pinned, not just reviewer memory.

Pins down the two CLI guard branches (unknown --file-view value and
--file-view passed with --type!=file) that were previously only covered
indirectly through buildCreateBlockData. Also adds the --file-view card
case so the explicit view_type=1 payload (different from the legacy
file: {} shape when the flag is omitted) is locked in as part of the
public flag contract.
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.

3 participants