Files
larksuite__cli/shortcuts/sheets/result_annotations.go
xiongyuanwen-byted decc9549b5 refactor(sheets): keep the success path off stderr (#2533)
* feat(sheets): reject local-office tokens in +workbook-export

A locally opened Office file (a local_office_ / fake_office_ token, or an
interleaved OFL0X one) names a file the Lark client is showing, not a cloud
document, so the drive export task can only fail on the backend -- and it
fails late, after the create and poll round trips, with an opaque message.

Refuse it up front with a typed failed_precondition that says the workbook is
already a file on disk, and points at +workbook-import for callers who want a
cloud spreadsheet they can export later. The check runs in Validate (so
--dry-run is covered too) and again after the wiki hop in Execute, where the
real spreadsheet token is first known.

* refactor(sheets): report success-path advisories in the result, not on stderr

Every sheets shortcut that had something to say on a successful run said it on
stderr: ignored sub-op locators, emulated dimension semantics, the deprecated
--dimension/--count and +cells-batch-set-style spellings, the dropdown
option-error steer, and the upload/export stage lines in the compatibility
layer. PowerShell's native-command handling and most agent harnesses read
non-empty stderr as failure, so a working call reported itself as an error --
and the facts a caller actually needed sat outside the JSON they parse.

Pure stage text ("Writing image", "Waiting for export task") is deleted: it
duplicates what the result already proves. Everything decision-relevant moves
into the payload:

  - data.warnings           ignored locators, colliding freezes, the dropdown
                            option-error steer (also shown in --dry-run now)
  - data.effective_operation +dim-insert's anchor shift under --inherit-style
                            before, and the whole (rows, cols) state a freeze
                            leaves behind
  - data.deprecation        +cells-batch-set-style and +dim-freeze's legacy
                            flag pair, under a key of its own rather than
                            mixed into warnings
  - data.upload             how +media-upload sent the file

Clean calls keep their exact previous payload shape: every field above is
added only when it has something to report.

Scope is shortcuts/sheets/** on purpose. The remaining success-path stderr in
this domain comes from shared code (the drive export/import core behind
+workbook-export / +workbook-import, the multipart media helper, the auto-grant
helper), which other domains share; cleaning those up belongs to their own
change. The one sheets-owned exception is +workbook-import's extension
correction, which has no slot in the import core's output envelope -- it is
documented at the call site and allowlisted in the guard test.

Tests pin the contract (a successful run leaves stderr empty) and each new
field, plus a source scan that stops new direct ErrOut writes from appearing.

* docs(sheets): point the dropdown option-error warning at data.warnings

The --source-range flag help still told callers the option-error steer arrives
on stderr; it now rides in the result. Mirrors the same edit in the upstream
spec (canonical-spec/spec-tables/flags.json), so the next sync is a no-op.

* fix(sheets): keep export identifiers in +export output, tighten the stderr guard

Review follow-ups on the success-path stderr change:

- +export --output-path lost file_token: on the download branch the token
  reached the caller only through the deleted "Export complete: file_token=…"
  stderr line, and the payload carried just saved_path and size_bytes. Both
  file_token and ticket now ride in the download result, so a caller can
  re-download or resume without re-running the export.

- The stderr guard allowlisted a whole file, hiding any future write in it.
  It now matches one exact statement in one file and asserts that write still
  exists, so both a new write and a stale exception fail the test.

- The contract comments claimed more than the tests prove. They now state
  that only sheets-OWNED code is silent, name the three commands whose noise
  comes from shared implementations (+workbook-export, +workbook-import,
  +media-upload over 20MB), and a new test pins that the shared export core
  does still write -- failing, by design, once that core is cleaned up.

* fix(drive): keep the export and import cores off stderr on success

+workbook-export and +workbook-import delegate to drive.RunExport /
drive.RunImport, so the sheets success-path contract could not hold while
those cores narrated every step: task creation, each poll attempt, completion,
"still in progress", and the import's media upload. Callers that read
non-empty stderr as failure saw a finished export report itself as an error.

The stage text is deleted -- ticket, ready, status, file_token, token and
next_command are all already in the payload. What the narration alone carried
moves into the result:

  - poll               attempts / transient_failures / last_error, added only
                       when a poll actually had to be retried, so a caller can
                       tell a clean run from one that limped to the finish
  - warnings           markdown export falling back to the token as file name
                       after a failed title lookup
  - input_corrections  a caller-supplied record of inputs the CLI rewrote
                       before the request ran; sheets +workbook-import uses it
                       for a mislabeled .xls that is really an .xlsx, which was
                       its last stderr write

drive +export / +import get the same treatment, since they share these cores.
Clean runs keep their exact previous payload shape.

With this, the sheets stderr guard needs no allowlist, and the contract test
covers both workbook commands end to end. Two shared paths a sheets caller can
still reach stay noisy and are named in the contract comment: multipart media
upload over 20MB, and the bot-identity auto-grant warning.

* test(sheets): cover the annotation shapes and both guard call sites

Review follow-ups, all test-side except one comment:

- +dim-insert's effective_operation had no test: a regression could drop the
  emulated-anchor block and still keep stderr empty. Now asserted field by
  field, plus the negative case (--inherit-style after rewrites nothing, so it
  must not gain the block).

- The local-office guard's second call site had no test. A /wiki/ URL only
  reveals its backing token after get_node runs in Execute, so that branch is
  now covered, asserting both the typed rejection and that no export task was
  created.

- annotateSheetsResult's three payload shapes are pinned: object annotated in
  place, array/scalar preserved under `result`, and an empty tool result left
  without an invented `result: null`. The doc comment now spells out that last
  case instead of lumping it in with non-object output.

- The export poll summary test asserted transient_failures but not attempts,
  so a wrong or missing count would have passed.

* fix: preserve recovery state on failure paths and TTY liveness during polls

Review round 2. Removing the success-path narration also removed information
from paths that fail after remote work has started, and removed the only
liveness signal an interactive user had:

- drive +import / sheets +workbook-import: once the import task exists, the
  ticket is the only handle back to it. A poll failure returned bare, so the
  ticket -- previously visible through the polling line -- was lost. It now
  rides on the typed error together with the +task_result command.

- sheets +export --output-path: a download or save failure happens after the
  artifact is ready, so the error now carries ticket, file_token and the
  +export-download command; re-running the whole export is not the recovery.
  A poll timeout carries the ticket for the same reason.

- sheets +batch-update / +batch-chart-*: batch_update is fail-fast without
  rollback, so the ignored-locator and colliding-freeze advisories matter most
  exactly when the call fails part-way -- they decide the safe retry set. They
  are now attached to the typed error's hint as well as the success payload.

- Bounded polls and the import upload are wrapped in RuntimeContext.StartSpinner,
  which is gated on StderrIsTerminal and is a strict no-op for pipes, CI and
  captured output. A human terminal gets liveness back; a machine caller's
  stderr stays empty (the contract tests, which capture stderr, still pass).

+workbook-export's rejection of Office tokens also stopped assuming the caller
holds the file: a local_office_ / fake_office_ prefix means the workbook is
already on their disk, but an interleaved OFL0X token is a file stored in Lark
that may never have been downloaded, so that class is now pointed at
drive +download (then +workbook-import if they want a Lark spreadsheet).

Each behaviour above has a regression test; httpmock's CapturedBodies doc
comment is corrected, since it is appended on every match, not only for
Reusable stubs.
2026-08-28 12:48:19 +08:00

120 lines
4.8 KiB
Go

// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
// Result annotations: how a sheets shortcut reports something that is true of
// the call but is not part of the tool's own payload — an input it ignored, a
// semantic it emulated, a server-side state the request will produce.
//
// These used to be printed to stderr on the success path. That made every such
// call indistinguishable from a failure to any runner that treats non-empty
// stderr as an error (PowerShell's native-command handling, most agent
// harnesses), and it put decision-relevant facts outside the one artifact a
// caller actually parses. They now ride in the success payload instead:
// `warnings` for things the caller may need to act on, and named fields
// (`effective_operation`, `ignored_inputs`) for facts about the request.
//
// A deprecation steer is a fourth kind: it describes the CLI surface rather
// than the resource, so it gets its own `deprecation` key instead of being
// mixed into `warnings` (see annotateSheetsDeprecation).
import (
"strings"
"github.com/larksuite/cli/errs"
)
// annotateSheetsResult attaches key/value to a tool result on its way to
// stdout.
//
// callTool returns whatever JSON the tool emitted: usually an object, but
// possibly nothing at all (empty output, returned as nil) or — for a tool that
// answers with an array or a scalar — a non-object. An annotation must never be
// silently dropped just because of the payload's shape:
//
// - object annotated in place, keeping its shape (every case in practice)
// - array /
// scalar wrapped as {"result": <original>, <key>: <value>}, so the tool's
// own answer survives alongside the annotation
// - nil the tool returned no result, so there is nothing to preserve and
// the payload is just {<key>: <value>}. Emitting "result": null
// would invent a field naming a result that does not exist.
func annotateSheetsResult(out interface{}, key string, value interface{}) interface{} {
switch typed := out.(type) {
case map[string]interface{}:
typed[key] = value
return typed
case nil:
return map[string]interface{}{key: value}
default:
return map[string]interface{}{"result": out, key: value}
}
}
// appendSheetsWarnings adds one or more advisory messages to a tool result's
// `warnings` array. No warnings means the payload is returned untouched, so a
// clean call keeps its exact previous shape.
func appendSheetsWarnings(out interface{}, warnings []string) interface{} {
if len(warnings) == 0 {
return out
}
existing, _ := out.(map[string]interface{})
if existing != nil {
if prior, ok := existing["warnings"].([]string); ok {
return annotateSheetsResult(out, "warnings", append(prior, warnings...))
}
if prior, ok := existing["warnings"].([]interface{}); ok {
merged := make([]interface{}, 0, len(prior)+len(warnings))
merged = append(merged, prior...)
for _, w := range warnings {
merged = append(merged, w)
}
return annotateSheetsResult(out, "warnings", merged)
}
}
return annotateSheetsResult(out, "warnings", warnings)
}
// attachSheetsWarningsToError carries advisories out on the failure path.
//
// Warnings like "this sub-op's locator was ignored" or "these two freezes
// overwrite each other" describe the REQUEST, not its outcome: they say which
// spreadsheet was actually targeted and which sub-ops are safe to resend. That
// is most valuable exactly when the call failed part-way, so they cannot live
// only on the success payload. They ride on the typed error's hint, which
// keeps the failure a single JSON envelope on stderr.
//
// The error's category / subtype / code / log_id are untouched, per the error
// contract's "propagate typed errors unchanged".
func attachSheetsWarningsToError(err error, warnings []string) error {
if err == nil || len(warnings) == 0 {
return err
}
note := "advisories for this request (they decide the safe retry set):\n" + strings.Join(warnings, "\n")
if p, ok := errs.ProblemOf(err); ok {
if strings.TrimSpace(p.Hint) != "" {
p.Hint = p.Hint + "\n" + note
} else {
p.Hint = note
}
}
return err
}
// annotateSheetsDeprecation attaches a steer off a superseded command or flag
// spelling. An empty note leaves the payload untouched.
//
// It gets a dedicated `deprecation` key rather than joining `warnings`, which
// are about the request's effect on the sheet. The natural home is the
// envelope's meta — it is metadata about the CLI surface, not about the
// resource — but meta lives in the shared output package, and this change is
// scoped to the sheets domain. Moving it there is a one-line change once the
// shared envelope gains the field.
func annotateSheetsDeprecation(out interface{}, note string) interface{} {
if note == "" {
return out
}
return annotateSheetsResult(out, "deprecation", note)
}