Skip to content

feat(drive): harden inspect shortcut failures#1323

Closed
fangshuyu-768 wants to merge 1 commit into
mainfrom
codex/inspect-cli-precheck
Closed

feat(drive): harden inspect shortcut failures#1323
fangshuyu-768 wants to merge 1 commit into
mainfrom
codex/inspect-cli-precheck

Conversation

@fangshuyu-768

@fangshuyu-768 fangshuyu-768 commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • harden drive +inspect input validation by rejecting conflicting --type values and malformed bare tokens before any API call
  • add limited retry/backoff for rate-limited wiki unwrap and drive metadata fetches, and annotate typed errors with the failing inspect stage
  • switch drive metadata lookup helpers onto CallAPITyped so inspect and its shared metadata path emit consistent typed errors

Testing

  • go test ./shortcuts/drive ./shortcuts/common
  • go test ./... (currently fails on existing cmd/schema tests with Unknown service: im on latest main; unrelated to this PR)

Summary by CodeRabbit

  • New Features

    • Drive Inspect command now automatically retries operations on rate-limit errors with configurable backoff timing.
  • Improvements

    • Enhanced input validation for URL and document type parameters to catch conflicts earlier.
    • Improved error messages with contextual stage labels for better troubleshooting.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR upgrades Drive inspect and Drive meta operations with typed error handling and rate-limit resilience. FetchDriveMeta now returns typed problem errors; DriveInspect adds centralized URL/type validation, configurable retry with exponential backoff, and error annotation with stage labels for better diagnostics.

Changes

Drive Inspect Resilience and Typed Error Handling

Layer / File(s) Summary
Typed error migration in Drive meta
shortcuts/common/drive_meta.go, shortcuts/common/drive_meta_test.go
FetchDriveMeta switches from runtime.CallAPI to runtime.CallAPITyped for the batch_query call. Test assertions now extract typed problem objects and verify error codes via errs.ProblemOf.
Retry infrastructure setup
shortcuts/drive/drive_inspect.go
Adds configurable retry count (driveInspectRateLimitRetries), initial backoff (driveInspectRetryInitialBackoff), and a testable timing hook (driveInspectAfter) for controlling waits in tests.
Validation and retry helper functions
shortcuts/drive/drive_inspect.go
Introduces driveInspectResolveRef (centralized URL/type parsing with conflict/fragment detection), driveInspectFetchMetaTitle (title fetch with retry), driveInspectCallWithRetry (bounded exponential backoff), driveInspectShouldRetry (retry decision via typed problem codes), driveInspectWait (context-aware wait), and driveInspectAnnotateError (stage-based error enrichment).
Entry point refactoring via driveInspectResolveRef
shortcuts/drive/drive_inspect.go
Validate, DryRun, and Execute are refactored to use driveInspectResolveRef for centralized URL/type resolution. DryRun short-circuits to an empty response on resolution failure; Execute replaces inline URL parsing with the resolver.
Retry and error annotation integration
shortcuts/drive/drive_inspect.go
Wiki node resolution wraps the get_node API call in driveInspectCallWithRetry and annotates failures with the "resolve_wiki" stage. Title lookup uses driveInspectFetchMetaTitle (which internally uses retry) and annotates failures with the "query_meta" stage.
Test coverage for validation, error handling, and retry scenarios
shortcuts/drive/drive_inspect_test.go
Test imports now include strings and errs for error assertions. New Validate tests assert failures on --type/--url conflicts and bare tokens with path fragments. Batch-query error test verifies typed problem objects. A new retry scenario test stubs a rate-limit response, overrides driveInspectAfter to control timing, and confirms eventual success.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • larksuite/cli#947: This PR builds directly on the Drive inspect shortcut and Drive meta helper introduced there, extending it with typed error handling and retry resilience.
  • larksuite/cli#1106: The URL parsing refactoring in driveInspectResolveRef relies on recognized resource URL patterns extended by this PR, so URL handling behavior is directly affected.
  • larksuite/cli#1121: Both PRs edit the same DriveInspect execution and validation test functions, with overlapping changes to error assertions and test setup.

Suggested labels

size/L, domain/ccm

Suggested reviewers

  • wittam-01

Poem

🐰 A rabbit's rhyme for retry dreams:
When rate limits block your path,
Exponential backoff soothes the wrath,
Typed errors guide the weary soul,
Stage annotations make us whole,
And retries keep the drive resolve alive! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 6.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description covers the main changes and provides a testing approach, but omits the structured template sections (Summary, Changes, Test Plan, Related Issues). Reformat the description to follow the template structure with clear sections for Summary, Changes, Test Plan checklist, and Related Issues for consistency.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: hardening the drive inspect shortcut's error handling and validation.
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 codex/inspect-cli-precheck

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/L Large or sensitive change across domains or core paths labels Jun 8, 2026
@github-actions

github-actions Bot commented Jun 8, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add larksuite/cli#codex/inspect-cli-precheck -y -g

@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 78.21782% with 22 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.42%. Comparing base (076f4d5) to head (b54abe8).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/drive/drive_inspect.go 78.00% 15 Missing and 7 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1323      +/-   ##
==========================================
- Coverage   71.42%   71.42%   -0.01%     
==========================================
  Files         688      688              
  Lines       65313    65384      +71     
==========================================
+ Hits        46653    46703      +50     
- Misses      15021    15035      +14     
- Partials     3639     3646       +7     

☔ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
shortcuts/drive/drive_inspect_test.go (2)

89-115: ⚡ Quick win

Use the standard test factory helper in these new validate tests.

These new unit tests build runtime context directly via common.TestNewRuntimeContext(...) instead of the repository-standard test factory helper.

As per coding guidelines, **/*_test.go: "Use cmdutil.TestFactory(t, config) for test factories in unit 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/drive/drive_inspect_test.go` around lines 89 - 115, Replace direct
use of common.TestNewRuntimeContext in TestDriveInspectValidate_URLTypeConflict
and TestDriveInspectValidate_BareTokenWithPathFragment with the
repository-standard test factory helper (cmdutil.TestFactory or TestFactory(t,
config)) so the tests construct the runtime via the shared factory; locate the
two tests and change the runtime creation before calling DriveInspect.Validate
to use the standard TestFactory helper with the same config values.

Source: Coding guidelines


583-586: ⚡ Quick win

Isolate config state in this TestFactory-based test.

Add t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) before factory/runtime setup to keep config state isolated per test.

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/drive/drive_inspect_test.go` around lines 583 - 586, In
TestDriveInspectExecute_RetriesRateLimitOnWikiResolve insert a call to
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) before creating the test
factory/runtime (before calling cmdutil.TestFactory or driveTestConfig) so the
TestFactory-based setup uses an isolated per-test config directory; this ensures
config state is isolated for this test.

Source: Coding guidelines

🤖 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_inspect_test.go`:
- Around line 578-579: The test currently uses strings.Contains to check
p.Message but the contract expects a prefix; update the assertion in the test to
use strings.HasPrefix instead of strings.Contains (i.e., replace the condition
with !strings.HasPrefix(p.Message, "query document metadata failed")) and keep
the t.Fatalf message so the test fails if the message does not start with that
prefix (reference p.Message and the failing t.Fatalf call).

---

Nitpick comments:
In `@shortcuts/drive/drive_inspect_test.go`:
- Around line 89-115: Replace direct use of common.TestNewRuntimeContext in
TestDriveInspectValidate_URLTypeConflict and
TestDriveInspectValidate_BareTokenWithPathFragment with the repository-standard
test factory helper (cmdutil.TestFactory or TestFactory(t, config)) so the tests
construct the runtime via the shared factory; locate the two tests and change
the runtime creation before calling DriveInspect.Validate to use the standard
TestFactory helper with the same config values.
- Around line 583-586: In TestDriveInspectExecute_RetriesRateLimitOnWikiResolve
insert a call to t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) before
creating the test factory/runtime (before calling cmdutil.TestFactory or
driveTestConfig) so the TestFactory-based setup uses an isolated per-test config
directory; this ensures config state is isolated for this test.
🪄 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: bfcb63a8-71b0-4caa-8d07-aa8ac572b523

📥 Commits

Reviewing files that changed from the base of the PR and between 076f4d5 and b54abe8.

📒 Files selected for processing (4)
  • shortcuts/common/drive_meta.go
  • shortcuts/common/drive_meta_test.go
  • shortcuts/drive/drive_inspect.go
  • shortcuts/drive/drive_inspect_test.go

Comment thread shortcuts/drive/drive_inspect_test.go
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/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant