Skip to content

Commit 51c3493

Browse files
authored
Fix todos update silently clearing completion subscribers (#540)
* Fix todos update silently clearing completion subscribers (#538) The BC3 todos PUT has replace semantics: any field omitted from the body is cleared. Neither branch of todos update included completion_subscriber_ids, so every update wiped the todo's "When done, notify" list. The #412/#413 read-modify-write merge couldn't preserve it because the SDK's Todo model drops completion_subscribers in todoFromGenerated (basecamp/basecamp-sdk#355) — the merge had nothing to carry forward. Preservation now works via a raw GET of the flat /todos/{id}.json route (which serves the field the SDK model drops), feeding the current subscriber ids into both the typed-merge and raw-clear PUT paths. The read fails closed: an HTTP error, malformed JSON, or a response missing the completion_subscribers key aborts the command before any PUT rather than risking a silent clear. The helper is commented as temporary and goes away once the SDK round-trips the field. Alongside the fix, subscribers become directly editable: - todos create/update --notify-on-completion <names or ids> sets them (comma-separated, with people-name tab completion) - todos update --no-notify-on-completion clears them (by omission — explicit intent skips the preservation read entirely) Unit tests cover preservation in both branches, the flat-route assertion, explicit set/clear bypassing the read, the fail-closed matrix (missing key / malformed JSON / HTTP 500 in each branch), flag conflicts, and the create body. A live smoke test exercises the full sequence: create with subscriber, title-only update preserves, --no-due preserves, --no-notify-on-completion clears. .surface gains the three new flag records by hand (verified identical to fresh generation); a full regeneration is deferred because the snapshot has unrelated drift since #499 changed the generator script. * Use completion-subscriber wording in --notify-on-completion errors --notify-on-completion resolved people through resolveAssigneeIDs, so failures surfaced as assignee errors ("No valid assignees provided", "Assignee ID must be a positive number") — misleading for a flag that sets completion subscribers. Parameterize the resolver with a role label: resolvePersonRoleID(s) carry the wording, and resolveAssigneeID(s) stay as assignee-labeled wrappers so existing call sites and messages are unchanged. The subscriber call sites now go through resolveCompletionSubscriberIDs. Tests cover both subscriber-worded messages and assert no PUT occurs on resolution failure. * Test the name-resolution failure path for --notify-on-completion The subscriber-wording tests covered the numeric-validation and empty-list errors but not the ResolvePerson miss, so the "failed to resolve completion subscriber" formatting was only exercised indirectly. The update mock now matches the flat preservation route exactly (/todos/999.json) instead of any .json GET, and serves /people routes an empty directory so name resolution deterministically misses. New subtest asserts the subscriber-worded resolve error and that no PUT occurs. The explicit set/clear tests tighten their no-preservation-read assertions to the exact route. * Address review: SDK error conversion + exact mock route match The preservation read's GET error now runs through convertSDKError before wrapping, so structured codes/hints (rate limit, circuit breaker) survive with the subscriber-specific context — matching every other raw Account() call site. The update mock's preservation branch now matches the account-scoped flat route exactly (/99999/todos/999.json) instead of by suffix, so a bucket-scoped GET can never satisfy it. * Reject missing or invalid subscriber ids in the preservation read A completion_subscribers element without a positive id would have put a zero into completion_subscriber_ids and reached the PUT, slipping past the fail-closed contract. The preservation read now errors on any non-positive id, and the fail-closed test matrix covers the case.
1 parent 6ec1a07 commit 51c3493

6 files changed

Lines changed: 402 additions & 12 deletions

File tree

‎.surface‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13091,6 +13091,7 @@ FLAG basecamp todos create --markdown type=bool
1309113091
FLAG basecamp todos create --md type=bool
1309213092
FLAG basecamp todos create --no-hints type=bool
1309313093
FLAG basecamp todos create --no-stats type=bool
13094+
FLAG basecamp todos create --notify-on-completion type=string
1309413095
FLAG basecamp todos create --profile type=string
1309513096
FLAG basecamp todos create --project type=string
1309613097
FLAG basecamp todos create --quiet type=bool
@@ -13359,9 +13360,11 @@ FLAG basecamp todos update --md type=bool
1335913360
FLAG basecamp todos update --no-description type=bool
1336013361
FLAG basecamp todos update --no-due type=bool
1336113362
FLAG basecamp todos update --no-hints type=bool
13363+
FLAG basecamp todos update --no-notify-on-completion type=bool
1336213364
FLAG basecamp todos update --no-starts-on type=bool
1336313365
FLAG basecamp todos update --no-stats type=bool
1336413366
FLAG basecamp todos update --notify type=bool
13367+
FLAG basecamp todos update --notify-on-completion type=string
1336513368
FLAG basecamp todos update --profile type=string
1336613369
FLAG basecamp todos update --project type=string
1336713370
FLAG basecamp todos update --quiet type=bool

‎e2e/smoke/smoke_todos_write.bats‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,55 @@ setup_file() {
138138
run_smoke basecamp todos trash "$todo_id" -p "$QA_PROJECT" --json
139139
}
140140

141+
@test "todos update preserves completion subscribers" {
142+
# Own person ID for use as a completion subscriber
143+
run_smoke basecamp api get /my/profile.json --json
144+
assert_success
145+
local person_id
146+
person_id=$(echo "$output" | jq -r '.data.id')
147+
[[ -n "$person_id" && "$person_id" != "null" ]] || mark_unverifiable "Cannot resolve own person ID"
148+
149+
# Create with a due date and a completion subscriber
150+
run_smoke basecamp todos create "Subscriber preservation test $(date +%s)" \
151+
--list "$QA_TODOLIST" -p "$QA_PROJECT" \
152+
--due "2026-08-15" \
153+
--notify-on-completion "$person_id" --json
154+
assert_success
155+
local todo_id
156+
todo_id=$(echo "$output" | jq -r '.data.id')
157+
158+
# Title-only update (typed merge branch) must preserve the subscriber
159+
run_smoke basecamp todos update "$todo_id" --title "Renamed, subscriber kept" --json
160+
assert_success
161+
162+
run_smoke basecamp api get "/todos/$todo_id.json" --json
163+
assert_success
164+
local subs
165+
subs=$(echo "$output" | jq -r '[.data.completion_subscribers[].id] | join(",")')
166+
[[ "$subs" == "$person_id" ]] || { echo "subscriber lost after title update: [$subs]"; return 1; }
167+
168+
# --no-due (raw clear branch) must also preserve the subscriber
169+
run_smoke basecamp todos update "$todo_id" --no-due --json
170+
assert_success
171+
172+
run_smoke basecamp api get "/todos/$todo_id.json" --json
173+
assert_success
174+
subs=$(echo "$output" | jq -r '[.data.completion_subscribers[].id] | join(",")')
175+
[[ "$subs" == "$person_id" ]] || { echo "subscriber lost after --no-due: [$subs]"; return 1; }
176+
177+
# --no-notify-on-completion clears the subscribers
178+
run_smoke basecamp todos update "$todo_id" --no-notify-on-completion --json
179+
assert_success
180+
181+
run_smoke basecamp api get "/todos/$todo_id.json" --json
182+
assert_success
183+
subs=$(echo "$output" | jq -r '.data.completion_subscribers | length')
184+
[[ "$subs" == "0" ]] || { echo "subscribers not cleared: $subs remain"; return 1; }
185+
186+
# Clean up
187+
run_smoke basecamp todos trash "$todo_id" -p "$QA_PROJECT" --json
188+
}
189+
141190
@test "todos trash trashes a todo" {
142191
local id_file="$BATS_FILE_TMPDIR/direct_todo_id"
143192
[[ -f "$id_file" ]] || mark_unverifiable "No direct todo created in prior test"

‎internal/commands/cards.go‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -347,27 +347,34 @@ You can pass either a card ID or a Basecamp URL:
347347
}
348348

349349
func resolveAssigneeID(ctx context.Context, app *appctx.App, input string) (int64, error) {
350+
return resolvePersonRoleID(ctx, app, input, "Assignee")
351+
}
352+
353+
// resolvePersonRoleID resolves a single person name or ID. The role label
354+
// ("Assignee", "Completion subscriber", …) names the person's role in error
355+
// messages so callers surface the flag the user actually passed.
356+
func resolvePersonRoleID(ctx context.Context, app *appctx.App, input, role string) (int64, error) {
350357
input = strings.TrimSpace(input)
351358
if input == "" {
352-
return 0, output.ErrUsage("Assignee cannot be empty")
359+
return 0, output.ErrUsage(fmt.Sprintf("%s cannot be empty", role))
353360
}
354361

355362
if id, err := strconv.ParseInt(input, 10, 64); err == nil {
356363
if id <= 0 {
357-
return 0, output.ErrUsage("Assignee ID must be a positive number")
364+
return 0, output.ErrUsage(fmt.Sprintf("%s ID must be a positive number", role))
358365
}
359366
return id, nil
360367
}
361368
resolvedID, _, err := app.Names.ResolvePerson(ctx, input)
362369
if err != nil {
363-
return 0, fmt.Errorf("failed to resolve assignee '%s': %w", input, err)
370+
return 0, fmt.Errorf("failed to resolve %s '%s': %w", strings.ToLower(role), input, err)
364371
}
365372
id, err := strconv.ParseInt(resolvedID, 10, 64)
366373
if err != nil {
367374
return 0, fmt.Errorf("invalid resolved ID '%s': %w", resolvedID, err)
368375
}
369376
if id <= 0 {
370-
return 0, fmt.Errorf("resolved assignee ID for '%s' is not valid: %d", input, id)
377+
return 0, fmt.Errorf("resolved %s ID for '%s' is not valid: %d", strings.ToLower(role), input, id)
371378
}
372379
return id, nil
373380
}
@@ -2460,6 +2467,12 @@ func resolveColumn(columns []basecamp.CardColumn, identifier string) int64 {
24602467
}
24612468

24622469
func resolveAssigneeIDs(ctx context.Context, app *appctx.App, input string) ([]int64, error) {
2470+
return resolvePersonRoleIDs(ctx, app, input, "Assignee")
2471+
}
2472+
2473+
// resolvePersonRoleIDs resolves a comma-separated list of person names or IDs,
2474+
// labeling errors with the given role (see resolvePersonRoleID).
2475+
func resolvePersonRoleIDs(ctx context.Context, app *appctx.App, input, role string) ([]int64, error) {
24632476
parts := strings.Split(input, ",")
24642477
ids := make([]int64, 0, len(parts))
24652478

@@ -2469,15 +2482,15 @@ func resolveAssigneeIDs(ctx context.Context, app *appctx.App, input string) ([]i
24692482
continue
24702483
}
24712484

2472-
id, err := resolveAssigneeID(ctx, app, part)
2485+
id, err := resolvePersonRoleID(ctx, app, part, role)
24732486
if err != nil {
24742487
return nil, err
24752488
}
24762489
ids = append(ids, id)
24772490
}
24782491

24792492
if len(ids) == 0 {
2480-
return nil, output.ErrUsage("No valid assignees provided")
2493+
return nil, output.ErrUsage(fmt.Sprintf("No valid %ss provided", strings.ToLower(role)))
24812494
}
24822495

24832496
return ids, nil

‎internal/commands/todos.go‎

Lines changed: 112 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -766,6 +766,7 @@ func newTodosCreateCmd() *cobra.Command {
766766
var due string
767767
var description string
768768
var attachFiles []string
769+
var notifyOnCompletion string
769770

770771
cmd := &cobra.Command{
771772
Use: "create <content>",
@@ -881,6 +882,13 @@ func newTodosCreateCmd() *cobra.Command {
881882
assigneeIDInt, _ := strconv.ParseInt(assigneeID, 10, 64)
882883
req.AssigneeIDs = []int64{assigneeIDInt}
883884
}
885+
if strings.TrimSpace(notifyOnCompletion) != "" {
886+
subscriberIDs, err := resolveCompletionSubscriberIDs(cmd.Context(), app, notifyOnCompletion)
887+
if err != nil {
888+
return err
889+
}
890+
req.CompletionSubscriberIDs = subscriberIDs
891+
}
884892

885893
todolistID, err := strconv.ParseInt(resolvedTodolist, 10, 64)
886894
if err != nil {
@@ -925,13 +933,15 @@ func newTodosCreateCmd() *cobra.Command {
925933
cmd.Flags().StringVarP(&due, "due", "d", "", "Due date (YYYY-MM-DD)")
926934
cmd.Flags().StringVar(&description, "description", "", "Extended description (Markdown)")
927935
cmd.Flags().StringArrayVar(&attachFiles, "attach", nil, "Attach file (repeatable)")
936+
cmd.Flags().StringVar(&notifyOnCompletion, "notify-on-completion", "", "People to notify when done (names or IDs, comma-separated)")
928937

929938
// Register tab completion for flags
930939
completer := completion.NewCompleter(nil)
931940
_ = cmd.RegisterFlagCompletionFunc("project", completer.ProjectNameCompletion())
932941
_ = cmd.RegisterFlagCompletionFunc("in", completer.ProjectNameCompletion())
933942
_ = cmd.RegisterFlagCompletionFunc("assignee", completer.PeopleNameCompletion())
934943
_ = cmd.RegisterFlagCompletionFunc("to", completer.PeopleNameCompletion())
944+
_ = cmd.RegisterFlagCompletionFunc("notify-on-completion", completer.PeopleNameCompletion())
935945

936946
return cmd
937947
}
@@ -946,6 +956,8 @@ func newTodosUpdateCmd() *cobra.Command {
946956
var noDue bool
947957
var noStartsOn bool
948958
var noDescription bool
959+
var notifyOnCompletion string
960+
var noNotifyOnCompletion bool
949961

950962
cmd := &cobra.Command{
951963
Use: "update <id|url> [title]",
@@ -961,7 +973,11 @@ You can pass either a todo ID or a Basecamp URL:
961973
Clear a field by passing its --no- flag or an empty value:
962974
basecamp todos update 789 --no-due
963975
basecamp todos update 789 --due ""
964-
basecamp todos update 789 --no-description`,
976+
basecamp todos update 789 --no-description
977+
978+
Set or clear the people notified when the todo is completed:
979+
basecamp todos update 789 --notify-on-completion "Jane Smith,Bob"
980+
basecamp todos update 789 --no-notify-on-completion`,
965981
RunE: func(cmd *cobra.Command, args []string) error {
966982
if len(args) == 0 {
967983
return missingArg(cmd, "<id|url>")
@@ -977,11 +993,17 @@ Clear a field by passing its --no- flag or an empty value:
977993
if noDescription && strings.TrimSpace(description) != "" {
978994
return output.ErrUsage("--no-description and --description cannot be used together")
979995
}
996+
if noNotifyOnCompletion && strings.TrimSpace(notifyOnCompletion) != "" {
997+
return output.ErrUsage("--no-notify-on-completion and --notify-on-completion cannot be used together")
998+
}
980999
// Detect clear intent: explicit --no-X flag or empty value via --X ""
9811000
clearDue := noDue || (cmd.Flags().Changed("due") && strings.TrimSpace(due) == "")
9821001
clearStarts := noStartsOn || (cmd.Flags().Changed("starts-on") && strings.TrimSpace(startsOn) == "")
9831002
clearDescription := noDescription || (cmd.Flags().Changed("description") && strings.TrimSpace(description) == "")
9841003
needsClear := clearDue || clearStarts || clearDescription
1004+
// Subscriber clearing works by omission in both branches, so it
1005+
// doesn't force the raw-PUT clear branch.
1006+
clearSubscribers := noNotifyOnCompletion || (cmd.Flags().Changed("notify-on-completion") && strings.TrimSpace(notifyOnCompletion) == "")
9851007

9861008
// Clearing due while setting starts is contradictory (Basecamp enforces starts <= due)
9871009
if clearDue && strings.TrimSpace(startsOn) != "" {
@@ -999,12 +1021,13 @@ Clear a field by passing its --no- flag or an empty value:
9991021

10001022
// No-op guard: at least one effective field required
10011023
assigneeChanged := (cmd.Flags().Changed("assignee") || cmd.Flags().Changed("to")) && strings.TrimSpace(assignee) != ""
1024+
subscribersChanged := cmd.Flags().Changed("notify-on-completion") && strings.TrimSpace(notifyOnCompletion) != ""
10021025
if strings.TrimSpace(effectiveTitle) == "" &&
10031026
strings.TrimSpace(description) == "" &&
10041027
strings.TrimSpace(due) == "" && strings.TrimSpace(startsOn) == "" &&
1005-
!assigneeChanged &&
1028+
!assigneeChanged && !subscribersChanged &&
10061029
(!cmd.Flags().Changed("notify") || !notify) &&
1007-
!needsClear {
1030+
!needsClear && !clearSubscribers {
10081031
return noChanges(cmd)
10091032
}
10101033

@@ -1100,6 +1123,26 @@ Clear a field by passing its --no- flag or an empty value:
11001123
body["assignee_ids"] = ids
11011124
}
11021125

1126+
// Completion subscribers: the SDK's Todo model drops them, so
1127+
// existingTodo can't supply them — set explicitly, clear by
1128+
// omission, or preserve via a raw read that must succeed
1129+
// before any PUT (fail closed).
1130+
if subscribersChanged {
1131+
subscriberIDs, err := resolveCompletionSubscriberIDs(cmd.Context(), app, notifyOnCompletion)
1132+
if err != nil {
1133+
return err
1134+
}
1135+
body["completion_subscriber_ids"] = subscriberIDs
1136+
} else if !clearSubscribers {
1137+
subscriberIDs, err := completionSubscriberIDs(cmd.Context(), app, todoID)
1138+
if err != nil {
1139+
return err
1140+
}
1141+
if len(subscriberIDs) > 0 {
1142+
body["completion_subscriber_ids"] = subscriberIDs
1143+
}
1144+
}
1145+
11031146
if cmd.Flags().Changed("notify") && notify {
11041147
body["notify"] = true
11051148
}
@@ -1166,6 +1209,25 @@ Clear a field by passing its --no- flag or an empty value:
11661209
}
11671210
req.AssigneeIDs = assigneeIDs
11681211
}
1212+
// Completion subscribers: the SDK's Todo model drops them, so
1213+
// existingTodo can't supply them — set explicitly, clear by
1214+
// omission (nil), or preserve via a raw read that must succeed
1215+
// before any PUT (fail closed).
1216+
if subscribersChanged {
1217+
subscriberIDs, err := resolveCompletionSubscriberIDs(cmd.Context(), app, notifyOnCompletion)
1218+
if err != nil {
1219+
return err
1220+
}
1221+
req.CompletionSubscriberIDs = subscriberIDs
1222+
} else if !clearSubscribers {
1223+
subscriberIDs, err := completionSubscriberIDs(cmd.Context(), app, todoID)
1224+
if err != nil {
1225+
return err
1226+
}
1227+
if len(subscriberIDs) > 0 {
1228+
req.CompletionSubscriberIDs = subscriberIDs
1229+
}
1230+
}
11691231
if cmd.Flags().Changed("notify") && notify {
11701232
req.Notify = true
11711233
}
@@ -1205,15 +1267,61 @@ Clear a field by passing its --no- flag or an empty value:
12051267
cmd.Flags().BoolVar(&noDue, "no-due", false, "Clear the due date")
12061268
cmd.Flags().BoolVar(&noStartsOn, "no-starts-on", false, "Clear the start date")
12071269
cmd.Flags().BoolVar(&noDescription, "no-description", false, "Clear the description")
1270+
cmd.Flags().StringVar(&notifyOnCompletion, "notify-on-completion", "", "People to notify when done (names or IDs, comma-separated)")
1271+
cmd.Flags().BoolVar(&noNotifyOnCompletion, "no-notify-on-completion", false, "Clear the people notified when done")
12081272

1209-
// Register tab completion for assignee flags
1273+
// Register tab completion for people flags
12101274
completer := completion.NewCompleter(nil)
12111275
_ = cmd.RegisterFlagCompletionFunc("assignee", completer.PeopleNameCompletion())
12121276
_ = cmd.RegisterFlagCompletionFunc("to", completer.PeopleNameCompletion())
1277+
_ = cmd.RegisterFlagCompletionFunc("notify-on-completion", completer.PeopleNameCompletion())
12131278

12141279
return cmd
12151280
}
12161281

1282+
// resolveCompletionSubscriberIDs resolves --notify-on-completion values
1283+
// (comma-separated names or IDs) with completion-subscriber wording in errors.
1284+
func resolveCompletionSubscriberIDs(ctx context.Context, app *appctx.App, input string) ([]int64, error) {
1285+
return resolvePersonRoleIDs(ctx, app, input, "Completion subscriber")
1286+
}
1287+
1288+
// completionSubscriberIDs reads the current completion subscriber ids via a raw
1289+
// GET of /todos/{id}.json. The SDK's Todo model drops completion_subscribers in
1290+
// todoFromGenerated (basecamp/basecamp-sdk#355), so a raw read is the only way
1291+
// to preserve them across the replace-semantics PUT (#538). Delete once the SDK
1292+
// round-trips the field.
1293+
//
1294+
// Fails closed: a missing or null completion_subscribers key, a malformed
1295+
// response, or a failed GET all return an error — proceeding without knowing
1296+
// the current subscribers would silently clear them.
1297+
func completionSubscriberIDs(ctx context.Context, app *appctx.App, todoID int64) ([]int64, error) {
1298+
resp, err := app.Account().Get(ctx, fmt.Sprintf("/todos/%d.json", todoID))
1299+
if err != nil {
1300+
return nil, fmt.Errorf("failed to read current completion subscribers for todo %d: %w", todoID, convertSDKError(err))
1301+
}
1302+
1303+
var raw struct {
1304+
CompletionSubscribers *[]struct {
1305+
ID int64 `json:"id"`
1306+
} `json:"completion_subscribers"`
1307+
}
1308+
if err := resp.UnmarshalData(&raw); err != nil {
1309+
return nil, fmt.Errorf("failed to parse completion subscribers for todo %d: %w", todoID, err)
1310+
}
1311+
if raw.CompletionSubscribers == nil {
1312+
return nil, fmt.Errorf("cannot verify current completion subscribers for todo %d: response missing completion_subscribers", todoID)
1313+
}
1314+
1315+
ids := make([]int64, len(*raw.CompletionSubscribers))
1316+
for i, s := range *raw.CompletionSubscribers {
1317+
if s.ID <= 0 {
1318+
return nil, fmt.Errorf("cannot verify current completion subscribers for todo %d: subscriber with missing or invalid id", todoID)
1319+
}
1320+
ids[i] = s.ID
1321+
}
1322+
return ids, nil
1323+
}
1324+
12171325
func newTodosCompleteCmd() *cobra.Command {
12181326
cmd := &cobra.Command{
12191327
Use: "complete <id|url>...",

0 commit comments

Comments
 (0)