Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
feat: unarchive message thread on new inbound message (per-phone setting) (#954)
Acho Arnold8010ce30a27e
diff --git a/.gitignore b/.gitignoreindex e15d590a..8f4caf4b 100644--- a/.gitignore+++ b/.gitignore@@ -13,7 +13,6 @@ SECURITY_AUDIT_REPORT.md*.exe-docs/.output.agents/skills-lock.jsondiff --git a/api/docs/docs.go b/api/docs/docs.goindex c5745825..c7fcd114 100644--- a/api/docs/docs.go+++ b/api/docs/docs.go@@ -3379,7 +3379,7 @@ const docTemplate = `{},"request_id": {"type": "string",- "example": "bulk-csv-a1B2c3D4e5"+ "example": "bulk-httpsms-file.csv"},"scheduled_count": {"type": "integer",@@ -3760,6 +3760,7 @@ const docTemplate = `{"messages_per_minute","phone_number","sim",+ "unarchive_thread","updated_at","user_id"],@@ -3804,6 +3805,11 @@ const docTemplate = `{"sim": {"$ref": "#/definitions/entities.SIM"},+ "unarchive_thread": {+ "description": "UnarchiveThread moves an archived message thread back to the inbox when a new message is received on this phone.",+ "type": "boolean",+ "example": false+ },"updated_at": {"type": "string","example": "2022-06-05T14:26:10.303278+03:00"@@ -4436,7 +4442,8 @@ const docTemplate = `{"messages_per_minute","missed_call_auto_reply","phone_number",- "sim"+ "sim",+ "unarchive_thread"],"properties": {"fcm_token": {@@ -4473,6 +4480,11 @@ const docTemplate = `{"description": "SIM is the SIM slot of the phone in case the phone has more than 1 SIM slot","type": "string","example": "SIM1"+ },+ "unarchive_thread": {+ "description": "UnarchiveThread moves an archived thread back to the inbox when a new message is received on this phone.",+ "type": "boolean",+ "example": false}}},diff --git a/api/docs/swagger.json b/api/docs/swagger.jsonindex 009797ca..25db6fc3 100644--- a/api/docs/swagger.json+++ b/api/docs/swagger.json@@ -3376,7 +3376,7 @@},"request_id": {"type": "string",- "example": "bulk-csv-a1B2c3D4e5"+ "example": "bulk-httpsms-file.csv"},"scheduled_count": {"type": "integer",@@ -3757,6 +3757,7 @@"messages_per_minute","phone_number","sim",+ "unarchive_thread","updated_at","user_id"],@@ -3801,6 +3802,11 @@"sim": {"$ref": "#/definitions/entities.SIM"},+ "unarchive_thread": {+ "description": "UnarchiveThread moves an archived message thread back to the inbox when a new message is received on this phone.",+ "type": "boolean",+ "example": false+ },"updated_at": {"type": "string","example": "2022-06-05T14:26:10.303278+03:00"@@ -4433,7 +4439,8 @@"messages_per_minute","missed_call_auto_reply","phone_number",- "sim"+ "sim",+ "unarchive_thread"],"properties": {"fcm_token": {@@ -4470,6 +4477,11 @@"description": "SIM is the SIM slot of the phone in case the phone has more than 1 SIM slot","type": "string","example": "SIM1"+ },+ "unarchive_thread": {+ "description": "UnarchiveThread moves an archived thread back to the inbox when a new message is received on this phone.",+ "type": "boolean",+ "example": false}}},diff --git a/api/docs/swagger.yaml b/api/docs/swagger.yamlindex bb004171..892c9ae4 100644--- a/api/docs/swagger.yaml+++ b/api/docs/swagger.yaml@@ -58,7 +58,7 @@ definitions:example: 30type: integerrequest_id:- example: bulk-csv-a1B2c3D4e5+ example: bulk-httpsms-file.csvtype: stringscheduled_count:example: 50@@ -388,6 +388,11 @@ definitions:type: stringsim:$ref: '#/definitions/entities.SIM'+ unarchive_thread:+ description: UnarchiveThread moves an archived message thread back to the+ inbox when a new message is received on this phone.+ example: false+ type: booleanupdated_at:example: "2022-06-05T14:26:10.303278+03:00"type: string@@ -402,6 +407,7 @@ definitions:- messages_per_minute- phone_number- sim+ - unarchive_thread- updated_at- user_idtype: object@@ -908,6 +914,11 @@ definitions:1 SIM slotexample: SIM1type: string+ unarchive_thread:+ description: UnarchiveThread moves an archived thread back to the inbox when+ a new message is received on this phone.+ example: false+ type: booleanrequired:- fcm_token- max_send_attempts@@ -916,6 +927,7 @@ definitions:- missed_call_auto_reply- phone_number- sim+ - unarchive_threadtype: objectrequests.UserNotificationUpdate:properties:diff --git a/api/pkg/di/container.go b/api/pkg/di/container.goindex f84f5b30..fafae1ae 100644--- a/api/pkg/di/container.go+++ b/api/pkg/di/container.go@@ -1111,6 +1111,7 @@ func (container *Container) MessageThreadService() (service *services.MessageThrcontainer.Logger(),container.Tracer(),container.MessageThreadRepository(),+ container.PhoneRepository(),container.EventDispatcher(),)}diff --git a/api/pkg/entities/phone.go b/api/pkg/entities/phone.goindex 97df6631..4f3c33f2 100644--- a/api/pkg/entities/phone.go+++ b/api/pkg/entities/phone.go@@ -24,6 +24,9 @@ type Phone struct {MissedCallAutoReply *string `json:"missed_call_auto_reply" example:"This phone cannot receive calls. Please send an SMS instead." validate:"optional"`+ // UnarchiveThread moves an archived message thread back to the inbox when a new message is received on this phone.+ UnarchiveThread bool `json:"unarchive_thread" gorm:"default:false" example:"false"`+CreatedAt time.Time `json:"created_at" example:"2022-06-05T14:26:02.302718+03:00"`UpdatedAt time.Time `json:"updated_at" example:"2022-06-05T14:26:10.303278+03:00"`}diff --git a/api/pkg/handlers/message_handler.go b/api/pkg/handlers/message_handler.goindex afe0127a..9da0ef1e 100644--- a/api/pkg/handlers/message_handler.go+++ b/api/pkg/handlers/message_handler.go@@ -265,7 +265,7 @@ func (h *MessageHandler) Index(c fiber.Ctx) error {messages, err := h.service.GetMessages(ctx, request.ToGetParams(h.userIDFomContext(c)))if err != nil {- msg := fmt.Sprintf("cannot get messgaes with params [%+#v]", request)+ msg := fmt.Sprintf("cannot get messages with params [%+#v]", request)ctxLogger.Error(stacktrace.Propagate(err, msg))return h.responseInternalServerError(c)}@@ -383,7 +383,7 @@ func (h *MessageHandler) PostReceive(c fiber.Ctx) error {message, err := h.service.ReceiveMessage(ctx, request.ToMessageReceiveParams(h.userIDFomContext(c), c.OriginalURL()))if err != nil {- msg := fmt.Sprintf("cannot receive message with paylod [%s]", c.Body())+ msg := fmt.Sprintf("cannot receive message with payload [%s]", c.Body())ctxLogger.Error(stacktrace.Propagate(err, msg))return h.responseInternalServerError(c)}diff --git a/api/pkg/requests/phone_update_request.go b/api/pkg/requests/phone_update_request.goindex 462d6428..96b2882e 100644--- a/api/pkg/requests/phone_update_request.go+++ b/api/pkg/requests/phone_update_request.go@@ -29,6 +29,9 @@ type PhoneUpsert struct {MissedCallAutoReply *string `json:"missed_call_auto_reply" example:"e.g. This phone cannot receive calls. Please send an SMS instead."`+ // UnarchiveThread moves an archived thread back to the inbox when a new message is received on this phone.+ UnarchiveThread bool `json:"unarchive_thread" example:"false"`+// SIM is the SIM slot of the phone in case the phone has more than 1 SIM slotSIM string `json:"sim" example:"SIM1"`@@ -75,6 +78,11 @@ func (input *PhoneUpsert) ToUpsertParams(user entities.AuthContext, source strinmaxSendAttempts = &input.MaxSendAttempts}+ var unarchiveThread *bool+ if _, exists := fields["unarchive_thread"]; exists {+ unarchiveThread = &input.UnarchiveThread+ }+var scheduleID *uuid.UUIDif _, exists := fields["message_send_schedule_id"]; exists {if parsed, err := uuid.Parse(strings.TrimSpace(input.MessageSendScheduleID)); err == nil {@@ -92,6 +100,7 @@ func (input *PhoneUpsert) ToUpsertParams(user entities.AuthContext, source strinFcmToken: fcmToken,UserID: user.ID,SIM: entities.SIM(input.SIM),+ UnarchiveThread: unarchiveThread,MessageSendScheduleID: scheduleID,}}diff --git a/api/pkg/services/message_service.go b/api/pkg/services/message_service.goindex 56766c98..f54feafd 100644--- a/api/pkg/services/message_service.go+++ b/api/pkg/services/message_service.go@@ -346,11 +346,13 @@ func (service *MessageService) ReceiveMessage(ctx context.Context, params *Messareturn nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))}+ owner := phonenumbers.Format(¶ms.Owner, phonenumbers.E164)+eventPayload := events.MessagePhoneReceivedPayload{MessageID: messageID,UserID: params.UserID,Encrypted: params.Encrypted,- Owner: phonenumbers.Format(¶ms.Owner, phonenumbers.E164),+ Owner: owner,Contact: params.Contact,Timestamp: params.Timestamp,Content: params.Content,diff --git a/api/pkg/services/message_thread_service.go b/api/pkg/services/message_thread_service.goindex d2027506..31287ebc 100644--- a/api/pkg/services/message_thread_service.go+++ b/api/pkg/services/message_thread_service.go@@ -21,6 +21,7 @@ type MessageThreadService struct {logger telemetry.Loggertracer telemetry.Tracerrepository repositories.MessageThreadRepository+ phoneRepository repositories.PhoneRepositoryeventDispatcher *EventDispatcher}@@ -29,6 +30,7 @@ func NewMessageThreadService(logger telemetry.Logger,tracer telemetry.Tracer,repository repositories.MessageThreadRepository,+ phoneRepository repositories.PhoneRepository,eventDispatcher *EventDispatcher,) (s *MessageThreadService) {return &MessageThreadService{@@ -36,6 +38,7 @@ func NewMessageThreadService(tracer: tracer,eventDispatcher: eventDispatcher,repository: repository,+ phoneRepository: phoneRepository,}}@@ -50,6 +53,14 @@ type MessageThreadUpdateParams struct {Timestamp time.Time}+// shouldCheckUnarchive reports whether a thread update is a new inbound message+// landing on an archived thread. Only in that case is the phone's+// UnarchiveThread setting consulted, so the phone is not loaded on the common+// path where the thread is not archived.+func (service *MessageThreadService) shouldCheckUnarchive(thread *entities.MessageThread, params MessageThreadUpdateParams) bool {+ return thread.IsArchived && params.Status == entities.MessageStatusReceived+}+// DeleteAllForUser deletes all entities.MessageThread for an entities.UserID.func (service *MessageThreadService) DeleteAllForUser(ctx context.Context, userID entities.UserID) error {ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)@@ -92,6 +103,16 @@ func (service *MessageThreadService) UpdateThread(ctx context.Context, params Mereturn nil}+ if service.shouldCheckUnarchive(thread, params) {+ phone, phoneErr := service.phoneRepository.Load(ctx, params.UserID, params.Owner)+ if phoneErr != nil {+ ctxLogger.Warn(stacktrace.Propagate(phoneErr, "cannot load phone [%s] for user [%s] to resolve UnarchiveThread; leaving thread [%s] archived", params.Owner, params.UserID, thread.ID))+ } else if phone.UnarchiveThread {+ thread.UpdateArchive(false)+ ctxLogger.Info(fmt.Sprintf("unarchiving thread [%s] after inbound message [%s]", thread.ID, params.MessageID))+ }+ }+if err = service.repository.Update(ctx, thread.Update(params.Timestamp, params.MessageID, params.Content, params.Status)); err != nil {msg := fmt.Sprintf("cannot update message thread with id [%s] after adding message [%s]", thread.ID, params.MessageID)return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))diff --git a/api/pkg/services/message_thread_service_test.go b/api/pkg/services/message_thread_service_test.gonew file mode 100644index 00000000..7e48ab43--- /dev/null+++ b/api/pkg/services/message_thread_service_test.go@@ -0,0 +1,23 @@+package services++import (+ "testing"++ "github.com/NdoleStudio/httpsms/pkg/entities"+ "github.com/stretchr/testify/assert"+)++func TestShouldCheckUnarchive(t *testing.T) {+ service := &MessageThreadService{}++ archived := &entities.MessageThread{IsArchived: true}+ notArchived := &entities.MessageThread{IsArchived: false}++ received := MessageThreadUpdateParams{Status: entities.MessageStatusReceived}+ sent := MessageThreadUpdateParams{Status: entities.MessageStatusSent}++ assert.True(t, service.shouldCheckUnarchive(archived, received), "archived + inbound -> consult phone setting")+ assert.False(t, service.shouldCheckUnarchive(archived, sent), "outbound status -> no check")+ assert.False(t, service.shouldCheckUnarchive(notArchived, received), "already unarchived -> no check")+ assert.False(t, service.shouldCheckUnarchive(notArchived, sent), "not archived + outbound -> no check")+}diff --git a/api/pkg/services/phone_service.go b/api/pkg/services/phone_service.goindex ae863d32..2e80abfa 100644--- a/api/pkg/services/phone_service.go+++ b/api/pkg/services/phone_service.go@@ -104,6 +104,7 @@ type PhoneUpsertParams struct {WebhookURL *stringMessageExpirationDuration *time.DurationMissedCallAutoReply *string+ UnarchiveThread *boolSIM entities.SIMMessageSendScheduleID *uuid.UUIDSource string@@ -312,6 +313,10 @@ func (service *PhoneService) update(phone *entities.Phone, params *PhoneUpsertPaphone.MissedCallAutoReply = params.MissedCallAutoReply}+ if params.UnarchiveThread != nil {+ phone.UnarchiveThread = *params.UnarchiveThread+ }+phone.SIM = params.SIMphone.MessageSendScheduleID = params.MessageSendScheduleIDdiff --git a/docs/superpowers/specs/2026-07-05-affiliates-landing-page-design.md b/docs/superpowers/specs/2026-07-05-affiliates-landing-page-design.mdnew file mode 100644index 00000000..31203352--- /dev/null+++ b/docs/superpowers/specs/2026-07-05-affiliates-landing-page-design.md@@ -0,0 +1,109 @@+# Affiliates Landing Page — Design++**Date:** 2026-07-05+**Component:** `web/` (Nuxt 4 SPA, Vuetify 4)++## Goal++Create a marketing landing page at `/affiliates` that convinces people to join the+httpSMS affiliate program, and replace the current external "Affiliates" footer link+(`https://httpsms.lemonsqueezy.com/affiliates`) with a `NuxtLink` to this new internal page.++All primary calls-to-action link to the LemonSqueezy affiliate signup:+`https://affiliates.lemonsqueezy.com/programs/httpsms` (opens in a new tab).++## Files++- **New:** `web/app/pages/affiliates/index.vue` — the landing page.+- **Edit:** `web/app/layouts/website.vue` — change the footer "Affiliates" link from the+ external `<a href="https://httpsms.lemonsqueezy.com/affiliates">` to+ `<NuxtLink to="/affiliates">`, keeping the existing `mdiShieldStar` warning icon and+ `text-white text-decoration-none footer-link` classes.++## Conventions to follow++- `<script setup lang="ts">` with `definePageMeta({ layout: 'website' })` and `useSeoMeta(...)`+ (mirrors `web/app/pages/privacy-policy/index.vue`).+- Vuetify 4 components (`VContainer`, `VRow`, `VCol`, `VCard`, `VBtn`, `VIcon`). No expansion+ panels. Use latest component props verified via context7 during implementation.+- Vuetify 4 typography classes only: `text-display-medium`, `text-headline-medium`,+ `text-headline-small`, `text-title-large`, `text-body-large` (no legacy `text-h*`).+- Hyperlinks get `text-decoration-none hover:text-decoration-underline` classes.+- Icons from `@mdi/js` imported in the script.+- External CTA links use `target="_blank"` and `rel="noopener"`.++## Page structure++The page uses the `website` layout (which provides the site nav + footer). Content is wrapped+in a `VContainer`; each section centered with `VCol cols="12" md="8" offset-md="2"` (or a wider+grid for the benefit cards).++Final copy below is written per the copywriting skill: benefit-first, specific, active voice,+customer language, one idea per section.++### 1. Hero+- Eyebrow text: `AFFILIATE PROGRAM`.+- H1 (`text-display-medium`): **Get paid to share httpSMS**+- Sub (`text-body-large`): *Earn up to $70 for every customer you refer — and keep earning every+ month they stay subscribed. If you already tell people to ditch expensive short codes, you might+ as well get paid for it.*+- Buttons: **Become an affiliate** (primary, → signup link) and **See how it works**+ (secondary/text, scrolls to the "How it works" section).++### 2. Why promote httpSMS (benefit cards)+Four `VCard`s in a responsive `VRow` (`cols=12 md=6` or `md=3`), each with an `@mdi/js` icon,+title, and one-line body:+1. **Up to $70 per sale** — Real commission on real subscriptions, not pennies per click.+2. **Recurring commission** — Get paid every month your referral stays, not just once.+3. **A product that sticks** — Developers wire httpSMS into daily workflows, so they rarely leave.+4. **Payouts on autopilot** — LemonSqueezy tracks every referral and pays you automatically.++### 3. How it works (3 numbered steps)+Section has an `id` so the hero "See how it works" button can scroll to it.+1. **Sign up free** — Join through LemonSqueezy in under a minute. No cost, no catch.+2. **Share your link** — Drop it in your blog posts, videos, docs, or DMs.+3. **Get paid** — We handle tracking and payouts. You collect on every sale.++### 4. FAQ (static two-column grid — no expansion panels)+Section heading (`text-headline-medium`): **Frequently asked questions**. Questions render+directly on the page (no accordions). Use a `VRow` of `VCol cols="12" md="6"` so it shows **two+columns on desktop and a single column on mobile**. Each item: bold question+(`text-title-large`) followed by the answer paragraph (`text-body-large`).++- **How much can I earn?** — Up to $70 per sale, plus recurring commission for as long as your+ referral stays subscribed.+- **How do I get paid?** — LemonSqueezy tracks your referrals and pays you automatically on their+ schedule.+- **Who can join?** — Anyone. Bloggers, YouTubers, developers, agencies — and it's free to join.+- **How do I track my referrals?** — Your LemonSqueezy dashboard shows clicks, referrals, and+ earnings in real time.+- **What converts best?** — Tutorials, honest reviews, and comparisons that show how httpSMS turns+ an Android phone into an SMS gateway.++### 5. Closing CTA banner+Full-width highlighted band:+- Heading: **Ready to start earning?**+- Sub: *Join free, grab your link, and turn your audience into recurring income.*+- Button: **Become an affiliate** → signup link.++## SEO meta++- `title`: "Affiliate Program — Earn up to $70 per Sale | httpSMS"+- `description`: "Join the httpSMS affiliate program and earn up to $70 for every customer you+ refer, with recurring commissions. Free to join, powered by LemonSqueezy."+- `ogTitle` / `ogDescription` mirror the above; `ogImage: https://httpsms.com/header.png`;+ `twitterCard: summary_large_image`.++## Out of scope++- No backend/API changes.+- No changes to the existing LemonSqueezy affiliate script in `nuxt.config.ts` /+ `public/integrations.js`.+- No new dependencies.++## Testing / verification++- `cd web && pnpm lint` passes for the changed files.+- Manual: `/affiliates` renders in the `website` layout; every CTA points to+ `https://affiliates.lemonsqueezy.com/programs/httpsms`; footer "Affiliates" link navigates to+ `/affiliates` internally.diff --git a/docs/superpowers/specs/2026-07-13-getting-started-page-design.md b/docs/superpowers/specs/2026-07-13-getting-started-page-design.mdnew file mode 100644index 00000000..15ca3de4--- /dev/null+++ b/docs/superpowers/specs/2026-07-13-getting-started-page-design.md@@ -0,0 +1,88 @@+# Getting Started page — Design++**Date:** 2026-07-13+**Status:** Approved++## Goal++Create the shortest possible, dummy-proof onboarding page that walks a+non-technical user through sending their first SMS with httpSMS:+**download → install → sign in → grant permissions → send a test message.**++The page must be self-explanatory and short. It reuses images from existing+blog posts and adds placeholders where the user will later drop GIFs/images.++## Route++- File: `web/app/pages/getting-started.vue`+- URL: `/getting-started`+- Layout: `website`++## Page structure (top → bottom)++1. **Hero**+ - `text-display-medium` (desktop) / `text-display-small` (mobile) title,+ e.g. "Send your first SMS in 5 minutes".+ - One-line subtitle.+ - Primary CTA `VBtn` (color primary): "⬇️ Download the Android app" linking+ to `https://github.com/NdoleStudio/httpsms/releases/latest/download/HttpSms.apk`.+ - Secondary CTA linking to `/login` (create account) when useful.+ - No gradient/glowing text (reserved for homepage hero).++2. **Numbered steps** (4 steps; each has a heading, 1–2 sentences, and an+ image or placeholder):+ - **Step 1 — Create your account & copy your API key.**+ Reuse `/img/blog/forward-incoming-sms-from-phone-to-webhook/settings.png`.+ Link to `/settings`.+ - **Step 2 — Download & install the app.**+ APK download link + placeholder for a GIF of installing the APK+ (`/img/getting-started/install-app.gif`). Info `VAlert` reminding to use+ international format e.g. `+18005550199`.+ - **Step 3 — Sign in on your phone.**+ Reuse `/img/blog/forward-incoming-sms-from-phone-to-webhook/android-app.png`;+ placeholder for a sign-in GIF (`/img/getting-started/sign-in.gif`).+ - **Step 4 — Send your first SMS.**+ From the web dashboard; link to `/threads`. Placeholder for a compose GIF+ (`/img/getting-started/send-sms.gif`).+ - After Step 3: an **info `VAlert`** linking to+ `/blog/grant-send-and-read-sms-permissions-on-android` for granting SMS+ permissions on Android 15+.++3. **"Automate it" section (bottom)**+ - Heading + links/cards to existing how-to blog posts:+ - Python — `/blog/send-sms-from-android-phone-with-python`+ - Excel — `/blog/how-to-send-sms-messages-from-excel`+ - CSV bulk — `/blog/send-bulk-sms-from-csv-file-with-no-code`+ - Zapier / Google Sheets — `/blog/send-sms-when-new-row-is-added-to-google-sheets-using-zapier`+ - Webhook forwarding — `/blog/forward-incoming-sms-from-phone-to-webhook`+ - End-to-end encryption — `/blog/end-to-end-encryption-to-sms-messages`++## Placeholders++For not-yet-available GIFs, render a styled bordered box (dashed border,+centered caption, e.g. "📹 GIF: Installing the APK — coming soon") that+references a real path under `/public/img/getting-started/`. This lets the+user drop assets in later without markup changes.++## Discoverability++- **Footer** (`web/app/layouts/website.vue`): add a "Getting Started" link to+ the **Resources** list.+- **`/threads` desktop empty state** (`web/app/pages/threads/index.vue`): add a+ "New here? Get started" `VBtn` below the Discord message (inside the+ `lgAndUp` empty-state block).++## Conventions to follow++- Vuetify 4 typography classes (`text-display-*`, `text-headline-large`,+ `text-title-large`, `text-body-large`).+- Every hyperlink: `text-decoration-none hover:text-decoration-underline`.+- `useSeoMeta` for title/description/OG tags (client-only SPA, `ssr: false`).+- Reuse `BlogSidebar`, `BackButton` patterns where appropriate.+- Warm, plain-language, beginner-friendly copy.++## Out of scope++- No "first login only" detection logic on `/threads`; the button shows in the+ existing desktop empty state.+- No new backend/API changes.diff --git a/tests/README.md b/tests/README.mdindex a37653e5..345d84d1 100644--- a/tests/README.md+++ b/tests/README.md@@ -53,6 +53,7 @@ The API's Firebase SDK is configured (via `FCM_ENDPOINT` env var) to redirect al- [x] **Send SMS E2E** — Full send lifecycle: API → FCM push → emulator responds with SENT/DELIVERED events → message reaches `delivered` status- [x] **Receive SMS E2E** — Phone submits received message to API → message is stored and retrievable via GET endpoint+- [x] **Unarchive Thread on Receive E2E** — Archived thread returns to the inbox on inbound message when the phone's `unarchive_thread` setting is enabled, and stays archived when disabled## Prerequisitesdiff --git a/tests/unarchive_thread_integration_test.go b/tests/unarchive_thread_integration_test.gonew file mode 100644index 00000000..35ee8bf5--- /dev/null+++ b/tests/unarchive_thread_integration_test.go@@ -0,0 +1,236 @@+package tests++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "testing"+ "time"++ httpsms "github.com/NdoleStudio/httpsms-go"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++type integrationThread struct {+ ID string `json:"id"`+ Contact string `json:"contact"`+ Owner string `json:"owner"`+ IsArchived bool `json:"is_archived"`+ LastMessageContent *string `json:"last_message_content"`+}++// setUnarchiveThread flips the per-phone unarchive_thread flag via a raw PUT+// (the httpsms-go client has no field for it).+func setUnarchiveThread(ctx context.Context, t *testing.T, phoneNumber string, enabled bool) {+ t.Helper()++ // sim is required by PUT /v1/phones validation, so it must be sent; setupPhone+ // always provisions the test phone on SIM1, so this preserves the existing slot.+ payload := map[string]interface{}{+ "phone_number": phoneNumber,+ "sim": "SIM1",+ "unarchive_thread": enabled,+ }+ body, err := json.Marshal(payload)+ require.NoError(t, err)++ req, err := http.NewRequestWithContext(ctx, http.MethodPut, apiBaseURL+"/v1/phones", bytes.NewReader(body))+ require.NoError(t, err)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("x-api-key", userAPIKey)++ resp, err := http.DefaultClient.Do(req)+ require.NoError(t, err)+ defer resp.Body.Close()++ respBody, err := io.ReadAll(resp.Body)+ require.NoError(t, err)+ require.Equal(t, http.StatusOK, resp.StatusCode, "set unarchive_thread failed: %s", string(respBody))+}++// receiveInbound submits an inbound message as the phone and returns the message ID.+// The phone-to-API-key association is applied asynchronously after setupPhone (via+// the phone_api_key event listener), so a freshly provisioned phone can briefly return+// 401 until the auth cache clears. Retry on that transient authorization failure.+func receiveInbound(ctx context.Context, t *testing.T, phoneAPIKey, from, to, content string, ts time.Time) string {+ t.Helper()++ payload := map[string]interface{}{+ "from": from,+ "to": to,+ "content": content,+ "sim": "SIM1",+ "timestamp": ts.UTC().Format(time.RFC3339),+ }+ body, err := json.Marshal(payload)+ require.NoError(t, err)++ var respBody []byte+ deadline := time.Now().Add(20 * time.Second)+ for {+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiBaseURL+"/v1/messages/receive", bytes.NewReader(body))+ require.NoError(t, err)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("x-api-key", phoneAPIKey)++ resp, err := http.DefaultClient.Do(req)+ require.NoError(t, err)+ respBody, err = io.ReadAll(resp.Body)+ resp.Body.Close()+ require.NoError(t, err)++ if resp.StatusCode == http.StatusOK {+ break+ }+ if resp.StatusCode == http.StatusUnauthorized && time.Now().Before(deadline) {+ time.Sleep(500 * time.Millisecond)+ continue+ }+ require.Equal(t, http.StatusOK, resp.StatusCode, "receive failed: %s", string(respBody))+ }++ var result httpsms.MessageResponse+ require.NoError(t, json.Unmarshal(respBody, &result))+ id := result.Data.ID.String()+ require.NotEmpty(t, id)+ return id+}++// fetchThreads returns threads for an owner filtered by archived state.+func fetchThreads(ctx context.Context, t *testing.T, owner string, archived bool) []integrationThread {+ t.Helper()++ reqURL := fmt.Sprintf("%s/v1/message-threads?owner=%s&is_archived=%t&limit=20", apiBaseURL, url.QueryEscape(owner), archived)+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)+ require.NoError(t, err)+ req.Header.Set("x-api-key", userAPIKey)++ resp, err := http.DefaultClient.Do(req)+ require.NoError(t, err)+ defer resp.Body.Close()++ respBody, err := io.ReadAll(resp.Body)+ require.NoError(t, err)+ require.Equal(t, http.StatusOK, resp.StatusCode, "fetch threads failed: %s", string(respBody))++ var result struct {+ Data []integrationThread `json:"data"`+ }+ require.NoError(t, json.Unmarshal(respBody, &result))+ return result.Data+}++func findThreadByContact(threads []integrationThread, contact string) *integrationThread {+ for i := range threads {+ if threads[i].Contact == contact {+ return &threads[i]+ }+ }+ return nil+}++// waitForThread polls the archived/unarchived thread list until a thread for the+// contact appears (optionally matching a last-message content), then returns it.+func waitForThread(ctx context.Context, t *testing.T, owner, contact string, archived bool, wantContent string, timeout time.Duration) *integrationThread {+ t.Helper()+ deadline := time.Now().Add(timeout)+ for time.Now().Before(deadline) {+ thread := findThreadByContact(fetchThreads(ctx, t, owner, archived), contact)+ if thread != nil && (wantContent == "" || (thread.LastMessageContent != nil && *thread.LastMessageContent == wantContent)) {+ return thread+ }+ time.Sleep(500 * time.Millisecond)+ }+ return nil+}++// archiveThread archives a thread by ID.+func archiveThread(ctx context.Context, t *testing.T, threadID string) {+ t.Helper()++ body, err := json.Marshal(map[string]interface{}{"is_archived": true})+ require.NoError(t, err)++ req, err := http.NewRequestWithContext(ctx, http.MethodPut, apiBaseURL+"/v1/message-threads/"+threadID, bytes.NewReader(body))+ require.NoError(t, err)+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("x-api-key", userAPIKey)++ resp, err := http.DefaultClient.Do(req)+ require.NoError(t, err)+ defer resp.Body.Close()++ respBody, err := io.ReadAll(resp.Body)+ require.NoError(t, err)+ require.Equal(t, http.StatusOK, resp.StatusCode, "archive thread failed: %s", string(respBody))+}++func TestUnarchiveThreadOnReceive_Enabled(t *testing.T) {+ ctx := context.Background()+ phone := setupPhone(ctx, t, 60)+ setUnarchiveThread(ctx, t, phone.PhoneNumber, true)++ contact := randomPhoneNumber()+ content1 := "first inbound " + randomEncryptionKey()+ content2 := "second inbound " + randomEncryptionKey()++ // First inbound message creates the thread.+ msgID1 := receiveInbound(ctx, t, phone.PhoneAPIKey, contact, phone.PhoneNumber, content1, time.Now().Add(-1*time.Minute))+ pollMessageStatus(ctx, t, msgID1, "received", 15*time.Second)++ thread := waitForThread(ctx, t, phone.PhoneNumber, contact, false, "", 15*time.Second)+ require.NotNil(t, thread, "thread not created for contact %s", contact)++ // Archive it.+ archiveThread(ctx, t, thread.ID)+ archived := waitForThread(ctx, t, phone.PhoneNumber, contact, true, "", 10*time.Second)+ require.NotNil(t, archived, "thread was not archived")++ // Second inbound message should unarchive it.+ msgID2 := receiveInbound(ctx, t, phone.PhoneAPIKey, contact, phone.PhoneNumber, content2, time.Now())+ pollMessageStatus(ctx, t, msgID2, "received", 15*time.Second)++ unarchived := waitForThread(ctx, t, phone.PhoneNumber, contact, false, content2, 20*time.Second)+ require.NotNil(t, unarchived, "thread was not unarchived after inbound message")+ assert.False(t, unarchived.IsArchived)+ require.NotNil(t, unarchived.LastMessageContent)+ assert.Equal(t, content2, *unarchived.LastMessageContent)+}++func TestUnarchiveThreadOnReceive_Disabled(t *testing.T) {+ ctx := context.Background()+ phone := setupPhone(ctx, t, 60) // unarchive_thread defaults to false; do not enable it++ contact := randomPhoneNumber()+ content1 := "first inbound " + randomEncryptionKey()+ content2 := "second inbound " + randomEncryptionKey()++ msgID1 := receiveInbound(ctx, t, phone.PhoneAPIKey, contact, phone.PhoneNumber, content1, time.Now().Add(-1*time.Minute))+ pollMessageStatus(ctx, t, msgID1, "received", 15*time.Second)++ thread := waitForThread(ctx, t, phone.PhoneNumber, contact, false, "", 15*time.Second)+ require.NotNil(t, thread, "thread not created for contact %s", contact)++ archiveThread(ctx, t, thread.ID)+ archived := waitForThread(ctx, t, phone.PhoneNumber, contact, true, "", 10*time.Second)+ require.NotNil(t, archived, "thread was not archived")++ // Second inbound message must NOT unarchive it. Sync on the archived thread's+ // last_message_content updating to content2 (proves the listener processed it),+ // then assert it is still archived.+ msgID2 := receiveInbound(ctx, t, phone.PhoneAPIKey, contact, phone.PhoneNumber, content2, time.Now())+ pollMessageStatus(ctx, t, msgID2, "received", 15*time.Second)++ stillArchived := waitForThread(ctx, t, phone.PhoneNumber, contact, true, content2, 20*time.Second)+ require.NotNil(t, stillArchived, "archived thread did not reflect the second inbound message")+ assert.True(t, stillArchived.IsArchived, "thread should remain archived when unarchive_thread is disabled")++ // And it must not have leaked into the unarchived list.+ assert.Nil(t, findThreadByContact(fetchThreads(ctx, t, phone.PhoneNumber, false), contact),+ "thread should not appear in the unarchived list")+}diff --git a/web/app/pages/settings/index.vue b/web/app/pages/settings/index.vueindex 17e35c7c..ea175253 100644--- a/web/app/pages/settings/index.vue+++ b/web/app/pages/settings/index.vue@@ -1688,6 +1688,15 @@ onMounted(async () => {placeholder="We are currently closed at the moment, please send us a text message from 09:00 to 17:00"hint="Here you can configure an automated SMS message which is sent to the caller when this phone has a missed call"/>+ <VSwitch+ v-model="activePhone.unarchive_thread"+ class="mt-4"+ color="primary"+ density="compact"+ label="Unarchive Threads Automatically"+ hint="When a new message is received on an archived conversation, change it back to the unarchived state"+ persistent-hint+ /></VCol></VRow></VContainer>diff --git a/web/app/stores/phones.ts b/web/app/stores/phones.tsindex b867e874..276fe292 100644--- a/web/app/stores/phones.ts+++ b/web/app/stores/phones.ts@@ -60,6 +60,7 @@ export const usePhonesStore = defineStore('phones', () => {max_send_attempts: parseInt(phone.max_send_attempts.toString()),messages_per_minute: parseInt(phone.messages_per_minute.toString()),message_send_schedule_id: phone.message_send_schedule_id ?? null,+ unarchive_thread: phone.unarchive_thread ?? false,},})notificationsStore.addNotification({diff --git a/web/shared/types/api.ts b/web/shared/types/api.tsindex df85420a..3f19b853 100644--- a/web/shared/types/api.ts+++ b/web/shared/types/api.ts@@ -61,7 +61,7 @@ export interface EntitiesBulkMessage {failed_count: number;/** @example 30 */pending_count: number;- /** @example "bulk-csv-a1B2c3D4e5" */+ /** @example "bulk-httpsms-file.csv" */request_id: string;/** @example 50 */scheduled_count: number;@@ -244,6 +244,11 @@ export interface EntitiesPhone {/** @example "+18005550199" */phone_number: string;sim: EntitiesSIM;+ /**+ * UnarchiveThread moves an archived message thread back to the inbox when a new message is received on this phone.+ * @example false+ */+ unarchive_thread: boolean;/** @example "2022-06-05T14:26:10.303278+03:00" */updated_at: string;/** @example "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" */@@ -525,6 +530,11 @@ export interface RequestsPhoneUpsert {* @example "SIM1"*/sim: string;+ /**+ * UnarchiveThread moves an archived thread back to the inbox when a new message is received on this phone.+ * @example false+ */+ unarchive_thread: boolean;}export interface RequestsUserNotificationUpdate {