Skip to content

feat(event): implement mail event domain package and mail +watch improvements#1134

Open
xukuncx wants to merge 3 commits into
larksuite:mainfrom
xukuncx:feat/5b0c64b
Open

feat(event): implement mail event domain package and mail +watch improvements#1134
xukuncx wants to merge 3 commits into
larksuite:mainfrom
xukuncx:feat/5b0c64b

Conversation

@xukuncx
Copy link
Copy Markdown
Collaborator

@xukuncx xukuncx commented May 27, 2026

Generated by the harness-coding skill.

  • Branch: feat/5b0c64b
  • Target: main

Sprints

ID Title Status Commit
S1 Synthesize transport contract for larksuite/cli passed
S2 Implement mail event registration and mail+watch improvements passed 4eaf133

This MR was created autonomously. Quality gates were enforced by the repo's own pre-commit hooks.

Summary by CodeRabbit

  • New Features

    • Added --as flag to specify identity type (user or bot)
    • Mail event consumption for mail.user_mailbox.event.message_received_v1 with comma-separated mailbox filtering (defaults to "me"), subscribing per-mailbox and auto-unsubscribing on exit
    • mail +watch gains --force to bypass app-level subscribe lock
  • Behavior

    • Message body excerpts truncated to 140 characters
  • Documentation

    • Updated mail consumption and concurrency guidance
  • Tests

    • Expanded mail and flag test coverage

Review Change Stack

…ovements

- Add events/mail/ domain package: register.go wires mail.user_mailbox.event.message_received_v1
  KeyDefinition (7 user scopes, AuthTypes: [user], PreConsume subscribe/rollback/cleanup,
  processMailMessageReceived flat output, parseMailboxes comma-split dedup default-me)
- Wire mail.Keys() into events/register.go init(); remove "intentionally omitted" placeholder
- Add --force flag and appID-level lockfile (shared with event +subscribe) to mail +watch
- Add migration hint in mail +watch Description and Execute stderr (prefer event consume path)
- Add test coverage: events/mail/ (20 tests), events/register_test.go (1 test),
  shortcuts/mail/mail_watch_event_consume_test.go (6 tests)
- Update skills/lark-event/SKILL.md: mail event example + Topic index Mail row
- Update skills/lark-mail/SKILL.md: +watch lockfile and migration tip

sprint: S2
…ept it

Verification report INT-CLI-EventListMailEvent-01 failed with 'unknown flag: --as'
because the root cobra command had no --as persistent flag. When --as appears before
the subcommand name, cobra parses flags at root level and returns an error.

Add IdentityType field to GlobalOptions and register --as in RegisterGlobalFlags
via the root command's PersistentFlags(). This allows 'lark-cli --as user event list'
to parse without error.

Subcommands with their own local --as (event consume, api/service shortcuts) are
unaffected: pflag.AddFlagSet skips flags already registered locally.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 27, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f6d976b7-c747-4330-b9c0-a1d5f58d4969

📥 Commits

Reviewing files that changed from the base of the PR and between ebc890e and d3cf75f.

📒 Files selected for processing (2)
  • events/mail/mail_message_received.go
  • events/mail/mail_message_received_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • events/mail/mail_message_received.go
  • events/mail/mail_message_received_test.go

📝 Walkthrough

Walkthrough

Adds mail event consumption: mail event key/handler, mailbox subscription pre-consume with rollback/cleanup, global --as identity flag, app-level subscribe lock for mail +watch with --force, tests for all flows, and documentation updates.

Changes

Mail Event Consumption with Identity Flag and Subscribe Lock

Layer / File(s) Summary
Global --as identity flag
cmd/global_flags.go, cmd/global_flags_test.go
GlobalOptions gains IdentityType; RegisterGlobalFlags registers root --as flag bound to it and tests parse/assignment.
Mail event definition and registry wiring
events/mail/register.go, events/register.go, events/register_test.go
Adds mail domain Keys() with parameter metadata, output schema binding, handler/pre-consume hooks, fixed scopes/auth metadata; wires mail.Keys() into global event init and adds regression test.
Mail handler, mailbox parsing, and pre-consume lifecycle
events/mail/mail_message_received.go, events/mail/mail_message_received_test.go
Adds MailMessageReceivedOutput, processMailMessageReceived (140-rune BodyExcerpt, UTF-8-safe), parseMailboxes (comma-split/trim/dedupe/default me), mailMessageReceivedPreConsume (sequential subscribe, reverse rollback on failure, cleanup unsubs). Comprehensive tests cover parsing, subscribe/rollback/cleanup semantics, and payload mapping including malformed JSON passthrough.
Mail watch shortcut with app-level subscribe lock
shortcuts/mail/mail_watch.go, shortcuts/mail/mail_watch_event_consume_test.go
MailWatch description extended, --force flag added to bypass lockfile.ForSubscribe(appID) single-instance subscribe lock; Execute acquires lock unless forced; tests validate description, force flag, flag/help independence, and scope alignment.
Documentation
skills/lark-event/SKILL.md, skills/lark-mail/SKILL.md
Skill docs updated with event consume mail.user_mailbox.event.message_received_v1 example (comma-separated mailbox, --as user), PreConsume subscribe/unsubscribe notes, and subscribe-lock guidance.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • larksuite/cli#198: Also touches shortcuts/mail/mail_watch.go adding related mailbox/watch behavior and filters; closely related to subscribe/lock/watch changes.

Suggested labels

feature

Suggested reviewers

  • haidaodashushu
  • chanthuang
  • infeng

Poem

🐰 I nibble bytes and bind a flag,

I parse mailboxes, skip the gag,
Subscriptions hop in ordered queues,
Rollback sprints back, cleanup snoozes,
--as user leads the happy gaggle.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description lacks the required template structure with Summary, Changes, Test Plan, and Related Issues sections. It only contains metadata about sprint status and autonomous generation. Restructure the description to include all template sections: add a Summary explaining the mail event implementation, a Changes list, a Test Plan section documenting verification steps, and a Related Issues section.
Docstring Coverage ⚠️ Warning Docstring coverage is 36.59% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main changes: implementing a mail event domain package and improving mail +watch functionality.
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 unit tests (beta)
  • Create PR with unit tests
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch feat/5b0c64b

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/mail PR touches the mail domain size/L Large or sensitive change across domains or core paths labels May 27, 2026
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: 2

🧹 Nitpick comments (3)
shortcuts/mail/mail_watch.go (1)

193-208: ⚡ Quick win

Add focused tests for lock acquisition/bypass and migration-tip path.

The new concurrency gate and --force bypass are critical behavior changes, but these added branches are currently uncovered. Please add unit tests that exercise: lock-create failure, lock-held validation error, --force bypass, and migration-tip emission path.

Also applies to: 214-223

🤖 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/mail/mail_watch.go` around lines 193 - 208, Add unit tests around
the new concurrency gate in mail_watch: cover failure to create a lock by
mocking lockfile.ForSubscribe to return an error, cover the lock-held branch by
having ForSubscribe return a lock whose TryLock returns an error and assert
output.ErrValidation is returned and contains the runtime.Config.AppID message,
cover the --force bypass by setting runtime.Bool("force") to true and verifying
ForSubscribe/TryLock are not called (or not required), and cover the
migration-tip/emission path referenced in the same area; exercise functions
lockfile.ForSubscribe, lock.TryLock, output.ErrValidation, and
runtime.Bool/runtime.Config.AppID to simulate and assert each behavior.
events/mail/register.go (1)

14-15: ⚡ Quick win

Extract shared mail watch/consume scopes into one constant source.

The same 7-scope list is duplicated across layers with “MUST stay in sync” comments. Please centralize the scope slice (single exported/internal source) and reference it from both events/mail/register.go and shortcuts/mail/mail_watch.go to prevent silent drift.

Also applies to: 37-48

🤖 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 `@events/mail/register.go` around lines 14 - 15, Create a single shared slice
constant (e.g., MailWatchScopes []string) in a common package and replace the
duplicated 7-item scope literals in both the Scopes field usage in
events/mail/register.go and the scopes reference in shortcuts/mail/mail_watch.go
to reference that single symbol (export it if used across packages or make it
package-internal if both files share a package); ensure the new MailWatchScopes
preserves the exact order and values and update imports/usages to reference this
symbol so the two locations no longer duplicate the list.
shortcuts/mail/mail_watch_event_consume_test.go (1)

64-84: 🏗️ Heavy lift

Test name/intent says behavior, but assertions only check flag existence.

TestMailWatch_PrintSchemaDoesNotRequireForce currently cannot catch regressions in the real --print-output-schema early-return path (e.g., lockfile still being required), because it only verifies both flags are present. Please either (a) rename this test to reflect existence-only checks, or (b) execute the command path and assert it succeeds without --force.

🤖 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/mail/mail_watch_event_consume_test.go` around lines 64 - 84, The
test TestMailWatch_PrintSchemaDoesNotRequireForce only checks MailWatch.Flags
contains "print-output-schema" and "force" but doesn't verify the early-return
behavior; update the test to exercise the command path: simulate running
MailWatch without "--force" but with "--print-output-schema" (invoke the command
runner or the Run/Execute method used by MailWatch) and assert it returns
success/early-terminates without requiring the lockfile, or alternatively rename
the test to indicate it only verifies flag existence; reference MailWatch.Flags,
the "print-output-schema" and "force" flag names, and the MailWatch Run/Execute
entrypoint when making the change.
🤖 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 `@events/mail/mail_message_received.go`:
- Around line 49-50: The current truncation in
events/mail/mail_message_received.go uses byte slicing on body (body =
body[:140]) which can split multi-byte UTF-8 characters; change the logic that
sets body_excerpt (or variable body) to slice by runes instead: convert body to
[]rune, take up to 140 runes, and convert back to string so multi-byte
characters remain intact and no panic occurs when shorter. Locate the truncation
near the body variable assignment and replace the byte-based slice with
rune-based slicing (e.g., rune conversion, min check, and reassembly) in the
same function handling mail message receipt.
- Around line 113-118: The cleanup closure is reusing the outer ctx (from
mailMessageReceivedPreConsume) which may be canceled on shutdown; change cleanup
to create a fresh timeout context for the unsubscribe calls (e.g., for each
subscribed[i] or once for the loop) and use that new ctx with rt.CallAPI,
ensuring you call cancel() after the requests; update references to use the new
local ctx instead of the outer ctx and keep using rt.CallAPI, subscribed and the
unsubscribe path as-is.

---

Nitpick comments:
In `@events/mail/register.go`:
- Around line 14-15: Create a single shared slice constant (e.g.,
MailWatchScopes []string) in a common package and replace the duplicated 7-item
scope literals in both the Scopes field usage in events/mail/register.go and the
scopes reference in shortcuts/mail/mail_watch.go to reference that single symbol
(export it if used across packages or make it package-internal if both files
share a package); ensure the new MailWatchScopes preserves the exact order and
values and update imports/usages to reference this symbol so the two locations
no longer duplicate the list.

In `@shortcuts/mail/mail_watch_event_consume_test.go`:
- Around line 64-84: The test TestMailWatch_PrintSchemaDoesNotRequireForce only
checks MailWatch.Flags contains "print-output-schema" and "force" but doesn't
verify the early-return behavior; update the test to exercise the command path:
simulate running MailWatch without "--force" but with "--print-output-schema"
(invoke the command runner or the Run/Execute method used by MailWatch) and
assert it returns success/early-terminates without requiring the lockfile, or
alternatively rename the test to indicate it only verifies flag existence;
reference MailWatch.Flags, the "print-output-schema" and "force" flag names, and
the MailWatch Run/Execute entrypoint when making the change.

In `@shortcuts/mail/mail_watch.go`:
- Around line 193-208: Add unit tests around the new concurrency gate in
mail_watch: cover failure to create a lock by mocking lockfile.ForSubscribe to
return an error, cover the lock-held branch by having ForSubscribe return a lock
whose TryLock returns an error and assert output.ErrValidation is returned and
contains the runtime.Config.AppID message, cover the --force bypass by setting
runtime.Bool("force") to true and verifying ForSubscribe/TryLock are not called
(or not required), and cover the migration-tip/emission path referenced in the
same area; exercise functions lockfile.ForSubscribe, lock.TryLock,
output.ErrValidation, and runtime.Bool/runtime.Config.AppID to simulate and
assert each 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: b9e870ec-1d47-4ac6-942e-d77c07eacd64

📥 Commits

Reviewing files that changed from the base of the PR and between ab94ee9 and ebc890e.

📒 Files selected for processing (11)
  • cmd/global_flags.go
  • cmd/global_flags_test.go
  • events/mail/mail_message_received.go
  • events/mail/mail_message_received_test.go
  • events/mail/register.go
  • events/register.go
  • events/register_test.go
  • shortcuts/mail/mail_watch.go
  • shortcuts/mail/mail_watch_event_consume_test.go
  • skills/lark-event/SKILL.md
  • skills/lark-mail/SKILL.md

Comment thread events/mail/mail_message_received.go Outdated
Comment thread events/mail/mail_message_received.go
@CLAassistant
Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ bubbmon233
❌ yangbin.1005


yangbin.1005 seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

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

Labels

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

3 participants