Skip to content

fix: improve error message when auto-detected identity is unsupported#439

Open
chanthuang wants to merge 1 commit intomainfrom
fix/shortcut-identity-auto-detect
Open

fix: improve error message when auto-detected identity is unsupported#439
chanthuang wants to merge 1 commit intomainfrom
fix/shortcut-identity-auto-detect

Conversation

@chanthuang
Copy link
Copy Markdown
Collaborator

@chanthuang chanthuang commented Apr 13, 2026

Summary

  • When a user-only shortcut (e.g. mail +draft-edit) is invoked without --as and the user has no active login (or token expired), auto-detect resolves to bot, causing a misleading error: "--as bot is not supported". The user never passed --as bot — they just need to login.
  • This fix improves the error message to distinguish auto-detected vs explicit --as mismatches:
    • Auto-detected: "this command requires user identity, but no user login was found (auto-detected as bot)\nhint: run lark-cli auth login first, then retry"
    • Explicit --as bot: "--as bot is not supported, this command only supports: user" (unchanged)

Test plan

  • go test ./internal/cmdutil/ -run TestCheckIdentity — updated test passes
  • Manual (no login): lark-cli mail +draft-edit --draft-id <id> --inspect → shows "requires user identity ... hint: run lark-cli auth login"
  • Manual (no login, explicit): lark-cli mail +draft-edit --draft-id <id> --inspect --as bot → shows "--as bot is not supported"
  • Manual (logged in): lark-cli mail +draft-edit --draft-id <id> --inspect → normal API call with identity=user

🤖 Generated with Claude Code

@github-actions github-actions bot added the size/M Single-domain feat or fix with limited business impact label Apr 13, 2026
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 13, 2026

📝 Walkthrough

Walkthrough

Updated error handling in the identity checking mechanism to provide clearer guidance when auto-detected identity fails validation. Changed error message from reporting unsupported identity with a hint to instructing users to perform login authentication, with corresponding test adjustments.

Changes

Cohort / File(s) Summary
Error Message Update
internal/cmdutil/factory.go
Modified CheckIdentity failure path for auto-detected identities to return validation error directing user to run lark-cli auth login instead of reporting unsupported identity with --as hint.
Test Adjustment
internal/cmdutil/factory_test.go
Updated TestCheckIdentity_Unsupported_AutoDetected test case: changed invocation parameters from (core.AsUser, []string{"bot"}) to (core.AsBot, []string{"user"}) and updated expected error message assertions to match new guidance.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Suggested labels

domain/mail, domain/im

Suggested reviewers

  • infeng
  • YangJunzhou-01
  • hugang-lark

Poem

🐰 A message refined, now clear and bright,
When identities clash, we guide them right,
No cryptic hints, just "login, please!"
The path to access flows with ease,
Tests aligned, all cozy and tight! 🔐

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: improving the error message when an auto-detected identity is unsupported, which is the primary focus of this PR.
Description check ✅ Passed The PR description covers all required template sections: Summary explains the problem and solution clearly, Changes are demonstrated through the error message examples, Test Plan documents verification steps with checkmarks, and Related Issues is acknowledged.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/shortcut-identity-auto-detect

Comment @coderabbitai help to get the list of available commands and usage tips.

@CLAassistant
Copy link
Copy Markdown

CLAassistant commented Apr 13, 2026

CLA assistant check
All committers have signed the CLA.

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.

🧹 Nitpick comments (1)
shortcuts/common/runner_identity_test.go (1)

90-106: Rename test to match asserted behavior.

The test name says CoercesToUser, but the assertion expects an error (i.e., no coercion for DefaultAs).

Suggested rename
-func TestResolveShortcutIdentity_UserOnly_DefaultAsBot_CoercesToUser(t *testing.T) {
+func TestResolveShortcutIdentity_UserOnly_DefaultAsBot_ReturnsError(t *testing.T) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/common/runner_identity_test.go` around lines 90 - 106, Rename the
test function TestResolveShortcutIdentity_UserOnly_DefaultAsBot_CoercesToUser to
reflect that it expects an error (e.g.,
TestResolveShortcutIdentity_UserOnly_DefaultAsBot_ErrorsOr_DoesNotCoerce) and
update the function declaration and any references; the test body (creating
Shortcut with AuthTypes []string{"user"}, config DefaultAs:"bot", calling
resolveShortcutIdentity and asserting err != nil) is correct, only the test name
should be changed to match the asserted behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@shortcuts/common/runner_identity_test.go`:
- Around line 90-106: Rename the test function
TestResolveShortcutIdentity_UserOnly_DefaultAsBot_CoercesToUser to reflect that
it expects an error (e.g.,
TestResolveShortcutIdentity_UserOnly_DefaultAsBot_ErrorsOr_DoesNotCoerce) and
update the function declaration and any references; the test body (creating
Shortcut with AuthTypes []string{"user"}, config DefaultAs:"bot", calling
resolveShortcutIdentity and asserting err != nil) is correct, only the test name
should be changed to match the asserted behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 27519b28-8fdc-4168-96f0-e8b6e44750d0

📥 Commits

Reviewing files that changed from the base of the PR and between 3917b77 and cafa56e.

📒 Files selected for processing (2)
  • shortcuts/common/runner.go
  • shortcuts/common/runner_identity_test.go

@greptile-apps
Copy link
Copy Markdown

greptile-apps bot commented Apr 13, 2026

Greptile Summary

This PR improves the error message in CheckIdentity for auto-detected identity mismatches, giving user-only shortcut callers a clear hint to run auth login when no user login exists. The test is correctly updated to exercise the primary use case (AsBot auto-detected against [\"user\"]).

  • P1 – wrong message for bot-only shortcuts: The hardcoded \"but no user login was found\" and auth login hint in the IdentityAutoDetected branch are only correct when as == AsBot. For bot-only shortcuts (e.g. event/subscribe) where a logged-in user is auto-detected as \"user\", the message incorrectly says "no user login was found (auto-detected as user)" and tells them to run auth login when the real action is to configure bot credentials or pass --as bot.

Confidence Score: 4/5

Safe to merge after fixing the hardcoded "no user login was found" message, which is wrong for bot-only shortcuts when a user is auto-detected.

One P1 finding: the new error message hardcodes "no user login was found" in the IdentityAutoDetected branch regardless of which identity was detected, producing an incorrect and misleading message for bot-only shortcuts (e.g. event/subscribe) when the user is logged in and auto-detected as "user". The change is otherwise well-scoped and the test update is correct for the primary use case.

internal/cmdutil/factory.go — the IdentityAutoDetected error branch needs an as.IsBot() guard before emitting the user-specific login hint.

Important Files Changed

Filename Overview
internal/cmdutil/factory.go Improves auto-detect error message for user-only shortcuts, but hardcodes "no user login was found" which produces an incorrect message for bot-only shortcuts (e.g. event/subscribe) when a user is logged in and auto-detected as "user".
internal/cmdutil/factory_test.go Test updated to match the primary use case (AsBot auto-detected, user-only supported); missing coverage for the reverse scenario (user auto-detected, bot-only supported).

Reviews (3): Last reviewed commit: "fix: improve error message when auto-det..." | Re-trigger Greptile

@github-actions
Copy link
Copy Markdown

github-actions bot commented Apr 13, 2026

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add larksuite/cli#fix/shortcut-identity-auto-detect -y -g

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@internal/cmdutil/factory.go`:
- Around line 130-131: The error message that constructs the mismatch string in
factory.go hardcodes "user login" which is incorrect for non-user identities;
update the formatted string used where the code currently builds: "this command
requires %s identity, but no user login was found (auto-detected as %s)\nhint:
run `lark-cli auth login` first, then retry" to a neutral form like "this
command requires %s identity, but no login was found (auto-detected as
%s)\nhint: run `lark-cli auth login` first, then retry" (or conditionally vary
the phrase only when list indicates a user identity); change the message
construction at that location to use the variable names already present (list
and as) and avoid hardcoding "user".

In `@shortcuts/common/runner_identity_test.go`:
- Around line 25-43: The test
TestResolveShortcutIdentity_UserOnly_AutoDetectBot_SuggestsLogin is asserting an
error even though resolveShortcutIdentity should coerce a missing --as to "user"
for a shortcut with Shortcut.AuthTypes == []string{"user"}; update the test to
expect no error from resolveShortcutIdentity (call using cmd from newTestCmd and
factory from cmdutil.TestFactory), assert the returned identity indicates "user"
(or the equivalent success result returned by resolveShortcutIdentity), and
remove the assertions that check for an "auth login" error and "requires user
identity" in err.Error().
🪄 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: 776615bd-e945-4ae3-be1f-aa9fc4f8ab8a

📥 Commits

Reviewing files that changed from the base of the PR and between cafa56e and 175c0f9.

📒 Files selected for processing (3)
  • internal/cmdutil/factory.go
  • internal/cmdutil/factory_test.go
  • shortcuts/common/runner_identity_test.go

Comment on lines +130 to +131
"this command requires %s identity, but no user login was found (auto-detected as %s)\nhint: run `lark-cli auth login` first, then retry",
list, as)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Auto-detected mismatch message is overly specific and can be wrong

Line 130 hardcodes a user-login diagnosis for every auto-detected mismatch. For bot-only (or other non-user) supported identities, this is misleading.

Proposed fix
 	list := strings.Join(supported, ", ")
 	if f.IdentityAutoDetected {
-		return output.ErrValidation(
-			"this command requires %s identity, but no user login was found (auto-detected as %s)\nhint: run `lark-cli auth login` first, then retry",
-			list, as)
+		if len(supported) == 1 && supported[0] == string(core.AsUser) {
+			return output.ErrValidation(
+				"this command requires user identity, but no user login was found (auto-detected as %s)\nhint: run `lark-cli auth login` first, then retry",
+				as,
+			)
+		}
+		return output.ErrValidation(
+			"auto-detected identity %s is not supported, this command only supports: %s",
+			as, list,
+		)
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@internal/cmdutil/factory.go` around lines 130 - 131, The error message that
constructs the mismatch string in factory.go hardcodes "user login" which is
incorrect for non-user identities; update the formatted string used where the
code currently builds: "this command requires %s identity, but no user login was
found (auto-detected as %s)\nhint: run `lark-cli auth login` first, then retry"
to a neutral form like "this command requires %s identity, but no login was
found (auto-detected as %s)\nhint: run `lark-cli auth login` first, then retry"
(or conditionally vary the phrase only when list indicates a user identity);
change the message construction at that location to use the variable names
already present (list and as) and avoid hardcoding "user".

Comment on lines +25 to +43
func TestResolveShortcutIdentity_UserOnly_AutoDetectBot_SuggestsLogin(t *testing.T) {
// No UserOpenId → auto-detect returns bot.
// Shortcut only supports user → should error with auth login hint.
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{AppID: "a", AppSecret: "s"})
cmd := newTestCmd("user", false) // --as not explicitly changed

s := &Shortcut{AuthTypes: []string{"user"}}

_, err := resolveShortcutIdentity(cmd, f, s)
if err == nil {
t.Fatal("resolveShortcutIdentity() expected error for auto-detected bot on user-only shortcut")
}
if !strings.Contains(err.Error(), "auth login") {
t.Errorf("error should suggest auth login, got: %v", err)
}
if !strings.Contains(err.Error(), "requires user identity") {
t.Errorf("error should mention required identity, got: %v", err)
}
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Test expectation conflicts with single-auth coercion behavior

Line 33-Line 42 asserts an error for omitted --as on a user-only shortcut. Per this PR’s objective, that path should coerce to user and proceed (not fail in resolveShortcutIdentity).

Proposed test adjustment
-func TestResolveShortcutIdentity_UserOnly_AutoDetectBot_SuggestsLogin(t *testing.T) {
+func TestResolveShortcutIdentity_UserOnly_AutoDetectBot_CoercesToUser(t *testing.T) {
 	// No UserOpenId → auto-detect returns bot.
-	// Shortcut only supports user → should error with auth login hint.
+	// Shortcut only supports user → should coerce to user when --as is omitted.
 	f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{AppID: "a", AppSecret: "s"})
 	cmd := newTestCmd("user", false) // --as not explicitly changed

 	s := &Shortcut{AuthTypes: []string{"user"}}

-	_, err := resolveShortcutIdentity(cmd, f, s)
-	if err == nil {
-		t.Fatal("resolveShortcutIdentity() expected error for auto-detected bot on user-only shortcut")
-	}
-	if !strings.Contains(err.Error(), "auth login") {
-		t.Errorf("error should suggest auth login, got: %v", err)
-	}
-	if !strings.Contains(err.Error(), "requires user identity") {
-		t.Errorf("error should mention required identity, got: %v", err)
+	as, err := resolveShortcutIdentity(cmd, f, s)
+	if err != nil {
+		t.Fatalf("resolveShortcutIdentity() unexpected error: %v", err)
+	}
+	if as != core.AsUser {
+		t.Errorf("resolveShortcutIdentity() = %q, want %q", as, core.AsUser)
 	}
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func TestResolveShortcutIdentity_UserOnly_AutoDetectBot_SuggestsLogin(t *testing.T) {
// No UserOpenId → auto-detect returns bot.
// Shortcut only supports user → should error with auth login hint.
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{AppID: "a", AppSecret: "s"})
cmd := newTestCmd("user", false) // --as not explicitly changed
s := &Shortcut{AuthTypes: []string{"user"}}
_, err := resolveShortcutIdentity(cmd, f, s)
if err == nil {
t.Fatal("resolveShortcutIdentity() expected error for auto-detected bot on user-only shortcut")
}
if !strings.Contains(err.Error(), "auth login") {
t.Errorf("error should suggest auth login, got: %v", err)
}
if !strings.Contains(err.Error(), "requires user identity") {
t.Errorf("error should mention required identity, got: %v", err)
}
}
func TestResolveShortcutIdentity_UserOnly_AutoDetectBot_CoercesToUser(t *testing.T) {
// No UserOpenId → auto-detect returns bot.
// Shortcut only supports user → should coerce to user when --as is omitted.
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{AppID: "a", AppSecret: "s"})
cmd := newTestCmd("user", false) // --as not explicitly changed
s := &Shortcut{AuthTypes: []string{"user"}}
as, err := resolveShortcutIdentity(cmd, f, s)
if err != nil {
t.Fatalf("resolveShortcutIdentity() unexpected error: %v", err)
}
if as != core.AsUser {
t.Errorf("resolveShortcutIdentity() = %q, want %q", as, core.AsUser)
}
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@shortcuts/common/runner_identity_test.go` around lines 25 - 43, The test
TestResolveShortcutIdentity_UserOnly_AutoDetectBot_SuggestsLogin is asserting an
error even though resolveShortcutIdentity should coerce a missing --as to "user"
for a shortcut with Shortcut.AuthTypes == []string{"user"}; update the test to
expect no error from resolveShortcutIdentity (call using cmd from newTestCmd and
factory from cmdutil.TestFactory), assert the returned identity indicates "user"
(or the equivalent success result returned by resolveShortcutIdentity), and
remove the assertions that check for an "auth login" error and "requires user
identity" in err.Error().

When a user-only shortcut is invoked without --as and auto-detect
resolves to bot (no login / expired token), show a clear message
suggesting `lark-cli auth login` instead of the misleading
"--as bot is not supported".

Change-Id: I684e6a422a907f428a68e8e4724fa8c50b13045d
Co-Authored-By: AI
@chanthuang chanthuang force-pushed the fix/shortcut-identity-auto-detect branch from 175c0f9 to b88039e Compare April 13, 2026 07:56
@chanthuang chanthuang changed the title fix: coerce auto-detected identity for single-auth shortcuts fix: improve error message when auto-detected identity is unsupported Apr 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/M Single-domain feat or fix with limited business impact

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants