Skip to content

feat(drive): add drive preview and cover shortcuts and document quota details#1259

Merged
zhoujunteng-max merged 6 commits into
mainfrom
feat/drive-add-preview-cover-and-quota
Jun 4, 2026
Merged

feat(drive): add drive preview and cover shortcuts and document quota details#1259
zhoujunteng-max merged 6 commits into
mainfrom
feat/drive-add-preview-cover-and-quota

Conversation

@zhoujunteng-max
Copy link
Copy Markdown
Collaborator

@zhoujunteng-max zhoujunteng-max commented Jun 4, 2026

Summary

This PR adds drive +preview and drive +cover shortcuts for Drive file preview artifact and cover downloads, and updates the lark-drive skill metadata to expose quota detail capability and the new shortcuts to AI agents.

Changes

  • add drive +preview to list and download available preview artifacts
  • add drive +cover to list and download built-in cover presets
  • normalize preview result wrapping and cover parameter mapping based on backend validation rules
  • add unit tests, dry-run E2E tests, and live workflow E2E tests for preview/cover flows
  • update skills/lark-drive/SKILL.md and add preview/cover references
  • document quota_details.get in skills/lark-drive/SKILL.md

Test Plan

  • Unit tests pass
  • Manual local verification confirms the lark-cli drive +preview and lark-cli drive +cover commands work as expected

Additional verification:

  • make unit-test
  • go test ./shortcuts/drive -run 'TestDrivePreview|TestDriveCover|TestShortcutsIncludesExpectedCommands'
  • go test ./tests/cli_e2e/drive -run 'TestDrive(Preview|Cover)DryRun'
  • go test ./tests/cli_e2e/drive -run 'TestDrive_PreviewAndCoverWorkflow'

Related Issues

  • None

Summary by CodeRabbit

  • New Features

    • Added Drive +preview and +cover shortcuts to list/download preview artifacts and cover presets (type/spec selection, optional version, dry-run support, output path, and collision policies).
  • Bug Fixes / Behavior

    • Stronger validation with clearer errors (404→failed-precondition for unavailable specs/types, hints to re-run list-only). Improved preview candidate normalization, extension inference, masked progress output, and safe output collision handling (error/overwrite/rename).
  • Documentation

    • New user guides and reference pages with examples, parameters, behaviors, and permission notes.
  • Tests

    • Extensive unit and e2e tests for list-only, download, dry-run, and workflow scenarios.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 4, 2026

Review Change Stack

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 202d9aad-61a6-44c6-be59-83969fb20d6b

📥 Commits

Reviewing files that changed from the base of the PR and between 84a974a and 52abe1f.

📒 Files selected for processing (2)
  • shortcuts/drive/drive_cover.go
  • shortcuts/drive/drive_preview_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • shortcuts/drive/drive_cover.go
  • shortcuts/drive/drive_preview_test.go

📝 Walkthrough

Walkthrough

Adds two Drive shortcuts: +preview to list/download preview artifacts and +cover to list/download built-in cover presets, plus shared helpers for validation, candidate selection, extension inference, streamed downloads with collision handling, unit and e2e tests, and documentation.

Changes

Drive Preview and Cover Shortcuts

Layer / File(s) Summary
Preview/Cover common helpers and data structures
shortcuts/drive/drive_preview_common.go
Defines constants, metadata structures, MIME→extension mappings, built-in preview type and cover spec catalogs; implements shared helpers for CLI validation, candidate retrieval and selection, preview_download parameter construction, streamed artifact download with path safety and collision handling (error/overwrite/rename), extension inference from headers or fallback, and validation/error hint construction.
Drive Preview shortcut implementation
shortcuts/drive/drive_preview.go
Shortcut metadata and flags for --file-token, --type, --version, --list-only, --output, --if-exists; validation of flag combinations; DryRun for list or download envelopes (optional version handling); Execute fetching candidates, outputting lists, selecting candidates, resolving version, and downloading with extension/collision handling.
Drive Cover shortcut implementation
shortcuts/drive/drive_cover.go
Shortcut metadata and flags for --file-token, --spec, --version, --list-only, --output, --if-exists; validation of spec names and mode rules; DryRun returning built-in candidates or building a preview_download GET; Execute that lists presets or downloads selected cover via shared helper with masked progress output; maps preview_download 404 into a spec-scoped FailedPrecondition validation error with hints.
Shortcut registration and wiring
shortcuts/drive/shortcuts.go, shortcuts/drive/shortcuts_test.go
Registers DrivePreview and DriveCover in Shortcuts() and updates tests to expect +preview and +cover.
Comprehensive unit test suite
shortcuts/drive/drive_preview_test.go
Covers list-only normalization, download mapping and rename collision handling, unavailable-type rejection, candidate selection preferences, cover spec catalog behavior, DryRun request shapes, validation errors (including not-ready FailedPrecondition), extension inference from Content-Type/Content-Disposition, metadata normalization, output-path resolution, scalar coercion, alias normalization, and hint composition.
E2E dry-run and workflow tests
tests/cli_e2e/drive/drive_preview_dryrun_test.go, tests/cli_e2e/drive/drive_preview_workflow_test.go
Dry-run tests validate the generated API call structure for preview list/download and cover download; live workflow test creates/upload fixture, polls for ready preview/cover candidates, downloads artifacts, and validates output paths, extensions, and contents.
User-facing documentation
skills/lark-drive/SKILL.md, skills/lark-drive/references/lark-drive-preview.md, skills/lark-drive/references/lark-drive-cover.md
Adds reference pages and SKILL guidance for +preview and +cover, including usage examples, parameter tables, output contracts, supported types/specs, behavioral constraints, and extension fallback rules; documents quota_details.get permission scope and user-only call requirement.

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant DriveAPI
  participant LocalFS
  CLI->>DriveAPI: POST /open-apis/drive/v1/medias/:file_token/preview_result (list)
  DriveAPI-->>CLI: preview candidates (types/status/downloadable)
  CLI->>CLI: select candidate / build preview_download params
  CLI->>DriveAPI: GET /open-apis/drive/v1/medias/:file_token/preview_download?...
  DriveAPI-->>CLI: stream artifact (Content-Type/Disposition)
  CLI->>LocalFS: write file (apply if-exists policy, extension inference)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • larksuite/cli#528: Related Drive e2e helper utilities used by the new Drive preview/cover workflow tests.

Suggested labels

size/L

Suggested reviewers

  • fangshuyu-768
  • wittam-01

🐰 Two new shortcuts hop into the garden,
Preview and cover, a hunter's delight!
List the candidates, pick what you seek—
Download with care, rename if it’s meek.
Hop, nibble, and stash your artifact tight!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main additions: two new Drive shortcuts (preview and cover) and documentation updates for quota details.
Description check ✅ Passed The description follows the template structure with Summary, Changes, Test Plan, and Related Issues sections. All key changes and verification steps are documented with checkmarks.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/drive-add-preview-cover-and-quota

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/XL Architecture-level or global-impact change labels Jun 4, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented Jun 4, 2026

Codecov Report

❌ Patch coverage is 84.30233% with 81 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.96%. Comparing base (b3fcf55) to head (52abe1f).
⚠️ Report is 11 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/drive/drive_preview_common.go 83.50% 39 Missing and 24 partials ⚠️
shortcuts/drive/drive_cover.go 84.84% 5 Missing and 5 partials ⚠️
shortcuts/drive/drive_preview.go 87.87% 4 Missing and 4 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1259      +/-   ##
==========================================
+ Coverage   69.90%   69.96%   +0.05%     
==========================================
  Files         645      669      +24     
  Lines       60233    64967    +4734     
==========================================
+ Hits        42108    45454    +3346     
- Misses      14823    15860    +1037     
- Partials     3302     3653     +351     

☔ View full report in Codecov by Harness.
📢 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

github-actions Bot commented Jun 4, 2026

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add larksuite/cli#feat/drive-add-preview-cover-and-quota -y -g

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: 4

🧹 Nitpick comments (1)
shortcuts/drive/drive_preview_test.go (1)

290-317: ⚡ Quick win

Mount the real shortcut instead of re-declaring its flags.

Lines 295-302 duplicate the preview/cover flag surface in test code, so these DryRun tests can keep passing after a production flag rename, default change, or registration tweak. Building the runtime from the mounted DrivePreview/DriveCover command would keep the tests coupled to the real CLI contract.

🤖 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/drive/drive_preview_test.go` around lines 290 - 317,
newDrivePreviewRuntime is re-declaring the preview/cover CLI flags in the test
instead of mounting the real shortcut command, which breaks tests if production
flags change; update newDrivePreviewRuntime to instantiate or mount the actual
DrivePreview (and DriveCover if relevant) cobra.Command (instead of creating cmd
:= &cobra.Command{Use: use}) to inherit the real flag set, then apply
stringFlags and boolFlags via cmd.Flags().Set as before and return the runtime
from common.TestNewRuntimeContextWithCtx(context.Background(), cmd,
driveTestConfig()) so tests track the real CLI registration.
🤖 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/drive/drive_preview_common.go`:
- Around line 501-506: The current switch branch for ifExists (case "" and
drivePreviewIfExistsError) incorrectly treats any non-nil runtime.FileIO().Stat
error as "path does not exist"; instead, change the logic in that branch to
explicitly check for fs.ErrNotExist and treat that as the non-existent path case
(return finalPath, resolution, nil), but propagate any other Stat error (return
it up) so permission/I/O errors are preserved; locate the check using
runtime.FileIO().Stat(finalPath), the drivePreviewIfExistsError constant, and
the errs.NewValidationError(...) code that currently returns the validation
error, and mirror the explicit fs.ErrNotExist handling already used in
nextAvailableDrivePreviewPath.
- Around line 501-519: The switch uses the raw ifExists string, which can
include surrounding whitespace and mismatch validation; normalize it first
(e.g., normalized := strings.TrimSpace(ifExists) or reassign ifExists =
strings.TrimSpace(ifExists)) and switch on that normalized value so cases like
drivePreviewIfExistsRename match; update the switch expression and keep
references to ifExists,
drivePreviewIfExistsError/drivePreviewIfExistsOverwrite/drivePreviewIfExistsRename,
nextAvailableDrivePreviewPath, and runtime.ResolveSavePath unchanged.

In `@skills/lark-drive/references/lark-drive-preview.md`:
- Line 45: The docs show `--type` example values (`png`/`jpg`/`source_file`)
that don't match the flag contract in shortcuts/drive/drive_preview.go (which
expects `pdf | html | text | image | source`); update the lark-drive-preview.md
`--type` examples and description to use the exact supported values (`pdf`,
`html`, `text`, `image`, `source`) and remove/replace `png`/`jpg`/`source_file`
so examples and text match the implementation and won't trigger the
unavailable-branch in DrivePreview flag parsing.

In `@skills/lark-drive/SKILL.md`:
- Line 272: Update the `+cover` SKILL.md entry so its 404 semantics match the
behavior in drive_preview_workflow_test.go: replace the phrase that says
"download-time HTTP 404 means the file has no artifact for that cover spec" with
text stating that a download-time HTTP 404 may indicate the artifact is not yet
ready or unavailable and that callers/agents should retry (or list artifacts
first then retry) rather than treat 404 as a final, non-retriable error.

---

Nitpick comments:
In `@shortcuts/drive/drive_preview_test.go`:
- Around line 290-317: newDrivePreviewRuntime is re-declaring the preview/cover
CLI flags in the test instead of mounting the real shortcut command, which
breaks tests if production flags change; update newDrivePreviewRuntime to
instantiate or mount the actual DrivePreview (and DriveCover if relevant)
cobra.Command (instead of creating cmd := &cobra.Command{Use: use}) to inherit
the real flag set, then apply stringFlags and boolFlags via cmd.Flags().Set as
before and return the runtime from
common.TestNewRuntimeContextWithCtx(context.Background(), cmd,
driveTestConfig()) so tests track the real CLI registration.
🪄 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: 8125166d-2326-4f48-bb2c-7c8108788966

📥 Commits

Reviewing files that changed from the base of the PR and between 7a0dbe0 and 0505142.

📒 Files selected for processing (11)
  • shortcuts/drive/drive_cover.go
  • shortcuts/drive/drive_preview.go
  • shortcuts/drive/drive_preview_common.go
  • shortcuts/drive/drive_preview_test.go
  • shortcuts/drive/shortcuts.go
  • shortcuts/drive/shortcuts_test.go
  • skills/lark-drive/SKILL.md
  • skills/lark-drive/references/lark-drive-cover.md
  • skills/lark-drive/references/lark-drive-preview.md
  • tests/cli_e2e/drive/drive_preview_dryrun_test.go
  • tests/cli_e2e/drive/drive_preview_workflow_test.go

Comment thread shortcuts/drive/drive_preview_common.go
Comment thread shortcuts/drive/drive_preview_common.go
Comment thread skills/lark-drive/references/lark-drive-preview.md
Comment thread skills/lark-drive/SKILL.md
- add `drive +preview` and `drive +cover` shortcuts
- wrap `preview_result` output with stable preview item fields
- support cover download via `preview_download` with validated preset mappings
- update lark-drive skill references for preview and cover usage
@zhoujunteng-max zhoujunteng-max force-pushed the feat/drive-add-preview-cover-and-quota branch from 0505142 to f3f06cd Compare June 4, 2026 06:24
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.

♻️ Duplicate comments (1)
shortcuts/drive/drive_preview_common.go (1)

501-521: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Trim --if-exists before switching to keep Validate/Execute behavior consistent.

Line 501 switches on the raw ifExists, while Line 254 validates strings.TrimSpace(policy). A value like --if-exists=" rename " passes validation but falls into the default error path at execution.

Suggested fix
 func resolveDrivePreviewOutputPath(runtime *common.RuntimeContext, outputPath string, header http.Header, fallbackExt, ifExists string) (string, *driveExtensionResolution, error) {
 	finalPath, resolution := autoAppendDrivePreviewExtension(outputPath, header, fallbackExt)
+	ifExists = strings.TrimSpace(ifExists)
 	if _, err := runtime.ResolveSavePath(finalPath); err != nil {
 		return "", nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "unsafe output path: %s", err).WithParam("--output")
 	}
🤖 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/drive/drive_preview_common.go` around lines 501 - 521, The switch
on the raw ifExists value can mis-handle values with surrounding whitespace;
trim the value before switching so execution matches earlier validation: apply
strings.TrimSpace to the ifExists value (or reuse the already-trimmed policy
variable) before the switch that checks drivePreviewIfExistsError,
drivePreviewIfExistsOverwrite, and drivePreviewIfExistsRename so values like "
rename " follow the same code paths (keep downstream calls like
nextAvailableDrivePreviewPath and runtime.ResolveSavePath unchanged).
🤖 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.

Duplicate comments:
In `@shortcuts/drive/drive_preview_common.go`:
- Around line 501-521: The switch on the raw ifExists value can mis-handle
values with surrounding whitespace; trim the value before switching so execution
matches earlier validation: apply strings.TrimSpace to the ifExists value (or
reuse the already-trimmed policy variable) before the switch that checks
drivePreviewIfExistsError, drivePreviewIfExistsOverwrite, and
drivePreviewIfExistsRename so values like " rename " follow the same code paths
(keep downstream calls like nextAvailableDrivePreviewPath and
runtime.ResolveSavePath unchanged).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 82e202ce-8c98-4cdb-9082-5f905b02c8b7

📥 Commits

Reviewing files that changed from the base of the PR and between 0505142 and f3f06cd.

📒 Files selected for processing (11)
  • shortcuts/drive/drive_cover.go
  • shortcuts/drive/drive_preview.go
  • shortcuts/drive/drive_preview_common.go
  • shortcuts/drive/drive_preview_test.go
  • shortcuts/drive/shortcuts.go
  • shortcuts/drive/shortcuts_test.go
  • skills/lark-drive/SKILL.md
  • skills/lark-drive/references/lark-drive-cover.md
  • skills/lark-drive/references/lark-drive-preview.md
  • tests/cli_e2e/drive/drive_preview_dryrun_test.go
  • tests/cli_e2e/drive/drive_preview_workflow_test.go
✅ Files skipped from review due to trivial changes (1)
  • skills/lark-drive/SKILL.md
🚧 Files skipped from review as they are similar to previous changes (7)
  • shortcuts/drive/shortcuts.go
  • shortcuts/drive/shortcuts_test.go
  • tests/cli_e2e/drive/drive_preview_dryrun_test.go
  • shortcuts/drive/drive_preview.go
  • tests/cli_e2e/drive/drive_preview_workflow_test.go
  • shortcuts/drive/drive_cover.go
  • shortcuts/drive/drive_preview_test.go

wittam-01
wittam-01 previously approved these changes Jun 4, 2026
Comment thread shortcuts/drive/drive_cover.go
Comment thread shortcuts/drive/drive_preview_common.go
@zhoujunteng-max zhoujunteng-max merged commit ac116e7 into main Jun 4, 2026
22 checks passed
@zhoujunteng-max zhoujunteng-max deleted the feat/drive-add-preview-cover-and-quota branch June 4, 2026 13:09
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/XL Architecture-level or global-impact change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants