diff --git a/go.mod b/go.mod index 84623a0c..91d4e5bf 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( charm.land/glamour/v2 v2.0.1 charm.land/lipgloss/v2 v2.0.6 github.com/basecamp/actioncable-client/go/v2 v2.0.2 - github.com/basecamp/hey-sdk/go v0.35.0 + github.com/basecamp/hey-sdk/go v0.35.1 github.com/basecamp/mcp v0.0.0-20261119020105-1a6d02c5380a github.com/charmbracelet/x/ansi v0.11.9 github.com/fsnotify/fsnotify v1.10.1 diff --git a/go.sum b/go.sum index 5de6472e..f414ba73 100644 --- a/go.sum +++ b/go.sum @@ -91,8 +91,8 @@ github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuP github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= github.com/basecamp/actioncable-client/go/v2 v2.0.2 h1:h2Sl15gj2lI/EX5E0EUxjyYgf0LF9Gn1zqEUInSrUpc= github.com/basecamp/actioncable-client/go/v2 v2.0.2/go.mod h1:3Y0N9V5LXclT5nQWcPhq/+6rj4eKXgKAX8dx15X8yB8= -github.com/basecamp/hey-sdk/go v0.35.0 h1:gV9Y8JweijV8vKeIQvkYj1Kk+liq3iuJNoOnUgVD4BA= -github.com/basecamp/hey-sdk/go v0.35.0/go.mod h1:ILC2upnVketSzbZTcN1iICeCpjCqvYpIflYcEVrgigw= +github.com/basecamp/hey-sdk/go v0.35.1 h1:azrn9JoilQaQ3QDBtZb4hiROmQFUyEIWWVWFq65wSTw= +github.com/basecamp/hey-sdk/go v0.35.1/go.mod h1:g4+w+Htmntp03iF9L7afzWyPVYeQzxFUYONlw9r4R+s= github.com/basecamp/mcp v0.0.0-20261119020105-1a6d02c5380a h1:5SI0hmC3B5wLusmAG917J9HGWnU2JLV+S2Ek8A0ABxk= github.com/basecamp/mcp v0.0.0-20261119020105-1a6d02c5380a/go.mod h1:K3sgTH90CIR6Ed0XPnivIBqNIpw6aeOlcXThBrZ+2gc= github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w= diff --git a/internal/cmd/draft.go b/internal/cmd/draft.go index 8830de34..33606eba 100644 --- a/internal/cmd/draft.go +++ b/internal/cmd/draft.go @@ -38,7 +38,7 @@ type draftOutput struct { func draftOutputFor(id int64, edit *generated.MessageEditState) draftOutput { out := draftOutput{ - From: edit.Sender.EmailAddress, + From: hey.DraftSentAs(edit).EmailAddress, ID: id, Subject: edit.Subject, Body: htmlutil.ToMarkdown(edit.Content), @@ -48,9 +48,6 @@ func draftOutputFor(id int64, edit *generated.MessageEditState) draftOutput { IsReply: edit.IsReply, AppURL: draftAppURL(id), } - if edit.Sender.Id == 0 { - out.From = edit.Creator.EmailAddress - } if !edit.ScheduledDeliveryAt.IsZero() { at := edit.ScheduledDeliveryAt out.ScheduledDeliveryAt = &at @@ -80,37 +77,6 @@ func parseDraftID(arg string) (int64, error) { return id, nil } -// draftContentFrom is the edit state as the full DraftContent an update resends. HEY -// revises a draft from the whole request, so every verb that writes one starts here. -func draftContentFrom(edit *generated.MessageEditState) hey.DraftContent { - content := hey.DraftContent{ - Subject: edit.Subject, - Content: edit.Content, - To: addressEmails(edit.Addressed.Directly), - CC: addressEmails(edit.Addressed.Copied), - BCC: addressEmails(edit.Addressed.Blindcopied), - - // The identity the draft was saved as rides every rewrite, or a draft - // composed from a shared or alternate address would be handed back to - // the account default by its first edit or the final send. - ActingSenderID: edit.Sender.Id, - } - if content.ActingSenderID == 0 { - // HEY omits sender when the draft is sent as its creator contact. - content.ActingSenderID = edit.Creator.Id - } - if !edit.ScheduledDeliveryAt.IsZero() { - // HEY's API reads a schedule's date and hour in UTC (ApiRequest sets - // Time.zone to UTC for every JSON request), so the served UTC moment is - // said back as its own UTC date and hour — the exact round-trip, whatever - // clock the host or the identity keeps. Proven live: an identity-zone - // conversion here moved a 09:00Z delivery to 04:00Z on the first edit. - at := edit.ScheduledDeliveryAt.UTC() - content.Schedule = &hey.DraftSchedule{Date: at.Format("2006-01-02"), Hour: at.Hour()} - } - return content -} - // preservableSchedule refuses an edit that could not keep the draft's scheduled // delivery where it is. HEY's API expresses a schedule as a whole UTC hour, so an // instant between hours — set from a HEY app on a fractional-offset clock like @@ -262,7 +228,7 @@ func (c *draftEditCommand) run(cmd *cobra.Command, args []string) error { if scheduleErr := preservableSchedule(edit); scheduleErr != nil { return scheduleErr } - content := draftContentFrom(edit) + content := hey.DraftContentFromEdit(edit) flags := cmd.Flags() fieldFlagged := flags.Changed("from") @@ -402,7 +368,7 @@ func (c *draftSendCommand) run(cmd *cobra.Command, args []string) error { if edit == nil { return apierr.ErrNotFound("draft", args[0]) } - content := draftContentFrom(edit) + content := hey.DraftContentFromEdit(edit) if len(content.To)+len(content.CC)+len(content.BCC) == 0 { return apierr.ErrUsageHint("the draft has no recipients", fmt.Sprintf("hey draft edit %d --to ", draftID)) } diff --git a/internal/cmd/thread_reply.go b/internal/cmd/thread_reply.go index 565c2420..cbf31d24 100644 --- a/internal/cmd/thread_reply.go +++ b/internal/cmd/thread_reply.go @@ -25,9 +25,9 @@ type replyRecipients = mail.ReplyRecipients // either: HEY never derives one, // so a reply sent without it saves drafts that read "No subject" in Drafts. // ActingSenderID is the identity the reply goes out as: the sender HEY resolved for -// the thread (or an explicit --from override), which on a shared or alternate address -// is not the account default; zero -// (the prefill named none, or was unreachable) leaves the SDK on the account default. +// the thread, else the acting user's own contact (or an explicit --from override), +// which on a shared or alternate address is not the account default; zero (the +// prefill was unreachable) leaves the SDK on the account default. type threadReplyTarget struct { EntryID int64 AccountID int64 diff --git a/internal/mail/reply_prefill.go b/internal/mail/reply_prefill.go index 796d9e8a..06aaaadc 100644 --- a/internal/mail/reply_prefill.go +++ b/internal/mail/reply_prefill.go @@ -37,8 +37,8 @@ type ReplyPrefill struct { // ReplyPrefillFromServer asks HEY how a reply to the entry starts out // (GET /entries/{id}/replies/new): the "Re: …" subject the reply carries; the sender // it goes out as — resolved from the entry's own to and from addresses, so a thread on -// a shared or alternate address answers as that address, not the account default, and -// named only when it differs from the acting user; and its recipients — the entry's +// a shared or alternate address answers as that address, not the account default, or +// else the acting user's own contact; and its recipients — the entry's // sender moved onto the To line and the acting user's own addresses, aliases and // catch-alls excluded — the exclusion no client can compute locally, and the reason // a reply used to be able to CC its writer back to themselves. A false answer sends @@ -52,13 +52,17 @@ func ReplyPrefillFromServer(ctx context.Context, client *hey.Client, entryID int if err != nil || prefilled == nil { return ReplyPrefill{}, false } + // HEY names the prefill's sender only when it differs from the acting user's + // own contact, the creator; zero would leave the SDK on the account's default + // sender, which need not be that address. + sentAs := hey.ReplySentAs(prefilled) prefill := ReplyPrefill{ Subject: prefilled.Subject, - ActingSenderID: prefilled.Sender.Id, + ActingSenderID: sentAs.Id, Sender: ReplySender{ - ID: prefilled.Sender.Id, - Name: prefilled.Sender.Name, - EmailAddress: prefilled.Sender.EmailAddress, + ID: sentAs.Id, + Name: sentAs.Name, + EmailAddress: sentAs.EmailAddress, }, Addressed: ReplyRecipients{ To: contactEmails(prefilled.Addressed.Directly), diff --git a/internal/mail/reply_prefill_test.go b/internal/mail/reply_prefill_test.go index 8da923d4..91f35b34 100644 --- a/internal/mail/reply_prefill_test.go +++ b/internal/mail/reply_prefill_test.go @@ -62,6 +62,29 @@ func TestReplyPrefillFromServer(t *testing.T) { } } +// HEY names the prefill's sender only when it differs from the acting user's own +// contact, so a reply from the person's own address carries the creator alone. That +// creator is the identity it goes out as: zero would leave the SDK on the account's +// default sender, which need not be the person's own address. +func TestReplyPrefillFromServerGoesOutAsTheCreatorWithoutASender(t *testing.T) { + client := replyPrefillClient(t, `{ + "subject": "Re: Weekly sync", "is_reply": true, + "creator": {"id": 77, "name": "Maria", "email_address": "maria@hey.com"}, + "addressed": {"directly": [{"id": 31, "email_address": "rick@example.com"}]} + }`) + + prefill, ok := ReplyPrefillFromServer(context.Background(), client, 12) + if !ok { + t.Fatal("an addressed prefill answers; no fallback is needed") + } + if prefill.ActingSenderID != 77 { + t.Errorf("acting sender = %d, want the creator's 77", prefill.ActingSenderID) + } + if want := (ReplySender{ID: 77, Name: "Maria", EmailAddress: "maria@hey.com"}); prefill.Sender != want { + t.Errorf("sender = %+v, want %+v", prefill.Sender, want) + } +} + // The subject and sender are answered even when the recipients are not: on a thread // with yourself, everyone HEY excludes is everyone there is, and only the recipients // need the caller's local fallback. diff --git a/internal/mcpserver/dispatch.go b/internal/mcpserver/dispatch.go index 3605c445..e63bafb9 100644 --- a/internal/mcpserver/dispatch.go +++ b/internal/mcpserver/dispatch.go @@ -70,6 +70,14 @@ func (d dispatcher) handle(ctx context.Context, dom gateway.Domain, op gateway.O return gateway.ErrorResult("%v", err), nil } + if full.ID == "UpdateMessage" { + kept, err := keepSavedSender(ctx, d.api, full.Action, params) + if err != nil { + return gateway.ErrorResult("%v", err), nil + } + params = kept + } + path, body, err := buildRequest(full, params) if err != nil { return gateway.ErrorResult("%v", err), nil diff --git a/internal/mcpserver/drafts.go b/internal/mcpserver/drafts.go index 96786da5..1ddcb601 100644 --- a/internal/mcpserver/drafts.go +++ b/internal/mcpserver/drafts.go @@ -1,6 +1,7 @@ package mcpserver import ( + "context" "encoding/json" "errors" "fmt" @@ -9,8 +10,10 @@ import ( "net/url" "regexp" "slices" + "strconv" "strings" + "github.com/basecamp/hey-sdk/go/pkg/generated" hey "github.com/basecamp/hey-sdk/go/pkg/hey" "github.com/basecamp/mcp/catalog" @@ -83,6 +86,56 @@ func draftOnly(action string, params map[string]any) (map[string]any, error) { return out, nil } +// draftEditPath is GetMessageEdit's path, where keepSavedSender reads the +// identity a draft was saved as. TestDraftEditPathIsTheModels holds it to the +// catalog. +const draftEditPath = "/messages/{messageId}/edit.json" + +// keepSavedSender gives an update_message that leaves out acting_sender_id the +// identity the draft was saved as: its sender, else its creator +// (hey.DraftSentAs). HEY revises a draft from the whole request, and a revision +// without acting_sender_id drops the draft's sender, so a draft saved from a +// shared or alternate address would quietly move to the account's own. A +// sender the caller chose is left as it is. params is not modified. +func keepSavedSender(ctx context.Context, api API, action string, params map[string]any) (map[string]any, error) { + if given, ok := params["acting_sender_id"]; ok && given != nil { + return params, nil + } + id, err := scalarString(params["messageId"]) + if _, given := params["messageId"]; !given || err != nil { + // buildRequest names the missing or unusable path parameter. + return params, nil //nolint:nilerr // reported by buildRequest instead + } + unread := func(why string) error { + return fmt.Errorf("%s keeps the address a draft sends from, and couldn't read draft %s's: %s. Nothing was changed. Pass acting_sender_id to choose it", + action, id, why) + } + resp, err := api.Get(ctx, strings.ReplaceAll(draftEditPath, "{messageId}", url.PathEscape(id))) + if err != nil { + return nil, unread(err.Error()) + } + var edit generated.MessageEditState + var page struct { + Postings any `json:"postings"` + } + if json.Unmarshal(resp.Data, &edit) != nil || json.Unmarshal(resp.Data, &page) != nil { + return nil, unread("HEY's answer was unreadable") + } + // HEY answers the edit page of a sent or deleted draft by redirecting to + // the Imbox, which the client follows; only the draft's own answer names + // the identity it was saved as. + if strconv.FormatInt(edit.Id, 10) != id || page.Postings != nil { + return nil, unread("it isn't a draft any more: it was sent or deleted") + } + sentAs := hey.DraftSentAs(&edit).Id + if sentAs == 0 { + return nil, unread("HEY named no sender for it") + } + out := maps.Clone(params) + out["acting_sender_id"] = sentAs + return out, nil +} + // savedAsDraft reports whether HEY acknowledged a draft save: 204 and a // Location naming the draft (haystack's respond_with_location_url). Anything // else is unconfirmed. Delivery answers the sent message, and an entry HEY @@ -185,7 +238,7 @@ func draftResult(resp *hey.Response, sendable bool) map[string]any { // draftDoc leads the description of each draft-first operation, so describe // tells the caller what this server does rather than what the wire can do. -const draftDoc = "Through hey mcp this only saves a draft: entry.status is always \"drafted\", and entry takes only addressed. It never delivers or schedules mail, and a request to send, schedule or triage is refused before HEY is contacted. Updating a scheduled draft clears its schedule. To deliver, " + howToSend + ". HEY's description of the endpoint follows; its delivery and scheduling paths aren't reachable here.\n\n" +const draftDoc = "Through hey mcp this only saves a draft: entry.status is always \"drafted\", and entry takes only addressed. It never delivers or schedules mail, and a request to send, schedule or triage is refused before HEY is contacted. Updating a scheduled draft clears its schedule. Updating a draft without acting_sender_id keeps the address it sends from. To deliver, " + howToSend + ". HEY's description of the endpoint follows; its delivery and scheduling paths aren't reachable here.\n\n" // holdToDrafts rewrites each draft-first operation in the catalog to // describe the draft-only contract: its summary (which the tool description @@ -203,6 +256,12 @@ func holdToDrafts(cat *catalog.Catalog) error { if err != nil { return fmt.Errorf("%s: %w", op.ID, err) } + if op.ID == "UpdateMessage" { + // The model reuses CreateMessage's body, which requires + // acting_sender_id; an update may leave it out to keep the + // address the draft sends from (keepSavedSender). + dropRequired(body, "acting_sender_id") + } op.Body = body op.Summary = strings.TrimSuffix(op.Summary, ".") + " (saved as a draft, never sent)" op.Doc = draftDoc + op.Doc @@ -211,6 +270,22 @@ func holdToDrafts(cat *catalog.Catalog) error { return nil } +// dropRequired takes name out of a JSON schema's required list. +func dropRequired(schema map[string]any, name string) { + required, _ := schema["required"].([]any) + kept := make([]any, 0, len(required)) + for _, r := range required { + if r != name { + kept = append(kept, r) + } + } + if len(kept) == 0 { + delete(schema, "required") + return + } + schema["required"] = kept +} + // draftBody returns a copy of body whose entry allows only draftEntryKeys, // with status pinned to "drafted". func draftBody(body map[string]any) (map[string]any, error) { diff --git a/internal/mcpserver/drafts_test.go b/internal/mcpserver/drafts_test.go index c39da3b2..b3adbaad 100644 --- a/internal/mcpserver/drafts_test.go +++ b/internal/mcpserver/drafts_test.go @@ -372,6 +372,7 @@ func TestDescribeServesTheDraftOnlyContract(t *testing.T) { Summary string `json:"summary"` Doc string `json:"doc"` Body struct { + Required []string `json:"required"` Properties struct { Entry struct { Properties map[string]map[string]any `json:"properties"` @@ -399,6 +400,11 @@ func TestDescribeServesTheDraftOnlyContract(t *testing.T) { if entry.AdditionalProperties == nil || *entry.AdditionalProperties { t.Error("entry schema admits other properties") } + // An update may leave acting_sender_id out to keep the draft's + // sender; a new draft still names one. + if requires := slices.Contains(op.Body.Required, "acting_sender_id"); requires == (action == "update_message") { + t.Errorf("%s body required = %v", action, op.Body.Required) + } }) } } @@ -534,3 +540,123 @@ func TestDescribeServesNoWireMechanics(t *testing.T) { } } } + +// routedAPI answers each request by method and path, and records every one. +type routedAPI struct { + fakeAPI + routes map[string]*hey.Response + calls []string +} + +func (r *routedAPI) answer(method, path string, body any) (*hey.Response, error) { + r.calls = append(r.calls, method+" "+path) + if method != "GET" { + r.method, r.path, r.body = method, path, body + } + if resp, ok := r.routes[method+" "+path]; ok { + return resp, nil + } + return nil, &hey.Error{HTTPStatus: http.StatusNotFound, Message: "not found"} +} + +func (r *routedAPI) Get(_ context.Context, path string) (*hey.Response, error) { + return r.answer("GET", path, nil) +} +func (r *routedAPI) Put(_ context.Context, path string, body any) (*hey.Response, error) { + return r.answer("PUT", path, body) +} + +func editState(json string) *hey.Response { + return &hey.Response{StatusCode: http.StatusOK, Data: []byte(json)} +} + +// An update_message without acting_sender_id keeps the identity the draft was +// saved as: HEY drops a draft's sender from a revision that names none, so a +// draft from a shared or alternate address would move to the account's own. +func TestUpdateMessageKeepsTheSavedSender(t *testing.T) { + cases := map[string]struct { + edit string + want float64 + }{ + "saved from an alternate address": {`{"id":5,"sender":{"id":215},"creator":{"id":11}}`, 215}, + "saved from the person's own": {`{"id":5,"creator":{"id":11}}`, 11}, + "with null postings": {`{"id":5,"postings":null,"creator":{"id":11}}`, 11}, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + api := &routedAPI{routes: map[string]*hey.Response{ + "GET /messages/5/edit.json": editState(tc.edit), + "PUT /messages/5": draftSaved("/messages/5"), + }} + params := paramsFor("update_message", nil) + delete(params, "acting_sender_id") + if text, isError := callThreads(t, api, "update_message", params); isError { + t.Fatalf("update refused: %s", text) + } + if got := sentBody(t, &api.fakeAPI)["acting_sender_id"]; got != tc.want { + t.Errorf("acting_sender_id = %v, want %v", got, tc.want) + } + if _, given := params["acting_sender_id"]; given { + t.Error("the caller's params were modified") + } + }) + } +} + +// A sender the caller chose is theirs: no read, no override. +func TestUpdateMessageWithASenderSendsIt(t *testing.T) { + api := &routedAPI{routes: map[string]*hey.Response{"PUT /messages/5": draftSaved("/messages/5")}} + if text, isError := callThreads(t, api, "update_message", paramsFor("update_message", nil)); isError { + t.Fatalf("update refused: %s", text) + } + if !reflect.DeepEqual(api.calls, []string{"PUT /messages/5"}) { + t.Errorf("calls = %v, want the update alone", api.calls) + } + if got := sentBody(t, &api.fakeAPI)["acting_sender_id"]; got != float64(1) { + t.Errorf("acting_sender_id = %v, want the caller's 1", got) + } +} + +// When the draft's identity can't be read, nothing is changed: an update +// without it is the one that moves the draft. +func TestUpdateMessageRefusesWhenTheSavedSenderIsUnknown(t *testing.T) { + cases := map[string]map[string]*hey.Response{ + "edit unreadable": {}, + "names no sender": {"GET /messages/5/edit.json": editState(`{"id":5}`)}, + "garbled response": {"GET /messages/5/edit.json": editState(`not json`)}, + // A sent or deleted draft's edit page redirects to a box, which the + // client follows: its identity isn't the draft's. + "another message's": {"GET /messages/5/edit.json": editState(`{"id":6,"sender":{"id":215}}`)}, + "a box's postings": {"GET /messages/5/edit.json": editState(`{"id":5,"postings":[],"creator":{"id":11}}`)}, + } + for name, routes := range cases { + t.Run(name, func(t *testing.T) { + routes["PUT /messages/5"] = draftSaved("/messages/5") + api := &routedAPI{routes: routes} + params := paramsFor("update_message", nil) + delete(params, "acting_sender_id") + text, isError := callThreads(t, api, "update_message", params) + if !isError || !strings.Contains(text, "Nothing was changed") || !strings.Contains(text, "acting_sender_id") { + t.Errorf("result = %q (error %v), want a refusal naming acting_sender_id", text, isError) + } + if slices.Contains(api.calls, "PUT /messages/5") { + t.Error("the draft was revised anyway") + } + }) + } +} + +func TestDraftEditPathIsTheModels(t *testing.T) { + cat := loadForTest(t) + for _, d := range cat.Domains { + for _, op := range d.Operations { + if op.ID == "GetMessageEdit" { + if op.Path != draftEditPath { + t.Errorf("GetMessageEdit path = %q, draftEditPath = %q", op.Path, draftEditPath) + } + return + } + } + } + t.Fatal("GetMessageEdit isn't in the catalog") +} diff --git a/internal/mcpserver/model/PROVENANCE.json b/internal/mcpserver/model/PROVENANCE.json index 71e7a22d..2fefd961 100644 --- a/internal/mcpserver/model/PROVENANCE.json +++ b/internal/mcpserver/model/PROVENANCE.json @@ -1,7 +1,7 @@ { "source": "github.com/basecamp/hey-sdk", - "commit": "4b256e98a811995a82bd3b94a7c739f24fe728a0", - "ref": "go/v0.35.0", + "commit": "8edac1066c638b8f479dba20645802658c59eb26", + "ref": "go/v0.35.1", "files": ["behavior-model.json", "openapi.json"], "synced_by": "scripts/sync-mcp-model.sh" } diff --git a/internal/mcpserver/model/openapi.json b/internal/mcpserver/model/openapi.json index 1ef97d39..998ad8b5 100644 --- a/internal/mcpserver/model/openapi.json +++ b/internal/mcpserver/model/openapi.json @@ -15782,11 +15782,11 @@ }, "scheduled_delivery_at_date": { "type": "string", - "description": "The delivery date: YYYY-MM-DD, \"today\" or \"tomorrow\", read in the identity's\ntime zone." + "description": "The delivery date: YYYY-MM-DD, \"today\" or \"tomorrow\", read in UTC, as HEY's\nAPI reads every JSON request's times." }, "scheduled_delivery_at_hour": { "type": "string", - "description": "The delivery hour, \"0\" through \"23\" — a string so that midnight survives\nomitempty. HEY schedules to the hour." + "description": "The delivery hour, \"0\" through \"23\", in UTC like the date — a string so that\nmidnight survives omitempty. HEY schedules to the hour." } } }, diff --git a/internal/mcpserver/param_contract_test.go b/internal/mcpserver/param_contract_test.go index 4f27c395..81f937d3 100644 --- a/internal/mcpserver/param_contract_test.go +++ b/internal/mcpserver/param_contract_test.go @@ -12,6 +12,7 @@ import ( "strings" "testing" + hey "github.com/basecamp/hey-sdk/go/pkg/hey" "github.com/modelcontextprotocol/go-sdk/mcp" "github.com/basecamp/mcp/catalog" @@ -217,7 +218,13 @@ type reachFunc func(in, name string, value any) bool func send(t *testing.T, domain *catalog.Domain, op *catalog.Operation, params map[string]any) (reachFunc, string) { t.Helper() api := &fakeAPI{} - res, err := dispatcher{api: api}.handle(context.Background(), domain, gateway.Operation{Action: op.Action}, params) + var client API = api + if op.ID == "UpdateMessage" { + // An update without acting_sender_id first reads the draft's + // sender (keepSavedSender); that read isn't the request checked. + client = savedSenderAPI{api} + } + res, err := dispatcher{api: client}.handle(context.Background(), domain, gateway.Operation{Action: op.Action}, params) if err != nil { t.Fatalf("%s: %v", op.Action, err) } @@ -339,3 +346,15 @@ func decoded(t *testing.T, body any) map[string]any { m, _ := roundTrip(t, body).(map[string]any) return m } + +// savedSenderAPI answers a draft's edit state, as the draft the path names, +// with the sender it was saved as, unrecorded, and passes every other +// request to the fake. +type savedSenderAPI struct{ *fakeAPI } + +func (a savedSenderAPI) Get(ctx context.Context, path string) (*hey.Response, error) { + if id, ok := strings.CutSuffix(strings.TrimPrefix(path, "/messages/"), "/edit.json"); ok { + return &hey.Response{StatusCode: 200, Data: []byte(`{"id":` + id + `,"creator":{"id":1}}`)}, nil + } + return a.fakeAPI.Get(ctx, path) +} diff --git a/internal/mcpserver/send.go b/internal/mcpserver/send.go index 61691dee..be59d95f 100644 --- a/internal/mcpserver/send.go +++ b/internal/mcpserver/send.go @@ -443,7 +443,7 @@ func snapshotOf(edit *generated.MessageEditState) (*draftSnapshot, error) { } snap := &draftSnapshot{ id: edit.Id, - from: edit.Sender, + from: hey.DraftSentAs(edit), to: edit.Addressed.Directly, cc: edit.Addressed.Copied, bcc: edit.Addressed.Blindcopied, @@ -451,11 +451,8 @@ func snapshotOf(edit *generated.MessageEditState) (*draftSnapshot, error) { body: body, scheduled: edit.ScheduledDeliveryAt, } - // HEY omits sender when the draft is sent as its creator contact, and the identity - // the draft was saved as rides the send (cmd's draftContentFrom does the same). - if snap.from.Id == 0 { - snap.from = edit.Creator - } + // The identity the draft was saved as rides the send: its sender, else its + // creator, which HEY names alone when the draft is sent as the creator contact. snap.actingSenderID = snap.from.Id sorted := func(contacts []generated.Contact) []string { diff --git a/nix/package.nix b/nix/package.nix index 389ad224..7360ab7c 100644 --- a/nix/package.nix +++ b/nix/package.nix @@ -18,7 +18,7 @@ buildGoModule.override { inherit go; } (finalAttrs: { # To update: run `make update-nix-hash` (Docker). It rewrites this quoted # value in place, so keep it a string literal rather than lib.fakeHash. - vendorHash = "sha256-gOw2wj1pYIrpPKQ9i8bjl21LJetKwx9v3WCNs3ve3gQ="; + vendorHash = "sha256-HTzwLc9C5b+RY+fvg3i8mPz1fR8CxKkp6wiKHhNceSY="; subPackages = [ "cmd/hey" ];