Skip to content

feat(im/chat-list): support --types flag for listing p2p single chats#1077

Open
shifengjuan-dev wants to merge 1 commit into
larksuite:mainfrom
shifengjuan-dev:feat/chat-list-types-p2p
Open

feat(im/chat-list): support --types flag for listing p2p single chats#1077
shifengjuan-dev wants to merge 1 commit into
larksuite:mainfrom
shifengjuan-dev:feat/chat-list-types-p2p

Conversation

@shifengjuan-dev
Copy link
Copy Markdown
Collaborator

@shifengjuan-dev shifengjuan-dev commented May 25, 2026

Summary

  • Add --types CSV flag to lark-cli im +chat-list, supported values: group / p2p / p2p,group. Backed by the new types query parameter on GET /open-apis/im/v1/chats.
  • Default behavior unchanged: omitting --types returns groups only (backward compatible).
  • Bot identity handling: reject --types=p2p alone at validation; for mixed --types=p2p,group strip p2p and send types=group, surfacing the request-level adjustment two ways — a warning: bot_strip_p2p: ... line on stderr (matches the warning: <code>: <message> convention in shortcuts/common/runner.go) and a structured {code, message} entry under outData["notices"] in stdout JSON. The notices slot is a separate top-level key from outData["filter"] (which stays scoped to --exclude-muted), so the two never collide and no priority resolution is needed when both fire. DryRun emits the same stderr warning for parity with shortcuts/drive/drive_search.go.
  • Renders new response fields (chat_mode / p2p_target_type / p2p_target_id) conditionally in table output; passes them through unchanged in JSON.
  • Documentation updated across three layers: Shortcut.Description, skills/lark-im/SKILL.md, and skills/lark-im/references/lark-im-chat-list.md.

Test Plan

  • go build ./... succeeds
  • go test ./shortcuts/im/... -count=1 passes (added ~10 new test functions covering normalizeTypes, resolveTypes, Validate, DryRun, Execute integration with HTTP mock, filter priority, p2p row rendering, defensive chat_mode-absent fallback, and user+mute+p2p mute-filter path)
  • go vet ./shortcuts/im/... clean
  • Manual sanity check on BOE/Online: lark-cli im +chat-list --as user --types p2p,group --format json returns at least one row with chat_mode="p2p" and a non-empty p2p_target_id (spec risk readme 优化建议 #2)

Summary by CodeRabbit

  • New Features

    • Added --types flag to list groups and/or P2P chats; input is trimmed, lowercased, deduped and preserves order.
    • Table output now includes chat_mode; P2P rows show target type and target id when present.
  • Bug Fixes

    • Empty --types no longer sends a types parameter (backwards compatible).
    • Bot identity: P2P-only requests are rejected; P2P is silently removed from mixed requests.
  • Documentation

    • Docs updated for --types usage, P2P fields, and user vs. bot behavior.
  • Tests

    • Added coverage for types normalization, identity rules, request params, rendering, dry-run and mute filtering.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 25, 2026

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
📝 Walkthrough

Walkthrough

Adds a --types CSV flag to im +chat-list with normalization and identity-aware resolution: users may request p2p, bots have p2p stripped; request params include types only when non-empty; responses include chat_mode and conditional p2p_target_* fields. Tests and docs updated.

Changes

P2P Chat Filtering Feature

Layer / File(s) Summary
Flag definition and imports
shortcuts/im/im_chat_list.go
Adds strings import and the --types flag; DryRun/Validate/Execute parse/resolve --types and pass effective types into request construction.
Response rendering and row fields
shortcuts/im/im_chat_list.go, shortcuts/im/im_chat_list_test.go
Rendered rows now include chat_mode and, when chat_mode is p2p, conditional p2p_target_type/p2p_target_id; defensive rendering omits these when absent.
Type normalization and request shaping
shortcuts/im/im_chat_list.go
Adds normalizeTypes and resolveTypes to trim/lowercase/validate/dedupe CSV input and apply bot-side p2p stripping; buildChatListParams accepts effectiveTypes and includes types only when non-empty.
Tests: infra, unit and execution
shortcuts/im/im_chat_list_test.go
Refactors test runtime to be identity-aware, registers flags appropriately, adds helpers, and adds tests validating normalize/resolve/Validate, dry-run passthrough, bot stripping, pretty output rendering, defensive rendering, and --exclude-muted filtering for users.
Skill docs and reference updates
skills/lark-im/SKILL.md, skills/lark-im/references/lark-im-chat-list.md
Docs updated to document --types usage, default groups-only behavior, p2p output fields, bot handling (reject/downgrade/strip), CLI examples, and troubleshooting/error text.

Sequence Diagram

sequenceDiagram
  participant Caller as User/Bot CLI
  participant Flags as "--types" flag
  participant Validate as ImChatList.Validate
  participant Normalize as normalizeTypes
  participant Resolve as resolveTypes
  participant Request as buildChatListParams
  participant API as Lark API
  participant Renderer as Renderer

  Caller->>Flags: provide --types CSV
  Flags->>Validate: parse & validate
  Validate->>Normalize: normalizeTypes()
  Normalize->>Resolve: normalized list
  Resolve->>Resolve: apply identity rules (user passthrough, bot strip p2p)
  Resolve-->>Request: effectiveTypes (CSV)
  Request->>API: HTTP call (includes types=... only if non-empty)
  API-->>Renderer: response (may include chat_mode, p2p_target_*)
  Renderer->>Caller: table/JSON output with fields/hints
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • YangJunzhou-01
  • sammi-bytedance

🐰 I trimmed CSVs under moonlit skies,
Lowercased hops and removed duplicate lies,
Bots politely drop p2p from their trail,
Users keep DMs intact down the mail,
Tests nibble crumbs and the output replies.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% 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 directly and clearly describes the main feature addition: support for a new --types flag enabling p2p chat listing.
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 pull request description covers the summary, changes, and test plan, but the Related Issues section is present yet marked as 'None'.

✏️ 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.

@github-actions github-actions Bot added domain/im PR touches the im domain size/M Single-domain feat or fix with limited business impact labels May 25, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented May 25, 2026

Codecov Report

❌ Patch coverage is 96.61017% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.05%. Comparing base (9d4233b) to head (7b2bf99).
⚠️ Report is 13 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/im/im_chat_list.go 96.61% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1077      +/-   ##
==========================================
+ Coverage   67.79%   68.05%   +0.26%     
==========================================
  Files         591      601      +10     
  Lines       55238    55821     +583     
==========================================
+ Hits        37449    37990     +541     
- Misses      14680    14688       +8     
- Partials     3109     3143      +34     

☔ View full report in Codecov by Sentry.
📢 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 May 25, 2026

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add shifengjuan-dev/lark-cli#feat/chat-list-types-p2p -y -g

@shifengjuan-dev shifengjuan-dev force-pushed the feat/chat-list-types-p2p branch 2 times, most recently from 4a6369a to c3db76e Compare May 25, 2026 12:17
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: 1

Caution

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

⚠️ Outside diff range comments (1)
shortcuts/im/im_chat_list.go (1)

65-103: ⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Missing bot_strip_p2p filter metadata when bot requests mixed types.

The bot downgrade is applied, but no filter.applied="bot_strip_p2p" notice is emitted, so the documented/output contract for downgraded bot requests is not met (and cannot override exclude-muted metadata as specified).

Also applies to: 194-213

🤖 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/im/im_chat_list.go` around lines 65 - 103, resolveTypes(runtime)
currently returns a second value that is ignored; capture that second return
(e.g., downgraded or botStripP2P bool) and use it to emit the proper filter
metadata when a bot request is downgraded: change "effective, _ :=
resolveTypes(runtime)" to capture the flag, and after computing outData and
mfOut, if runtime.IsBot() && downgraded then set outData["filter"] =
MuteFilterMetaToMap(MuteFilterMeta{Applied:"bot_strip_p2p", ...}) or merge with
existing mfOut.Meta so that mfOut.Meta.Applied/"filter" reflects
"bot_strip_p2p"; reference resolveTypes, effective, runtime.IsBot(),
MaybeApplyMuteFilter, mfOut.Meta.Applied and outData["filter"] when making this
change.
🧹 Nitpick comments (1)
shortcuts/im/im_chat_list_test.go (1)

26-57: ⚡ Quick win

Align test runtime setup with repo test guidelines.

The helper builds runtime context without cmdutil.TestFactory(t, config) and without config-dir isolation via t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()). Please switch the helper to the standard test factory pattern so all added tests inherit the expected isolation behavior.

As per coding guidelines **/*_test.go: "Use cmdutil.TestFactory(t, config) for test factories in unit tests" and "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/im/im_chat_list_test.go` around lines 26 - 57, The helper
newChatListTestRuntimeContextWithIdentity currently builds a cobra.Command and
sets flags manually; replace that with the repo standard test factory pattern:
call t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) to isolate config, create
a factory via cmdutil.TestFactory(t, config) (or cmdutil.TestFactory(t, nil) if
no extra config), and pass that factory into
common.TestNewRuntimeContextWithIdentity instead of constructing cmd directly;
ensure you still set the same flags on the returned command/context so existing
tests keep the same behavior.
🤖 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 `@skills/lark-im/references/lark-im-chat-list.md`:
- Around line 89-90: Update the doc text for the bot downgrade examples to
reflect the actual runtime behavior: when using the CLI flag combination `--as
bot --types=p2p,group` the service emits metadata
`filter.applied="bot_strip_p2p"` (and you should mention interaction with
`filter-priority`) rather than silently stripping `p2p`; change the example
lines and any related examples in this section to state that metadata is
included in the JSON response and show the proper emitted field
(`filter.applied="bot_strip_p2p"`) and how it affects results; ensure all other
examples in the same section are updated consistently to mention the emitted
metadata.

---

Outside diff comments:
In `@shortcuts/im/im_chat_list.go`:
- Around line 65-103: resolveTypes(runtime) currently returns a second value
that is ignored; capture that second return (e.g., downgraded or botStripP2P
bool) and use it to emit the proper filter metadata when a bot request is
downgraded: change "effective, _ := resolveTypes(runtime)" to capture the flag,
and after computing outData and mfOut, if runtime.IsBot() && downgraded then set
outData["filter"] = MuteFilterMetaToMap(MuteFilterMeta{Applied:"bot_strip_p2p",
...}) or merge with existing mfOut.Meta so that mfOut.Meta.Applied/"filter"
reflects "bot_strip_p2p"; reference resolveTypes, effective, runtime.IsBot(),
MaybeApplyMuteFilter, mfOut.Meta.Applied and outData["filter"] when making this
change.

---

Nitpick comments:
In `@shortcuts/im/im_chat_list_test.go`:
- Around line 26-57: The helper newChatListTestRuntimeContextWithIdentity
currently builds a cobra.Command and sets flags manually; replace that with the
repo standard test factory pattern: call t.Setenv("LARKSUITE_CLI_CONFIG_DIR",
t.TempDir()) to isolate config, create a factory via cmdutil.TestFactory(t,
config) (or cmdutil.TestFactory(t, nil) if no extra config), and pass that
factory into common.TestNewRuntimeContextWithIdentity instead of constructing
cmd directly; ensure you still set the same flags on the returned
command/context so existing tests keep the same behavior.
🪄 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: b992e0c3-12c0-45c4-8df8-184707262b10

📥 Commits

Reviewing files that changed from the base of the PR and between 4a6369a and c3db76e.

📒 Files selected for processing (4)
  • shortcuts/im/im_chat_list.go
  • shortcuts/im/im_chat_list_test.go
  • skills/lark-im/SKILL.md
  • skills/lark-im/references/lark-im-chat-list.md
✅ Files skipped from review due to trivial changes (1)
  • skills/lark-im/SKILL.md

Comment thread skills/lark-im/references/lark-im-chat-list.md Outdated
@shifengjuan-dev shifengjuan-dev force-pushed the feat/chat-list-types-p2p branch from c3db76e to 657b56c Compare May 25, 2026 13:17
@shifengjuan-dev
Copy link
Copy Markdown
Collaborator Author

Pushed force update addressing review feedback (commit 657b56c):

  • CodeRabbit Major Can I join the meeting via CLI? #1+readme 优化建议 #2 (bot_strip_p2p contract): not a code defect — see thread. The PR description was the source of the contradiction; updated the PR body to match the implementation/doc/tests (silent strip, no filter.applied notice on bot type-downgrade).
  • CodeRabbit Nitpick (test helper isolation): added t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) in newChatListTestRuntimeContextWithIdentity (covers both helper entry points). Did not swap to cmdutil.TestFactory(t, config) because common.TestNewRuntimeContextWithIdentity(cmd, cfg, as) has no *Factory parameter — the helper's purpose is to drive pure-logic tests (Validate, buildChatListParams, resolveTypes, DryRun) that don't need a wired HTTP factory. The HTTP integration helpers newBotShortcutRuntime / newUserShortcutRuntime in helpers_network_test.go also hand-roll *cmdutil.Factory rather than route through cmdutil.TestFactory, so this matches the package's existing convention.

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.

Caution

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

⚠️ Outside diff range comments (1)
shortcuts/im/im_chat_list_test.go (1)

26-57: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Use the standard unit-test factory helper in this runtime constructor.

This helper is a unit-test factory path but it builds runtime context via common.TestNewRuntimeContextWithIdentity instead of cmdutil.TestFactory(t, config).

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/im/im_chat_list_test.go` around lines 26 - 57, The helper
newChatListTestRuntimeContextWithIdentity builds a runtime context using
common.TestNewRuntimeContextWithIdentity(cmd, nil, as) but per test guidelines
you should create a test factory with cmdutil.TestFactory(t, config) and pass
that factory into the runtime constructor instead of nil; update the function to
build a cfg (or reuse defaults), call factory := cmdutil.TestFactory(t, cfg) and
then return common.TestNewRuntimeContextWithIdentity(cmd, factory, as) (keeping
the existing cmd setup and flags), so the test uses the standard
cmdutil.TestFactory(t, ...) path.
🤖 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.

Outside diff comments:
In `@shortcuts/im/im_chat_list_test.go`:
- Around line 26-57: The helper newChatListTestRuntimeContextWithIdentity builds
a runtime context using common.TestNewRuntimeContextWithIdentity(cmd, nil, as)
but per test guidelines you should create a test factory with
cmdutil.TestFactory(t, config) and pass that factory into the runtime
constructor instead of nil; update the function to build a cfg (or reuse
defaults), call factory := cmdutil.TestFactory(t, cfg) and then return
common.TestNewRuntimeContextWithIdentity(cmd, factory, as) (keeping the existing
cmd setup and flags), so the test uses the standard cmdutil.TestFactory(t, ...)
path.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f62c55c5-99b5-4349-b007-eaa8c6aa94c6

📥 Commits

Reviewing files that changed from the base of the PR and between c3db76e and 657b56c.

📒 Files selected for processing (4)
  • shortcuts/im/im_chat_list.go
  • shortcuts/im/im_chat_list_test.go
  • skills/lark-im/SKILL.md
  • skills/lark-im/references/lark-im-chat-list.md
✅ Files skipped from review due to trivial changes (2)
  • skills/lark-im/references/lark-im-chat-list.md
  • skills/lark-im/SKILL.md

@shifengjuan-dev shifengjuan-dev force-pushed the feat/chat-list-types-p2p branch from 657b56c to c7ae9ba Compare May 26, 2026 02:40
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.

Caution

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

⚠️ Outside diff range comments (1)
shortcuts/im/im_chat_list_test.go (1)

26-57: 🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift

Use cmdutil.TestFactory(t, config) in this unit-test runtime helper.

This helper currently constructs runtime context via common.TestNewRuntimeContextWithIdentity; please switch the unit-test factory path to cmdutil.TestFactory(t, config) to align with repo test-factory requirements.

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/im/im_chat_list_test.go` around lines 26 - 57, The helper
newChatListTestRuntimeContextWithIdentity currently returns
common.TestNewRuntimeContextWithIdentity(cmd, nil, as); replace that with the
repo-standard cmdutil.TestFactory(t, config) call: build a Factory config object
containing the prepared *cobra.Command and the Identity (e.g., a struct/value
holding cmd and as), then call cmdutil.TestFactory(t, config) and return its
runtime context instead of using common.TestNewRuntimeContextWithIdentity;
update any imports to include cmdutil and remove the old common call.
🤖 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.

Outside diff comments:
In `@shortcuts/im/im_chat_list_test.go`:
- Around line 26-57: The helper newChatListTestRuntimeContextWithIdentity
currently returns common.TestNewRuntimeContextWithIdentity(cmd, nil, as);
replace that with the repo-standard cmdutil.TestFactory(t, config) call: build a
Factory config object containing the prepared *cobra.Command and the Identity
(e.g., a struct/value holding cmd and as), then call cmdutil.TestFactory(t,
config) and return its runtime context instead of using
common.TestNewRuntimeContextWithIdentity; update any imports to include cmdutil
and remove the old common call.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 152ff382-3368-4042-92ea-e1e65a0b1bf0

📥 Commits

Reviewing files that changed from the base of the PR and between 657b56c and c7ae9ba.

📒 Files selected for processing (4)
  • shortcuts/im/im_chat_list.go
  • shortcuts/im/im_chat_list_test.go
  • skills/lark-im/SKILL.md
  • skills/lark-im/references/lark-im-chat-list.md
✅ Files skipped from review due to trivial changes (2)
  • skills/lark-im/references/lark-im-chat-list.md
  • skills/lark-im/SKILL.md

@shifengjuan-dev
Copy link
Copy Markdown
Collaborator Author

Holding the original judgment — the cmdutil.TestFactory(t, config) swap is not applicable to this helper. (Reposting and expanding on the reasoning from #issuecomment-4534572804 since the re-review didn't carry that context forward.)

No matching signature to swap:

  • cmdutil.TestFactory(t, config) (internal/cmdutil/testing.go:32) returns (*Factory, stdout, stderr, *httpmock.Registry) — it wires an HTTP-mockable Factory for integration tests.
  • This helper builds a *RuntimeContext for pure-logic tests of buildChatListParams, normalizeTypes, resolveTypes, Validate, and DryRun. None of them touch the Factory; none make HTTP calls.
  • common.TestNewRuntimeContextWithIdentity(cmd, cfg, as) (shortcuts/common/testing.go:29) has no *Factory parameter — there is no straight signature swap. Your suggested "Factory config object containing the prepared *cobra.Command and the Identity" doesn't match core.CliConfig, which holds neither.

Same-package precedent for hand-rolling:
The HTTP integration helpers in this very package — newBotShortcutRuntime / newUserShortcutRuntime in shortcuts/im/helpers_network_test.go:75-117 — also do not route through cmdutil.TestFactory; they hand-roll &cmdutil.Factory{...}. So the cited guideline isn't uniformly applied even where a Factory is genuinely needed; applying it here, where no Factory is needed at all, would be unnecessary boilerplate.

What was applied:
The cheap, valid half of the suggestion is already in place — t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) was added to the helper in commit c7ae9ba for config-dir isolation, matching the markdown_diff_test.go / register_test.go pattern.

Per the AI-agent prompt accompanying this review ("Fix only still-valid issues, skip the rest with a brief reason"), recording this as skipped with the reasons above. Won't change.

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 26, 2026

@shifengjuan-dev: Your reasoning is technically sound on all three counts — signature mismatch, no Factory dependency in pure-logic tests, and same-package hand-rolling precedent in helpers_network_test.go. The config-dir isolation via t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) covers the only actionable part of the original suggestion. Acknowledged and recorded.

Kicking off the review now.


✏️ Learnings added
Learnt from: shifengjuan-dev
URL: https://github.com/larksuite/cli/pull/1077

Timestamp: 2026-05-26T03:27:12.349Z
Learning: In the `shortcuts/im` package (Go), the test helper `newChatListTestRuntimeContextWithIdentity` intentionally does NOT use `cmdutil.TestFactory(t, config)` because it builds a `*RuntimeContext` for pure-logic tests (`buildChatListParams`, `normalizeTypes`, `resolveTypes`, `Validate`, `DryRun`) that make no HTTP calls and need no wired Factory. `cmdutil.TestFactory` returns `(*Factory, stdout, stderr, *httpmock.Registry)` for HTTP-mockable integration tests — a completely different signature from `common.TestNewRuntimeContextWithIdentity(cmd, cfg, as)` in `shortcuts/common/testing.go:29` which has no `*Factory` parameter. The HTTP integration helpers `newBotShortcutRuntime`/`newUserShortcutRuntime` in `shortcuts/im/helpers_network_test.go:75-117` also hand-roll `&cmdutil.Factory{}` rather than routing through `cmdutil.TestFactory`. Config-dir isolation is handled via `t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Add a new --types flag (string_slice; values from {group, p2p}) to
+chat-list, backed by the new GET /open-apis/im/v1/chats `types` query
parameter. Accepts CSV (--types group,p2p) and repeated-flag forms
(--types group --types p2p).

Defaults to groups-only (backward compatible). Under user identity,
p2p single chats appear with chat_mode="p2p" plus p2p_target_type /
p2p_target_id fields. Under bot identity:

  - --types=p2p alone is rejected at validation
  - --types=p2p,group is silently downgraded to types=group (no runtime
    notice; skill docs document this contract)

Updates Shortcut.Description, lark-im SKILL.md (frontmatter trigger
+ shortcut table row), and the chat-list reference doc with command
examples, the new parameter, output field documentation, and a
dedicated "Bot identity and p2p" section.

Change-Id: I637ce23b3c6ce4ec350f0ac26dbac8120761bb71
@shifengjuan-dev shifengjuan-dev force-pushed the feat/chat-list-types-p2p branch from c7ae9ba to 7b2bf99 Compare May 26, 2026 06:51
@shifengjuan-dev
Copy link
Copy Markdown
Collaborator Author

Pushed force update 7b2bf99 switching the bot --types=p2p,group handling from silent strip → structured notice.

Why the change: A P2 review off-thread flagged that the silent-strip behavior — "success but quietly returning fewer kinds of data" — is misleading to both humans and agents. The same concern is what motivated the original PR-body contract; we walked it back earlier because no implementation existed. This commit restores it with a cleaner shape than the original draft (which had tried to overload outData["filter"]).

Design — chose B3 (separate notices slot):

  • outData["filter"] stays scoped to --exclude-muted (row-level filter). Unchanged shape, unchanged consumers.
  • outData["notices"] is a new top-level array carrying request-level adjustments. First entry: {"code": "bot_strip_p2p", "message": "..."}.
  • Stderr also gets warning: bot_strip_p2p: <message> (the warning: <code>: <message> convention from shortcuts/common/runner.go).
  • DryRun emits the same stderr warning so previewed requests truthfully reflect what Execute would send (parity with shortcuts/drive/drive_search.go).

Why not "priority resolution" on a single filter slot:
bot_strip_p2p is a request-level adjustment (we changed the outgoing query), not a row-level filter. Putting it in outData["filter"] would conflate two concepts; using separate keys eliminates the priority question entirely.

Pattern lineage in this repo:

  • shortcuts/drive/drive_search.go — request adjustments → stderr notices (same shape)
  • shortcuts/common/runner.go:649warning: <code>: <message> stderr format
  • shortcuts/mail/draft/model.gooutData["warnings"] as a structured array

Changes:

  • shortcuts/im/im_chat_list.go: resolveTypes signature gains stripped bool; DryRun + Execute emit the warning; Execute writes outData["notices"].
  • shortcuts/im/im_chat_list_test.go: flipped TestImChatList_Execute_BotStripsP2p assertions (must contain notices in stdout + stderr warning; must not pollute filter.applied); added TestImChatList_DryRun_BotStripsP2pStderrNotice; TestResolveTypes gains wantStripped column.
  • skills/lark-im/references/lark-im-chat-list.md: "Bot identity and p2p" section now documents stderr + JSON behavior and the slot-separation rationale.
  • PR body bullet docs: clarify install methods and add source build steps #3 updated accordingly.

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

Labels

domain/im PR touches the im 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.

1 participant