Skip to content

Add activities for user actions on labels#44522

Merged
lucasmrod merged 4 commits into
mainfrom
36976-activities-for-labels
May 1, 2026
Merged

Add activities for user actions on labels#44522
lucasmrod merged 4 commits into
mainfrom
36976-activities-for-labels

Conversation

@lucasmrod
Copy link
Copy Markdown
Member

@lucasmrod lucasmrod commented Apr 30, 2026

Resolves #36976

  • Changes file added for user-visible changes in changes/, orbit/changes/ or ee/fleetd-chrome/changes.
    See Changes files for more information.

Testing

  • Added/updated automated tests
  • QA'd all new/changed functionality manually

Summary by CodeRabbit

  • New Features

    • Label operations (create, edit, delete) now generate activities shown in the activity feed with label and optional fleet context.
    • Host label add/remove operations emit corresponding label edited activities; duplicate label names are deduplicated.
    • Label activity types are selectable/filterable in the activity dashboard.
  • Tests

    • Added unit, integration, and UI tests covering label activity emission, rendering, filtering, and GitOps label lifecycle scenarios.

@lucasmrod lucasmrod requested a review from a team as a code owner April 30, 2026 18:21
Copilot AI review requested due to automatic review settings April 30, 2026 18:21
@lucasmrod lucasmrod requested a review from a team as a code owner April 30, 2026 18:21
Copy link
Copy Markdown

@claude claude Bot left a comment

Choose a reason for hiding this comment

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

Claude Code Review

This repository is configured for manual code reviews. Comment @claude review to trigger a review and subscribe this PR to future pushes, or @claude review once for a one-time review.

Tip: disable this comment in your organization's Code Review settings.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 30, 2026

Codecov Report

❌ Patch coverage is 71.62162% with 63 lines in your changes missing coverage. Please review.
✅ Project coverage is 66.80%. Comparing base (a52e4ff) to head (5a10f4f).
⚠️ Report is 31 commits behind head on main.

Files with missing lines Patch % Lines
server/service/labels.go 73.33% 22 Missing and 18 partials ⚠️
server/service/hosts.go 67.56% 6 Missing and 6 partials ⚠️
...d/fleetctl/fleetctl/testing_utils/testing_utils.go 25.00% 3 Missing and 3 partials ⚠️
...vityFeed/GlobalActivityItem/GlobalActivityItem.tsx 85.71% 3 Missing ⚠️
server/datastore/mysql/labels.go 66.66% 1 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #44522      +/-   ##
==========================================
+ Coverage   66.76%   66.80%   +0.04%     
==========================================
  Files        2636     2637       +1     
  Lines      211834   212402     +568     
  Branches     9425     9568     +143     
==========================================
+ Hits       141437   141902     +465     
- Misses      57551    57604      +53     
- Partials    12846    12896      +50     
Flag Coverage Δ
backend 68.58% <70.14%> (+0.03%) ⬆️
frontend 54.80% <85.71%> (+0.05%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 30, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1dedeaf5-92ee-419f-87a8-be343ee6fe32

📥 Commits

Reviewing files that changed from the base of the PR and between b4decac and 5a10f4f.

📒 Files selected for processing (2)
  • server/service/hosts.go
  • server/service/labels.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • server/service/labels.go

Walkthrough

Adds activity generation for label lifecycle events by introducing three new activity detail types (created_label, edited_label, deleted_label). Backend: new datastore method to fetch label membership host IDs, datastore interface and mock extensions, service logic to emit activities on label create/modify/delete, host label add/remove, and ApplyLabelSpecs comparisons to detect semantic changes before emitting activities. Frontend: new activity types, extended activity detail fields, filter mappings, UI templates, and tests to render label activities. Tests and GitOps integration updated to capture and validate emitted label activities.

Possibly related PRs

  • fleetdm/fleet PR 43795: Adds new activity-detail types and updates the activity registry/ActivityDetailsList in the same activity subsystem files.
  • fleetdm/fleet PR 44094: Extends the activity/audit system with new activity types and corresponding frontend templates and server activity structs touching the same enums and activity handling.
  • fleetdm/fleet PR 37116: Changes label membership and datastore label logic overlapping with the new LabelMembershipHostIDs method and related datastore/mocking tests.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.75% 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 'Add activities for user actions on labels' clearly and concisely describes the main objective of the changeset: introducing activity logging for label operations (create, edit, delete).
Description check ✅ Passed The PR description includes the issue reference (#36976), confirms checklist items for changes file and testing, but omits many other template sections and provides minimal implementation details.
Linked Issues check ✅ Passed The code changes comprehensively implement the core requirements from #36976: activities are generated for label create/edit/delete across UI and GitOps flows for both global and team labels, frontend displays new activity types, and extensive test coverage validates the implementation.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing label activity logging as specified in #36976. No unrelated functionality, dependencies, or scope creep detected across backend services, datastore, frontend, and tests.

✏️ 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 36976-activities-for-labels

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
Review rate limit: 7/8 reviews remaining, refill in 7 minutes and 30 seconds.

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

Copy link
Copy Markdown
Contributor

@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 `@server/service/hosts.go`:
- Around line 3629-3673: emitEditedLabelActivities can emit duplicate activities
when labelNames contains duplicates; before the final loop over labelNames
deduplicate them (e.g., build a seen map[string]bool and either produce an
ordered slice of unique names or skip repeats during iteration) so you only call
svc.NewActivity once per distinct label name; use the existing labels map lookup
(labels[name]) and keep the rest of the logic (fleetName resolution,
svc.NewActivity) unchanged.

In `@server/service/labels.go`:
- Around line 816-827: The function labelSpecMatchesLabel currently ignores
platform-only changes so add a platform comparison to detect those edits: in
labelSpecMatchesLabel (params *fleet.LabelSpec, *fleet.Label) compare
spec.Platforms (or spec.Platform) with label.Platforms (or label.Platform) and
return false when they differ; for slice fields use a slice-equality check
(e.g., reflect.DeepEqual) and place this check before the HostVitalsCriteria
comparison so platform-only changes cause the function to return false and
trigger edited_label activity.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9532040c-16de-4191-9777-6514d20c3a30

📥 Commits

Reviewing files that changed from the base of the PR and between f94b66f and 287b4d9.

📒 Files selected for processing (15)
  • changes/36976-activities-for-labels
  • cmd/fleetctl/fleetctl/apply_test.go
  • cmd/fleetctl/fleetctl/testing_utils/testing_utils.go
  • cmd/fleetctl/integrationtest/gitops/gitops_enterprise_integration_test.go
  • frontend/interfaces/activity.ts
  • frontend/pages/DashboardPage/cards/ActivityFeed/GlobalActivityItem/GlobalActivityItem.tests.tsx
  • frontend/pages/DashboardPage/cards/ActivityFeed/GlobalActivityItem/GlobalActivityItem.tsx
  • server/datastore/mysql/labels.go
  • server/datastore/mysql/labels_test.go
  • server/fleet/activities.go
  • server/fleet/datastore.go
  • server/mock/datastore_mock.go
  • server/service/hosts.go
  • server/service/labels.go
  • server/service/labels_test.go

Comment thread server/service/hosts.go
Comment thread server/service/labels.go
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR adds first-class activity feed events for label lifecycle changes (create/edit/delete) across UI actions, GitOps spec apply, and host manual-label membership changes, and renders those new activities in the Dashboard Activity Feed.

Changes:

  • Add new activity types: created_label, edited_label, deleted_label, and emit them from relevant service paths (label CRUD, ApplyLabelSpecs, add/remove labels on host).
  • Add unfiltered label membership host-ID lookup to support “manual label hosts changed” detection during GitOps apply.
  • Update frontend activity feed templates/types/tests to display and filter the new label activities.

Reviewed changes

Copilot reviewed 14 out of 15 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
server/service/labels.go Emits label activities on create/edit/delete and GitOps spec apply, including change detection helpers.
server/service/hosts.go Emits edited_label activities when manual labels are added/removed from a host.
server/fleet/activities.go Registers new activity detail types for label actions.
server/fleet/datastore.go Extends datastore interface with LabelMembershipHostIDs.
server/mock/datastore_mock.go Adds mock support for LabelMembershipHostIDs.
server/datastore/mysql/labels.go Implements LabelMembershipHostIDs in MySQL datastore.
server/datastore/mysql/labels_test.go Adds datastore test coverage for unfiltered membership lookup.
server/service/labels_test.go Adds/updates unit tests verifying label activity emission paths.
frontend/pages/DashboardPage/cards/ActivityFeed/GlobalActivityItem/GlobalActivityItem.tsx Renders new label activities in the global activity feed.
frontend/pages/DashboardPage/cards/ActivityFeed/GlobalActivityItem/GlobalActivityItem.tests.tsx Adds frontend test coverage for new activity renderings.
frontend/interfaces/activity.ts Adds new activity enum values, details fields, and filter-label mappings.
cmd/fleetctl/integrationtest/gitops/gitops_enterprise_integration_test.go Adds GitOps integration test that validates per-label activities across create/edit/no-op/delete scenarios.
cmd/fleetctl/fleetctl/testing_utils/testing_utils.go Extends default mocked DS behavior to support new ApplyLabelSpecs activity detection paths.
cmd/fleetctl/fleetctl/apply_test.go Adjusts invocation tracking for LabelsByName to account for new calls.
changes/36976-activities-for-labels Adds user-visible change entry for the new label activities.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread server/service/labels.go
Comment thread server/fleet/activities.go
Comment thread server/service/labels.go Outdated
Comment thread server/service/labels.go Outdated
Copy link
Copy Markdown
Contributor

@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.

♻️ Duplicate comments (1)
server/service/labels.go (1)

816-827: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Compare platform in spec-vs-label matching to avoid missing real edit activities.

Platform-only GitOps updates currently evaluate as unchanged, so edited_label is not emitted for a real label edit.

Suggested fix
 func labelSpecMatchesLabel(spec *fleet.LabelSpec, label *fleet.Label) bool {
 	if spec.Description != label.Description {
 		return false
 	}
+	if spec.Platform != label.Platform {
+		return false
+	}
 	if spec.Query != label.Query {
 		return false
 	}
 	if spec.LabelMembershipType != label.LabelMembershipType {
 		return false
 	}
 	return jsonRawMessageEqual(spec.HostVitalsCriteria, label.HostVitalsCriteria)
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/service/labels.go` around lines 816 - 827, The labelSpecMatchesLabel
function currently omits comparing the platform fields, causing platform-only
GitOps updates to be treated as unchanged; update labelSpecMatchesLabel (used to
detect edits) to also compare spec.Platform with label.Platform (e.g.,
spec.Platform != label.Platform) as part of the equality checks so that a
difference in platform triggers a non-match and allows edited_label to be
emitted.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@server/service/labels.go`:
- Around line 816-827: The labelSpecMatchesLabel function currently omits
comparing the platform fields, causing platform-only GitOps updates to be
treated as unchanged; update labelSpecMatchesLabel (used to detect edits) to
also compare spec.Platform with label.Platform (e.g., spec.Platform !=
label.Platform) as part of the equality checks so that a difference in platform
triggers a non-match and allows edited_label to be emitted.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 48c97a94-7090-47de-94d4-825eaff8a13f

📥 Commits

Reviewing files that changed from the base of the PR and between 287b4d9 and de8db29.

📒 Files selected for processing (2)
  • cmd/fleetctl/integrationtest/gitops/gitops_enterprise_integration_test.go
  • server/service/labels.go

Copy link
Copy Markdown
Contributor

@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 (2)
server/service/labels.go (1)

195-230: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Skip edited_label for no-op ModifyLabel requests.

This path now emits an edit activity even when the payload doesn't change the label at all (empty payload, same name/description, same manual host set). That will create false audit entries and is inconsistent with the semantic no-op check added in ApplyLabelSpecs. Compare against the pre-update state and return without SaveLabel/NewActivity when nothing changed.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/service/labels.go` around lines 195 - 230, The ModifyLabel flow
currently always calls SaveLabel and NewActivity even when the incoming payload
makes no changes; update the logic in the ModifyLabel handler to first compute
whether any actual changes would occur (compare the incoming payload fields —
name, description, label.LabelMembershipType, and the resolved hostIDs — against
the existing label state and its current membership set obtained from the DS),
and if nothing would change, return early without calling
svc.ds.UpdateLabelMembershipByHostIDs, svc.ds.SaveLabel, or svc.NewActivity;
reuse the existing variables (label, payload, hostIDs, savedHostIDs) and the
same filter/context so the check mirrors ApplyLabelSpecs behavior and only
proceeds to UpdateLabelMembershipByHostIDs/SaveLabel/NewActivity when a real
change is detected.
server/service/hosts.go (1)

3581-3585: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Only emit edited_label when the host's membership actually changed.

Both paths now log an edit for every requested label name, even when the datastore write is a no-op (for example, adding a label the host already has or removing one it never had). That makes the activity feed inaccurate and easy to spam. Capture the host's label set before the write and emit activities only for labels whose membership changed.

Also applies to: 3621-3625

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@server/service/hosts.go` around lines 3581 - 3585, Before calling
svc.ds.AddLabelsToHost, read the host's current label membership (e.g., via
host.LabelIDs or a datastore reader like svc.ds.GetLabelsForHost) and compute
which of the requested labelIDs/labelNames will actually change membership;
after the AddLabelsToHost call only invoke svc.emitEditedLabelActivities with
the subset of labelNames that were added or removed (i.e., whose membership
toggled). Apply the same change to the other occurrence around
svc.ds.RemoveLabelsFromHost / the block referenced at 3621-3625 so
emitEditedLabelActivities is only called for labels with actual membership
changes.
🧹 Nitpick comments (1)
cmd/fleetctl/integrationtest/gitops/gitops_enterprise_integration_test.go (1)

3382-3539: ⚡ Quick win

Cover the remaining team-scoped label types in this GitOps activity test.

This test only exercises team label activities with a dynamic label. The PR scope also includes team-scoped manual and host_vitals/IdP-created labels, so a regression in either path would still pass here.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@cmd/fleetctl/integrationtest/gitops/gitops_enterprise_integration_test.go`
around lines 3382 - 3539, The test currently only exercises team-scoped dynamic
labels; extend it to cover team-scoped manual and host_vitals/IdP-created label
flows by adding parallel phases that call writeTeam (in addition to writeGlobal)
to create a team manual label (with hosts list) and a team host_vitals label
(with criteria), then run apply() and flush() and assert the emitted activities
include ActivityTypeCreatedLabel, ActivityTypeEditedLabel and
ActivityTypeDeletedLabel for those team labels (verifying FleetID/FleetName
presence for team-scoped activities), and also include no-op re-apply checks and
edits (change query -> change hosts -> change criteria) using the same pattern
as existing global label phases; locate changes around the existing
writeTeam/writeGlobal/apply/flush sequences and reuse the same assertions that
check types (ActivityTypeCreatedLabel, ActivityTypeEditedLabel,
ActivityTypeDeletedLabel) and name membership to ensure team manual and
host_vitals paths are covered.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@server/service/hosts.go`:
- Around line 3581-3585: Before calling svc.ds.AddLabelsToHost, read the host's
current label membership (e.g., via host.LabelIDs or a datastore reader like
svc.ds.GetLabelsForHost) and compute which of the requested labelIDs/labelNames
will actually change membership; after the AddLabelsToHost call only invoke
svc.emitEditedLabelActivities with the subset of labelNames that were added or
removed (i.e., whose membership toggled). Apply the same change to the other
occurrence around svc.ds.RemoveLabelsFromHost / the block referenced at
3621-3625 so emitEditedLabelActivities is only called for labels with actual
membership changes.

In `@server/service/labels.go`:
- Around line 195-230: The ModifyLabel flow currently always calls SaveLabel and
NewActivity even when the incoming payload makes no changes; update the logic in
the ModifyLabel handler to first compute whether any actual changes would occur
(compare the incoming payload fields — name, description,
label.LabelMembershipType, and the resolved hostIDs — against the existing label
state and its current membership set obtained from the DS), and if nothing would
change, return early without calling svc.ds.UpdateLabelMembershipByHostIDs,
svc.ds.SaveLabel, or svc.NewActivity; reuse the existing variables (label,
payload, hostIDs, savedHostIDs) and the same filter/context so the check mirrors
ApplyLabelSpecs behavior and only proceeds to
UpdateLabelMembershipByHostIDs/SaveLabel/NewActivity when a real change is
detected.

---

Nitpick comments:
In `@cmd/fleetctl/integrationtest/gitops/gitops_enterprise_integration_test.go`:
- Around line 3382-3539: The test currently only exercises team-scoped dynamic
labels; extend it to cover team-scoped manual and host_vitals/IdP-created label
flows by adding parallel phases that call writeTeam (in addition to writeGlobal)
to create a team manual label (with hosts list) and a team host_vitals label
(with criteria), then run apply() and flush() and assert the emitted activities
include ActivityTypeCreatedLabel, ActivityTypeEditedLabel and
ActivityTypeDeletedLabel for those team labels (verifying FleetID/FleetName
presence for team-scoped activities), and also include no-op re-apply checks and
edits (change query -> change hosts -> change criteria) using the same pattern
as existing global label phases; locate changes around the existing
writeTeam/writeGlobal/apply/flush sequences and reuse the same assertions that
check types (ActivityTypeCreatedLabel, ActivityTypeEditedLabel,
ActivityTypeDeletedLabel) and name membership to ensure team manual and
host_vitals paths are covered.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0196fe1e-47b0-4d05-b05b-f4de04af5baf

📥 Commits

Reviewing files that changed from the base of the PR and between de8db29 and b4decac.

📒 Files selected for processing (4)
  • cmd/fleetctl/integrationtest/gitops/gitops_enterprise_integration_test.go
  • server/service/hosts.go
  • server/service/labels.go
  • server/service/labels_test.go

nulmete
nulmete previously approved these changes May 1, 2026
Copy link
Copy Markdown
Member

@nulmete nulmete left a comment

Choose a reason for hiding this comment

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

Haven't tested locally but code LGTM.
I think the only comment that we might need to address is the one related to "treating no rows as an error, or return an empty slice". The other are stylistic/architectural.

Comment thread server/datastore/mysql/labels.go
Comment thread server/service/hosts.go
Comment thread server/service/hosts.go Outdated
Comment thread server/service/labels.go
Comment on lines +114 to +115
ID: label.ID,
Name: label.Name,
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

If I remember correctly, all labels are treated as global as of now, correct?
(So, in the UI we'll never show which fleet this label was created for)

If so, should we put a comment or create a sub-task to pass in the FleetID and FleetName here for future reference?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agree, a comment makes sense.

Comment thread server/service/labels.go Outdated
Comment on lines +805 to +807
// labelMatchesScope reports whether the given label belongs to the team scope
// identified by teamID (nil means global scope).
func labelMatchesScope(l *fleet.Label, teamID *uint) bool {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: what about renaming to labelMatchesTeamScope and dropping the comment? I think the function is small enough that we can infer it does that.

same comment for:

  • the labelSpecMatchesLabel function below (though the function name and arguments are clear to me)
  • the lookupTeamNameForLabel function at the bottom.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good idea.

PS: I'll keep comment for labelSpecMatchesLabel to indicate that currently it's through GitOps that you can edit all label fields.

Comment thread server/service/labels.go Outdated

// lookupTeamNameForLabel returns the team name for the given team ID, or nil
// if the team ID is nil (global label).
func (svc *Service) lookupTeamNameForLabel(ctx context.Context, teamID *uint) (*string, error) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🤔 I thought we were passing a label as an argument (since I read "ForLabel" in the function name)

could this function name be simplified to just "lookupTeamName" or "getTeamName"? (we can infer it's for the given teamID that we pass, so no need to include the "For..." suffix IMHO)

Comment thread server/service/labels.go
Comment on lines +570 to +582
if err := svc.ds.DeleteLabel(ctx, label.Name, filter); err != nil {
return err
}

if err := svc.NewActivity(ctx, vc.User, fleet.ActivityTypeDeletedLabel{
ID: label.ID,
Name: label.Name,
FleetID: label.TeamID,
FleetName: label.TeamName,
}); err != nil {
return ctxerr.Wrap(ctx, err, "create activity for label deletion")
}
return nil
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

if the label was deleted but the activity creation failed we'd report an error back to the UI, correct? Not likely to happen, but who knows

anyways, I think this is an existing pattern to create activities right after the main operation of the endpoints (I've seen this in other endpoints as well)

IMHO, creating an activity after something is done is a side effect that should be done asynchronously and shouldn't affect the return status/body of the endpoint

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

going to deep here 😅 but in a past project, we had an "operations" layer that was in between the API layer (handler.go) and service layer (this method)... so:

  • if we needed to perform ANY async operation, then we would call the operations layer (API -> operations -> service)
  • if everything was synchronous, then we'd directly call the service layer (API -> service)

usually operations would involve some enqueuing an async job, so in this case I think we'd enqueue a job to create such activity after the service call to DeleteLabel.

happy to follow-up on this if this is something that would add value in the long run :)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Agree, this is the current pattern. Needs some revisiting.

Comment thread server/service/hosts.go
Comment on lines +3612 to 3613
labelNames = server.RemoveDuplicatesFromSlice(labelNames)
labelIDs, err := svc.validateLabelNames(ctx, "remove", labelNames, tmID)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nit: we call validateLabelNames in two different places, so we have to call RemoveDuplicatesFromSlice in both places. Should we consider deduping inside validateLabelNames?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I actually moved it outside so that the deduped label names are used in the outer scope (issue caught by AI).

@lucasmrod lucasmrod merged commit 1e4a9f2 into main May 1, 2026
61 checks passed
@lucasmrod lucasmrod deleted the 36976-activities-for-labels branch May 1, 2026 13:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

New activities for creating/editing/deleting labels

3 participants