Skip to content

fix: align api success envelopes#1489

Merged
liangshuo-1 merged 1 commit into
larksuite:mainfrom
Tantanz20020918:fix/api-envelope-alignment
Jun 17, 2026
Merged

fix: align api success envelopes#1489
liangshuo-1 merged 1 commit into
larksuite:mainfrom
Tantanz20020918:fix/api-envelope-alignment

Conversation

@Tantanz20020918

@Tantanz20020918 Tantanz20020918 commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator

Summary

Align raw API and metadata API success JSON responses with the shortcut envelope contract. This makes successful JSON output consistently expose ok, identity, and business data without leaking Lark transport-level code or msg at the top level.

Changes

  • Add output.WriteSuccessEnvelope and output.SuccessEnvelopeData in internal/output/envelope_success.go.
  • Update raw API response handling in internal/client/response.go and paginated raw API output in cmd/api/api.go.
  • Update metadata API paginated output in cmd/service/service.go and remove the old raw-response jq pagination helper from internal/client/pagination.go.
  • Add paginated content-safety scanning for JSON and streaming formats, including block-mode coverage for streamed pages.
  • Keep shortcut RuntimeContext.StreamPages source-compatible while adapting to the callback error path in shortcuts/common/runner.go.

Test Plan

Local verification:

  • git diff --check
  • gofmt -l cmd/api/api.go cmd/api/api_test.go cmd/service/service.go cmd/service/service_test.go internal/client/client.go internal/client/client_test.go internal/client/pagination.go internal/client/response.go internal/client/response_test.go shortcuts/common/runner.go internal/output/envelope_success.go internal/output/envelope_success_test.go
  • go test ./internal/output ./internal/client ./cmd/api ./cmd/service ./shortcuts/common -count=1
  • make unit-test
  • go vet ./...
  • go mod tidy completed with no go.mod or go.sum changes
  • go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.1.6 run --new-from-rev=origin/main

Manual PR-preview smoke using pkg.pr.new package:

  • Installed the preview package from pkg.pr.new into an isolated npm prefix and invoked /private/tmp/lark-cli-pr-50fd1ee/bin/lark-cli directly, without uninstalling or using the machine-global lark-cli.
  • Used an isolated LARKSUITE_CLI_CONFIG_DIR=/private/tmp/lark-cli-pr-sandbox-50fd1ee, initialized the test app, and completed user device authorization with the test account; no existing ~/.lark-cli login state was used.
  • Created a temporary Base/table, inserted one safe row and one ignore previous instructions marker row, and verified shortcut base +record-list --format json returns ok, identity, and data without top-level code or msg.
  • Verified raw API record-list success returns the same success envelope shape without top-level code or msg.
  • Verified raw API pagination with --page-all --page-size 1 and LARKSUITE_CLI_CONTENT_SAFETY_MODE=warn attaches top-level _content_safety_alert while preserving original data.
  • Verified raw API --jq .data.items[].fields.Note in warn mode returns filtered stdout and still emits the content-safety warning on stderr.
  • Verified raw API block mode exits with code 6, writes no stdout, and returns a structured policy/content_safety error envelope on stderr.
  • Verified metadata API success with calendar calendars list returns ok, identity, and data without top-level code or msg.
  • Created a temporary calendar through metadata API with the safety marker in description; warn mode attaches _content_safety_alert, and block mode returns empty stdout plus a structured policy/content_safety error envelope.
  • Verified raw API and metadata API missing-resource failures both return unified ok=false, identity=user, error=... envelopes.
  • Cleaned up the temporary calendar and Base test records after verification; removed the local preview-package prefix and isolated sandbox directory.

Related Issues

N/A

Summary by CodeRabbit

Release Notes

  • New Features

    • Added structured success envelopes for paginated outputs to standardize response shape.
    • Added content-safety scanning to pagination, with alert warnings in warn mode and blocking in block mode (unsafe pages omitted).
  • Improvements

    • Enhanced --page-all to run safety checks per streamed page (ndjson/table/csv) and to aggregate results consistently for JSON/jq flows.
    • Updated pagination success/error handling to avoid protocol-field leakage and to return clearer, typed error responses.
  • Tests

    • Expanded output-shape and content-safety coverage with stricter JSON assertions.

@CLAassistant

CLAassistant commented Jun 16, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions github-actions Bot added the size/L Large or sensitive change across domains or core paths label Jun 16, 2026
@coderabbitai

coderabbitai Bot commented Jun 16, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Introduces SuccessEnvelopeOptions/WriteSuccessEnvelope output helpers and refactors apiPaginate, servicePaginate, and HandleResponse to emit structured success envelopes with per-page content-safety scanning. StreamPages/paginateLoop gain error-returning callbacks for early halt on content-safety blocks. The PaginateWithJq helper is removed. All call sites and tests are updated accordingly.

Changes

Success Envelope, Content-Safety Pagination, and StreamPages Error Propagation

Layer / File(s) Summary
SuccessEnvelope contract and helpers
internal/output/envelope_success.go, internal/output/envelope_success_test.go
Defines SuccessEnvelopeOptions, SuccessEnvelopeData, and WriteSuccessEnvelope (with content-safety scanning, optional jq filtering, and JSON emission). Tests cover data extraction fallbacks, envelope output field correctness, jq-filtered output, and content-safety warnings/blocks.
StreamPages error propagation and content-safety error refactor
internal/client/client.go, internal/client/client_test.go, internal/client/pagination.go, shortcuts/common/runner.go, errs/subtypes.go, internal/output/emit.go, internal/output/emit_test.go
paginateLoop's onResult callback now returns error to enable early halt; StreamPages's onItems callback updated to func([]interface{}) error with propagation. PaginateWithJq is deleted and its context import removed. Tests updated to match new signatures; a new test verifies pagination stops on callback error. shortcuts/common/runner adapts its callback wrapper. SubtypeContentSafety constant added. Content-safety error construction in emit.go now uses errs.NewContentSafetyError with rules and cause attachment; tests assert the typed error.
HandleResponse output-order reorganization
internal/client/response.go, internal/client/response_test.go
Reorders JSON-response post-parse branching: --output path safety-scans before saving; non-output path emits success envelope for json/jq first; safety scanning only reached for non-JSON formats. Tests assert typed errs.Problem errors and absence of success envelope on error paths.
apiPaginate refactor with envelope and safety scanning
cmd/api/api.go, cmd/api/api_test.go
apiRun passes CommandPath into apiPaginate; jq path uses PaginateAll then WriteSuccessEnvelope; streaming callback performs ScanForSafety per page before formatting; non-list and default paths both write success envelopes. Tests validate envelope structure for bot-mode and batch pages, add batch JSON envelope test, introduce content-safety provider, and test warn/block modes in both JSON and ndjson formats.
servicePaginate refactor with envelope and safety scanning
cmd/service/service.go, cmd/service/service_test.go
serviceMethodRun passes CommandPath into servicePaginate; same envelope/safety-scan pattern as api: jq via PaginateAll, per-page scanning in streaming callback, success envelopes on no-items and default paths. Tests validate bot-mode envelope structure, add content-safety provider tests for warn/block modes in JSON and ndjson, and add business-error raw-response tests for default/streaming/jq paths.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as apiPaginate / servicePaginate
  participant PaginateAll
  participant StreamPages
  participant ScanForSafety
  participant WriteSuccessEnvelope

  alt --jq set
    CLI->>PaginateAll: request, pagOpts
    PaginateAll-->>CLI: aggregated result
    CLI->>WriteSuccessEnvelope: result, {CommandPath, Identity, JqExpr}
    WriteSuccessEnvelope->>ScanForSafety: aggregated data
    ScanForSafety-->>WriteSuccessEnvelope: alert or block error
    WriteSuccessEnvelope-->>CLI: jq-filtered envelope JSON
  else streaming format (ndjson/table/csv)
    CLI->>StreamPages: request, onItems callback, pagOpts
    loop per page
      StreamPages->>ScanForSafety: page items, commandPath, errOut
      alt blocked
        ScanForSafety-->>StreamPages: block error
        StreamPages-->>CLI: halt pagination
      else warn/ok
        ScanForSafety-->>StreamPages: alert (optional)
        StreamPages-->>CLI: format page items to stdout
      end
    end
  else default JSON
    CLI->>PaginateAll: request, pagOpts
    PaginateAll-->>CLI: aggregated result
    CLI->>WriteSuccessEnvelope: result, {CommandPath, Identity}
    WriteSuccessEnvelope->>ScanForSafety: aggregated data
    ScanForSafety-->>WriteSuccessEnvelope: alert or block error
    WriteSuccessEnvelope-->>CLI: envelope JSON
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • larksuite/cli#211: Adds jq-aware pagination via PaginateWithJq/HandleResponse; the current PR refactors those same pagination paths and removes PaginateWithJq in favor of inline PaginateAll + WriteSuccessEnvelope.
  • larksuite/cli#606: Main PR's pagination now invokes output.ScanForSafety(commandPath, ...) and emits SuccessEnvelope/blocking behavior using the content-safety machinery introduced by the retrieved PR (notably internal/output/emit.go / command-path wiring), so they're directly connected at the code integration points.
  • larksuite/cli#984: The main PR's pagination content-safety behavior (emitting/propagating typed errs.ContentSafetyError and its subtype) is built on the typed errs/ error-contract additions from the retrieved PR, so the changes are related at the error-type level.

Suggested labels

size/XL, feature

Suggested reviewers

  • liangshuo-1

Poem

🐇 Hoppity-hop through pages we go,
Each JSON envelope perfectly in tow,
Safety scans guard what the data might say,
Blocked pages skipped, let the safe ones play,
With envelopes sealed and jq filters bright,
The rabbit ships output that's structured and right! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% 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 'fix: align api success envelopes' directly describes the main change: standardizing success JSON responses across API layers.
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.
Description check ✅ Passed The PR description is comprehensive and well-structured, covering all required template sections with substantive detail.

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

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

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.

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
internal/client/client_test.go (1)

110-192: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add a dedicated error-path test for the new callback contract.

These updates only adapt callback signatures, but they don’t verify the new behavior: onItems returning an error should halt pagination and propagate that error from StreamPages. Please add a test that returns a sentinel error from onItems and asserts both propagation and early stop semantics.

As per coding guidelines, “Every behavior change needs a test alongside the change.”

🤖 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 `@internal/client/client_test.go` around lines 110 - 192, Add a new test
function that verifies the error-handling behavior of the StreamPages method
when the onItems callback returns an error. Create a test that configures a mock
response with multiple pages or items, then have the onItems callback return a
sentinel error (for example, a custom error or errors.New("test error")), and
assert that StreamPages propagates that error and halts pagination early
(confirming that not all items were processed). This test should demonstrate
both the error propagation and the early-stop semantics of the callback
contract.

Source: Coding guidelines

cmd/api/api_test.go (1)

358-390: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Strengthen typed error assertions for the newly added API error paths.

Line 388 only verifies that the error is typed, and Line 622 still validates behavior via message substring. For these error-path tests, please assert typed metadata (category/subtype, and param where applicable) plus cause preservation, not just presence/string checks.

As per coding guidelines, *_test.go error-path tests must assert typed metadata via errs.ProblemOf and cause preservation rather than message substrings. Based on learnings, when asserting param, use errors.As(..., *errs.ValidationError) since errs.ProblemOf does not expose Param.

Also applies to: 583-624

🤖 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 `@cmd/api/api_test.go` around lines 358 - 390, The error-path tests in
TestApiCmd_PageAll_NonBatchAPI_ErrorStillOutputsJSON and the test at lines
583-624 are using weak assertions that only check for error presence and message
substrings instead of verifying typed error metadata and cause preservation.
Replace the simple typed error checks (using errs.ProblemOf for presence only)
and string substring validations with assertions that verify the complete typed
metadata including category, subtype, and param fields where applicable. When
asserting the param field, use errors.As to extract the ValidationError type
directly since errs.ProblemOf does not expose Param, and ensure cause
preservation is also validated as part of these assertions.

Sources: Coding guidelines, Learnings

cmd/service/service.go (1)

666-668: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Missing raw JSON output on business error paths in servicePaginate. Both the streaming and default branches omit the output.FormatValue(out, result, output.FormatJSON) call before returning a business error, unlike the jq path in this file (lines 633-636) and all three paths in api.go. This prevents users from inspecting the actual API response when a business error occurs.

  • cmd/service/service.go#L666-L668: Add output.FormatValue(out, result, output.FormatJSON) before returning apiErr in the streaming path.
  • cmd/service/service.go#L684-L686: Add output.FormatValue(out, result, output.FormatJSON) before returning apiErr in the default path.
🤖 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 `@cmd/service/service.go` around lines 666 - 668, The servicePaginate function
in cmd/service/service.go omits raw JSON output on business error paths,
preventing users from inspecting API responses when errors occur. In
cmd/service/service.go at lines 666-668, add output.FormatValue(out, result,
output.FormatJSON) before returning apiErr in the streaming path where checkErr
returns a non-nil error. In cmd/service/service.go at lines 684-686, add the
same output.FormatValue(out, result, output.FormatJSON) call before returning
apiErr in the default path where checkErr returns a non-nil error. This ensures
both branches output the raw JSON response before returning, consistent with the
jq path and the patterns used in api.go.
🤖 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 `@cmd/service/service_test.go`:
- Around line 595-639: The error-path tests in
TestServiceMethod_PageAll_StreamFormatBlockSkipsBlockedPage (595-639), the test
at 649-675, and the test at 866-895 currently only validate error message
presence using string contains checks, but should instead validate typed error
metadata and preserved cause chains. For each affected test, replace the
message-only assertions with assertions that check the error's typed metadata
using errors.As to validate fields like category, subtype, and param when
relevant (since errs.ProblemOf only exposes problem-level fields), and verify
the cause chain is preserved by checking that the underlying error wraps the
expected root cause. Update all three test locations to follow this pattern
consistently.

---

Outside diff comments:
In `@cmd/api/api_test.go`:
- Around line 358-390: The error-path tests in
TestApiCmd_PageAll_NonBatchAPI_ErrorStillOutputsJSON and the test at lines
583-624 are using weak assertions that only check for error presence and message
substrings instead of verifying typed error metadata and cause preservation.
Replace the simple typed error checks (using errs.ProblemOf for presence only)
and string substring validations with assertions that verify the complete typed
metadata including category, subtype, and param fields where applicable. When
asserting the param field, use errors.As to extract the ValidationError type
directly since errs.ProblemOf does not expose Param, and ensure cause
preservation is also validated as part of these assertions.

In `@cmd/service/service.go`:
- Around line 666-668: The servicePaginate function in cmd/service/service.go
omits raw JSON output on business error paths, preventing users from inspecting
API responses when errors occur. In cmd/service/service.go at lines 666-668, add
output.FormatValue(out, result, output.FormatJSON) before returning apiErr in
the streaming path where checkErr returns a non-nil error. In
cmd/service/service.go at lines 684-686, add the same output.FormatValue(out,
result, output.FormatJSON) call before returning apiErr in the default path
where checkErr returns a non-nil error. This ensures both branches output the
raw JSON response before returning, consistent with the jq path and the patterns
used in api.go.

In `@internal/client/client_test.go`:
- Around line 110-192: Add a new test function that verifies the error-handling
behavior of the StreamPages method when the onItems callback returns an error.
Create a test that configures a mock response with multiple pages or items, then
have the onItems callback return a sentinel error (for example, a custom error
or errors.New("test error")), and assert that StreamPages propagates that error
and halts pagination early (confirming that not all items were processed). This
test should demonstrate both the error propagation and the early-stop semantics
of the callback contract.
🪄 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: bafc2526-b813-464a-8093-2dfd326c788b

📥 Commits

Reviewing files that changed from the base of the PR and between ed7fdd1 and 0be7518.

📒 Files selected for processing (12)
  • cmd/api/api.go
  • cmd/api/api_test.go
  • cmd/service/service.go
  • cmd/service/service_test.go
  • internal/client/client.go
  • internal/client/client_test.go
  • internal/client/pagination.go
  • internal/client/response.go
  • internal/client/response_test.go
  • internal/output/envelope_success.go
  • internal/output/envelope_success_test.go
  • shortcuts/common/runner.go
💤 Files with no reviewable changes (1)
  • internal/client/pagination.go

Comment thread cmd/service/service_test.go
@Tantanz20020918
Tantanz20020918 force-pushed the fix/api-envelope-alignment branch from 0be7518 to d0b721c Compare June 17, 2026 03:54

@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

🤖 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 `@internal/output/envelope_success.go`:
- Around line 47-51: The issue is that when a jq expression filters the envelope
output, the content-safety alert can be filtered away, exposing flagged data
without any visible warning. Before calling JqFilter when opts.JqExpr is not
empty, check if scanResult.Alert exists and if so, emit a warning message to
stderr to ensure the alert is visible even when jq filters the envelope fields.
Additionally, add a regression test case that verifies the stderr warning is
emitted when both a content-safety alert is present and jq filtering is applied.
🪄 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: 806377be-e5e3-44a2-98b7-2672f4216d49

📥 Commits

Reviewing files that changed from the base of the PR and between 0be7518 and d0b721c.

📒 Files selected for processing (12)
  • cmd/api/api.go
  • cmd/api/api_test.go
  • cmd/service/service.go
  • cmd/service/service_test.go
  • internal/client/client.go
  • internal/client/client_test.go
  • internal/client/pagination.go
  • internal/client/response.go
  • internal/client/response_test.go
  • internal/output/envelope_success.go
  • internal/output/envelope_success_test.go
  • shortcuts/common/runner.go
💤 Files with no reviewable changes (1)
  • internal/client/pagination.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • shortcuts/common/runner.go
  • internal/output/envelope_success_test.go
  • cmd/service/service.go
  • internal/client/response_test.go
  • internal/client/client.go
  • cmd/api/api.go

Comment thread internal/output/envelope_success.go
@Tantanz20020918
Tantanz20020918 force-pushed the fix/api-envelope-alignment branch from d0b721c to c8408b7 Compare June 17, 2026 06:09

@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 (1)
internal/output/envelope_success_test.go (1)

55-76: ⚡ Quick win

Avoid whitespace-sensitive JSON assertions in this test.

These strings.Contains checks couple the test to PrintJson formatting (spaces/newlines), so harmless formatting changes can fail the test. Parse JSON and assert fields structurally instead.

Proposed refactor
 import (
+	"encoding/json"
 	"strings"
 	"testing"

 	extcs "github.com/larksuite/cli/extension/contentsafety"
 )
@@
 	got := out.String()
-	for _, want := range []string{`"ok": true`, `"identity": "bot"`, `"data": {`, `"id": "1"`} {
-		if !strings.Contains(got, want) {
-			t.Fatalf("output missing %s:\n%s", want, got)
-		}
-	}
-	if strings.Contains(got, `"code"`) || strings.Contains(got, `"msg"`) {
-		t.Fatalf("output leaked Lark protocol fields:\n%s", got)
-	}
-	if strings.Contains(got, `_content_safety_alert`) {
-		t.Fatalf("output should omit empty content-safety alert:\n%s", got)
-	}
+	var env map[string]interface{}
+	if err := json.Unmarshal([]byte(got), &env); err != nil {
+		t.Fatalf("invalid json output: %v\n%s", err, got)
+	}
+	if env["ok"] != true || env["identity"] != "bot" {
+		t.Fatalf("unexpected envelope: %#v", env)
+	}
+	data, ok := env["data"].(map[string]interface{})
+	if !ok || data["id"] != "1" {
+		t.Fatalf("unexpected data payload: %#v", env["data"])
+	}
+	if _, exists := env["code"]; exists {
+		t.Fatalf("output leaked protocol field code: %#v", env)
+	}
+	if _, exists := env["msg"]; exists {
+		t.Fatalf("output leaked protocol field msg: %#v", env)
+	}
+	if _, exists := env["_content_safety_alert"]; exists {
+		t.Fatalf("output should omit empty content-safety alert: %#v", env)
+	}
 }
🤖 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 `@internal/output/envelope_success_test.go` around lines 55 - 76, The test
TestWriteSuccessEnvelope_PrintsShortcutCompatibleEnvelope uses strings.Contains
to verify JSON output formatting, which couples the test to whitespace and
formatting decisions. Replace these string-based assertions with JSON parsing:
unmarshal the output string into a map or appropriate struct, then assert on the
actual field values and structure instead. This will make the test robust to
harmless formatting changes while still validating that the correct fields and
values are present in the envelope.
🤖 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 `@internal/output/envelope_success_test.go`:
- Around line 96-125: Add a new test function following the pattern of
TestWriteSuccessEnvelope_JqWarnsWhenSafetyAlertFiltered to cover the blocked
safety mode path. Set the environment variable LARKSUITE_CLI_CONTENT_SAFETY_MODE
to "block" with the same mockProvider setup, then call WriteSuccessEnvelope and
verify that it returns an error rather than nil. Assert that the error has the
correct type metadata (not just string message matching) and that the cause
chain is preserved, while also verifying that the stdout output buffer remains
empty when the block mode triggers an early return.

---

Nitpick comments:
In `@internal/output/envelope_success_test.go`:
- Around line 55-76: The test
TestWriteSuccessEnvelope_PrintsShortcutCompatibleEnvelope uses strings.Contains
to verify JSON output formatting, which couples the test to whitespace and
formatting decisions. Replace these string-based assertions with JSON parsing:
unmarshal the output string into a map or appropriate struct, then assert on the
actual field values and structure instead. This will make the test robust to
harmless formatting changes while still validating that the correct fields and
values are present in the envelope.
🪄 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: 5f13e644-ace6-46db-97ef-145d6de58984

📥 Commits

Reviewing files that changed from the base of the PR and between d0b721c and c8408b7.

📒 Files selected for processing (12)
  • cmd/api/api.go
  • cmd/api/api_test.go
  • cmd/service/service.go
  • cmd/service/service_test.go
  • internal/client/client.go
  • internal/client/client_test.go
  • internal/client/pagination.go
  • internal/client/response.go
  • internal/client/response_test.go
  • internal/output/envelope_success.go
  • internal/output/envelope_success_test.go
  • shortcuts/common/runner.go
💤 Files with no reviewable changes (1)
  • internal/client/pagination.go
🚧 Files skipped from review as they are similar to previous changes (10)
  • internal/client/client_test.go
  • shortcuts/common/runner.go
  • internal/client/response_test.go
  • internal/client/response.go
  • internal/output/envelope_success.go
  • internal/client/client.go
  • cmd/service/service.go
  • cmd/api/api_test.go
  • cmd/api/api.go
  • cmd/service/service_test.go

Comment thread internal/output/envelope_success_test.go
@Tantanz20020918
Tantanz20020918 force-pushed the fix/api-envelope-alignment branch from c8408b7 to 50fd1ee Compare June 17, 2026 07:03
@codecov

codecov Bot commented Jun 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 79.23077% with 27 lines in your changes missing coverage. Please review.
✅ Project coverage is 73.46%. Comparing base (c0730b4) to head (50fd1ee).
⚠️ Report is 17 commits behind head on main.

Files with missing lines Patch % Lines
cmd/service/service.go 77.77% 7 Missing and 1 partial ⚠️
internal/client/response.go 57.14% 6 Missing ⚠️
cmd/api/api.go 87.87% 2 Missing and 2 partials ⚠️
shortcuts/common/runner.go 0.00% 4 Missing ⚠️
internal/client/client.go 75.00% 3 Missing ⚠️
internal/output/envelope_success.go 92.00% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1489      +/-   ##
==========================================
+ Coverage   73.35%   73.46%   +0.11%     
==========================================
  Files         750      754       +4     
  Lines       69250    70188     +938     
==========================================
+ Hits        50799    51565     +766     
- Misses      14711    14816     +105     
- Partials     3740     3807      +67     

☔ 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

github-actions Bot commented Jun 17, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add Tantanz20020918/cli#fix/api-envelope-alignment -y -g

@Tantanz20020918
Tantanz20020918 force-pushed the fix/api-envelope-alignment branch 3 times, most recently from 4ac9e0f to 2c3331e Compare June 17, 2026 09:26
@Tantanz20020918
Tantanz20020918 force-pushed the fix/api-envelope-alignment branch from 2c3331e to 3944eda Compare June 17, 2026 09:31
@github-actions

Copy link
Copy Markdown

PR Quality Summary

The semantic review system could not produce a fully trusted result. This is not reported as a code defect.

System status

  • semantic review degraded: semantic review request too large (endpoint=https[:]//ark.cn-beijing.volces.com/api/plan/v3/chat/completions model=deepseek-v4-pro response_format=none attempt=1/3 bytes=207211 limit=65536) — Action: inspect deterministic quality-gate diagnostics

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants