Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
chore: remove superpoers docs
Acho Arnold Ewin42b1dd7aa244
diff --git a/docs/superpowers/plans/2026-05-26-nuxt4-vuetify4-migration.md b/docs/superpowers/plans/2026-05-26-nuxt4-vuetify4-migration.mddeleted file mode 100644index d5853283..00000000--- a/docs/superpowers/plans/2026-05-26-nuxt4-vuetify4-migration.md+++ /dev/null@@ -1,3300 +0,0 @@-# Nuxt 4 + Vuetify 4 Migration Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Migrate the httpSMS frontend from Nuxt 2 + Vue 2 + Vuetify 2 to Nuxt 4 + Vue 3 + Vuetify 4 with full TypeScript, Pinia state management, and `<script setup>` Composition API.--**Architecture:** Fresh Nuxt 4 project replacing the existing `web/` directory. All Vue 2 class-based components (`vue-property-decorator`) will be rewritten as `<script setup lang="ts">` using Composition API. Vuex store will be split into domain-specific Pinia stores. Firebase auth via `nuxt-vuefire`. The Vuetify MCP tools (`vuetify-mcp-get_component_api_by_version`, `vuetify-mcp-get_v4_breaking_changes`) MUST be called for every component/page migration to validate Vuetify 4 compatibility.--**Tech Stack:** Nuxt 4, Vue 3, Vuetify 4, Pinia, TypeScript, nuxt-vuefire, Firebase JS SDK, Pusher.js, Chart.js, libphonenumber-js-------## File Structure--```-web/-├── app/-│ ├── app.vue-│ ├── assets/-│ │ ├── img/ (copy from old assets/img/)-│ │ └── styles/-│ │ └── settings.scss-│ ├── components/-│ │ ├── BackButton.vue-│ │ ├── BlogAuthorBio.vue-│ │ ├── BlogInfo.vue-│ │ ├── CopyButton.vue-│ │ ├── FirebaseAuth.vue-│ │ ├── FixedHeader.vue-│ │ ├── LoadingButton.vue-│ │ ├── LoadingDashboard.vue-│ │ ├── MessageThread.vue-│ │ ├── MessageThreadHeader.vue-│ │ ├── NuxtLogo.vue-│ │ └── Toast.vue-│ ├── composables/-│ │ ├── useApi.ts-│ │ └── useFilters.ts-│ ├── layouts/-│ │ ├── default.vue-│ │ ├── error.vue-│ │ └── website.vue-│ ├── middleware/-│ │ ├── auth.ts-│ │ └── guest.ts-│ ├── pages/-│ │ ├── index.vue-│ │ ├── login.vue-│ │ ├── billing/index.vue-│ │ ├── blog/-│ │ │ ├── index.vue-│ │ │ ├── how-to-send-sms-messages-from-excel.vue-│ │ │ ├── grant-send-and-read-sms-permissions-on-android.vue-│ │ │ ├── forward-incoming-sms-from-phone-to-webhook.vue-│ │ │ ├── end-to-end-encryption-to-sms-messages.vue-│ │ │ ├── send-bulk-sms-from-csv-file-with-no-code.vue-│ │ │ ├── send-sms-from-android-phone-with-python.vue-│ │ │ └── send-sms-when-new-row-is-added-to-google-sheets-using-zapier.vue-│ │ ├── bulk-messages/index.vue-│ │ ├── heartbeats/[id].vue-│ │ ├── messages/index.vue-│ │ ├── phone-api-keys/index.vue-│ │ ├── privacy-policy/index.vue-│ │ ├── search-messages/index.vue-│ │ ├── settings/index.vue-│ │ ├── terms-and-conditions/index.vue-│ │ └── threads/-│ │ ├── index.vue-│ │ └── [id]/index.vue-│ ├── plugins/-│ │ ├── vuetify.ts-│ │ ├── chart.client.ts-│ │ └── vue-glow.client.ts-│ ├── stores/-│ │ ├── app.ts-│ │ ├── auth.ts-│ │ ├── billing.ts-│ │ ├── messages.ts-│ │ ├── notifications.ts-│ │ ├── phones.ts-│ │ └── threads.ts-│ └── utils/-│ ├── bag.ts-│ ├── capitalize.ts-│ ├── errors.ts-│ └── filters.ts-├── shared/-│ └── types/-│ ├── api.ts-│ ├── billing.ts-│ ├── heartbeat.ts-│ ├── message-thread.ts-│ ├── message.ts-│ └── user.ts-├── public/ (copy from old static/)-├── nuxt.config.ts-├── package.json-├── tsconfig.json-└── .env-```-------## Task 1: Backup Old Code & Scaffold Nuxt 4 Project--**Files:**-- Delete (after backup): `web/` (entire old structure)-- Create: `web/package.json`, `web/nuxt.config.ts`, `web/tsconfig.json`, `web/app/app.vue`--- [ ] **Step 1: Create a backup branch of the current web/ code**--```bash-cd C:\Users\Arnold\Work\NdoleStudio\httpsms.com-git stash-git checkout main-git checkout -b backup/web-nuxt2-vuetify2-git checkout feat/migrate-nuxt4-vuetify4-git stash pop-```--- [ ] **Step 2: Remove old web/ contents (except .env files and static assets)**--```bash-cd C:\Users\Arnold\Work\NdoleStudio\httpsms.com-# Remove old source files but keep .env and static for reference-Remove-Item -Recurse -Force web/node_modules, web/.nuxt, web/dist, web/coverage-# We'll scaffold fresh and copy what we need-```--- [ ] **Step 3: Initialize fresh Nuxt 4 project**--```bash-cd C:\Users\Arnold\Work\NdoleStudio\httpsms.com-# Remove old web directory entirely-Remove-Item -Recurse -Force web-# Create fresh Nuxt 4 project-npx nuxi@latest init web --template v4 --package-manager pnpm-cd web-```--- [ ] **Step 4: Install all dependencies**--```bash-cd C:\Users\Arnold\Work\NdoleStudio\httpsms.com\web-pnpm add vuetify@latest @mdi/js sass pusher-js firebase chart.js chartjs-adapter-moment vue-chartjs date-fns libphonenumber-js qrcode moment-pnpm add -D @types/qrcode vuetify-nuxt-module-pnpm add nuxt-vuefire-```--- [ ] **Step 5: Commit scaffold**--```bash-cd C:\Users\Arnold\Work\NdoleStudio\httpsms.com-git add -A-git commit -m "feat(web): scaffold fresh Nuxt 4 project for migration"-```-------## Task 2: Configure nuxt.config.ts--**Files:**-- Create: `web/nuxt.config.ts`--- [ ] **Step 1: Write nuxt.config.ts with all modules and settings**--```typescript-// web/nuxt.config.ts-export default defineNuxtConfig({- compatibilityDate: '2025-01-01',-- ssr: true,-- modules: [- 'vuetify-nuxt-module',- 'nuxt-vuefire',- '@pinia/nuxt',- ],-- css: [- 'vuetify/styles',- ],-- build: {- transpile: ['vuetify', 'chart.js', 'vue-chartjs'],- },-- vite: {- define: {- 'process.env.DEBUG': false,- },- css: {- preprocessorOptions: {- scss: {- api: 'modern-compiler',- },- },- },- },-- vuetify: {- moduleOptions: {- styles: { configFile: 'app/assets/styles/settings.scss' },- },- vuetifyOptions: {- theme: {- defaultTheme: 'dark',- },- icons: {- defaultSet: 'mdi-svg',- },- display: {- thresholds: {- md: 960,- lg: 1280,- xl: 1920,- xxl: 2560,- },- },- },- },-- vuefire: {- config: {- apiKey: process.env.FIREBASE_API_KEY,- authDomain: process.env.FIREBASE_AUTH_DOMAIN,- projectId: process.env.FIREBASE_PROJECT_ID,- storageBucket: process.env.FIREBASE_STORAGE_BUCKET,- messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,- appId: process.env.FIREBASE_APP_ID,- measurementId: process.env.FIREBASE_MEASUREMENT_ID,- },- auth: {- enabled: true,- },- },-- runtimeConfig: {- public: {- apiBaseUrl: process.env.API_BASE_URL || 'http://localhost:8000',- appUrl: process.env.APP_URL || 'https://httpsms.com',- appName: process.env.APP_NAME || 'HTTP SMS',- appGithubUrl: process.env.APP_GITHUB_URL || 'https://github.com/NdoleStudio/httpsms',- appDocumentationUrl: process.env.APP_DOCUMENTATION_URL || 'https://docs.httpsms.com',- appDownloadUrl: process.env.APP_DOWNLOAD_URL || 'https://apk.httpsms.com/HttpSms.apk',- appEnv: process.env.APP_ENV || 'production',- checkoutUrl: process.env.CHECKOUT_URL || '',- enterpriseCheckoutUrl: process.env.ENTERPRISE_CHECKOUT_URL || '',- cloudflareTurnstileSiteKey: process.env.CLOUDFLARE_TURNSTILE_SITE_KEY || '',- pusherKey: process.env.PUSHER_KEY || '',- pusherCluster: process.env.PUSHER_CLUSTER || '',- },- },-- nitro: {- prerender: {- routes: ['/'],- },- },-- routeRules: {- '/messages': { ssr: false },- '/settings': { ssr: false },- '/threads/**': { ssr: false },- '/billing': { ssr: false },- '/bulk-messages': { ssr: false },- },-- app: {- head: {- titleTemplate: '%s',- title: 'Convert your android phone into an SMS gateway - httpSMS',- htmlAttrs: { lang: 'en' },- script: [- { src: '/integrations.js', async: true, defer: true },- { src: 'https://lmsqueezy.com/affiliate.js', async: true, defer: true },- { src: 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit' },- ],- meta: [- { charset: 'utf-8' },- { name: 'viewport', content: 'width=device-width, initial-scale=1' },- { name: 'description', content: 'Use your android phone to send and receive SMS messages using a simple HTTP API.' },- { name: 'format-detection', content: 'telephone=no' },- { name: 'twitter:site', content: '@NdoleStudio' },- { name: 'twitter:card', content: 'summary_large_image' },- { property: 'og:title', content: 'Convert your android phone into an SMS gateway - httpSMS' },- { property: 'og:description', content: 'Use your android phone to send and receive SMS messages using a simple HTTP API.' },- { property: 'og:image', content: 'https://httpsms.com/header.png' },- ],- link: [{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }],- },- },-})-```--- [ ] **Step 2: Create Vuetify SASS settings file**--```scss-// web/app/assets/styles/settings.scss-@use 'vuetify/settings' with (- $grid-breakpoints: (- 'md': 960px,- 'lg': 1280px,- 'xl': 1920px,- 'xxl': 2560px,- ),-);-```--- [ ] **Step 3: Create app.vue**--```vue-<!-- web/app/app.vue -->-<template>- <NuxtLayout>- <NuxtPage />- </NuxtLayout>-</template>-```--- [ ] **Step 4: Copy .env file**--```bash-# Copy from old .env (reference the backed-up content)-cd C:\Users\Arnold\Work\NdoleStudio\httpsms.com\web-```--Create `web/.env` with the same environment variables as the original.--- [ ] **Step 5: Commit configuration**--```bash-git add -A-git commit -m "feat(web): configure nuxt.config.ts with Vuetify 4, VueFire, Pinia"-```-------## Task 3: Port Utility Files--**Files:**-- Create: `web/app/utils/bag.ts`-- Create: `web/app/utils/capitalize.ts`-- Create: `web/app/utils/errors.ts`-- Create: `web/app/utils/filters.ts`--- [ ] **Step 1: Create bag.ts**--```typescript-// web/app/utils/bag.ts-export default class Bag<T> {- private items = new Map<string, Array<T>>()-- serialize(): Record<string, Array<T>> {- const result: Record<string, Array<T>> = {}- this.items.forEach((value: T[], key) => {- result[key] = value- })- return result- }-- static fromObject<T>(items: Record<string, Array<T>>): Bag<T> {- const result = new Bag<T>()- Object.keys(items).forEach((key) => {- result.addMany(key, items[key])- })- return result- }-- add(key: string, value: T): this {- let messages: Array<T> | undefined = this.items.get(key)- if (messages === undefined) {- messages = []- }-- if (!messages.includes(value)) {- messages.push(value)- }-- this.items.set(key, messages)- return this- }-- addMany(key: string, values: Array<T>): this {- values.forEach((value: T) => {- this.add(key, value)- })- return this- }-- has(key: string): boolean {- return this.items.has(key)- }-- first(key: string): T | undefined {- if (this.has(key)) {- return this.get(key)[0] ?? undefined- }- return undefined- }-- get(key: string): Array<T> {- const result = this.items.get(key)- if (result === undefined) {- return []- }- return result- }-- size(): number {- return this.items.size- }-}-```--- [ ] **Step 2: Create capitalize.ts**--```typescript-// web/app/utils/capitalize.ts-export function capitalize(value: string | null): string {- if (!value) {- return ''- }- return value.charAt(0).toUpperCase() + value.slice(1)-}-```--- [ ] **Step 3: Create errors.ts**--```typescript-// web/app/utils/errors.ts-import Bag from '~/utils/bag'-import { capitalize } from '~/utils/capitalize'--export class ErrorMessages extends Bag<string> {}--const sanitize = (key: string, values: Array<string>): Array<string> => {- return values.map((value: string) => {- return capitalize(- value- .split(key)- .join(key.replace('_', ' '))- .split('_')- .join(' ')- .split('-')- .join(' ')- .split(' char')- .join(' character')- .split(' field ')- .join(' '),- )- })-}--interface AxiosLikeError {- response?: {- data?: { data?: Record<string, string[]> }- status?: number- }-}--export const getErrorMessages = (error: AxiosLikeError): ErrorMessages => {- const errors = new ErrorMessages()- if (- error === null ||- typeof error.response?.data?.data !== 'object' ||- error.response?.data?.data === null ||- error.response?.status !== 422- ) {- return errors- }-- Object.keys(error.response.data.data).forEach((key: string) => {- errors.addMany(key, sanitize(key, error.response!.data!.data![key]))- })-- return errors-}-```--- [ ] **Step 4: Create filters.ts**--```typescript-// web/app/utils/filters.ts-import { intervalToDuration, formatDuration } from 'date-fns'-import { parsePhoneNumber, isValidPhoneNumber } from 'libphonenumber-js'--export function formatPhoneNumber(value: string): string {- if (!isValidPhoneNumber(value)) {- return value- }- const phoneNumber = parsePhoneNumber(value)- if (phoneNumber) {- return phoneNumber.formatInternational()- }- return value-}--export function phoneCountry(value: string): string {- const phoneNumber = parsePhoneNumber(value)- if (phoneNumber && phoneNumber.country) {- const regionNames = new Intl.DisplayNames(undefined, { type: 'region' })- return regionNames.of(phoneNumber.country) ?? 'Earth'- }- return 'Earth'-}--export function formatTimestamp(value: string): string {- return new Date(value).toLocaleString()-}--export function formatMoney(value: string | number): string {- return new Intl.NumberFormat('en-US', {- style: 'currency',- currency: 'USD',- }).format(typeof value === 'string' ? parseInt(value) : value)-}--export function formatDecimal(value: string | number): string {- return new Intl.NumberFormat('en-US', {- style: 'decimal',- }).format(typeof value === 'string' ? parseInt(value) : value)-}--export function formatBillingPeriod(value: string): string {- return new Date(value).toLocaleDateString('en-US', {- year: 'numeric',- month: 'long',- })-}--export function humanizeTime(value: string): string {- const durations = intervalToDuration({- start: new Date(),- end: new Date(value),- })- return formatDuration(durations)-}-```--- [ ] **Step 5: Commit utilities**--```bash-git add -A-git commit -m "feat(web): port utility files (bag, capitalize, errors, filters)"-```-------## Task 4: Port API Models/Types--**Files:**-- Create: `web/shared/types/message-thread.ts`-- Create: `web/shared/types/message.ts`-- Create: `web/shared/types/heartbeat.ts`-- Create: `web/shared/types/billing.ts`-- Create: `web/shared/types/user.ts`-- Copy: `web/shared/types/api.ts` (from old `web/models/api.ts`)--- [ ] **Step 1: Create shared types directory and copy model files**--Copy the existing model files from the old `web/models/` directory (available on the backup branch) into `web/shared/types/`. These files are pure TypeScript interfaces and need no changes:--```typescript-// web/shared/types/message-thread.ts-export interface MessageThread {- color: string- contact: string- created_at: string- id: string- last_message_content: string- last_message_id: string- is_archived: boolean- order_timestamp: string- owner: string- updated_at: string-}-```--```typescript-// web/shared/types/message.ts-export interface Message {- contact: string- content: string- attachments: Array<string> | null- created_at: string- failure_reason: string- id: string- last_attempted_at: string | null- order_timestamp: string- owner: string- received_at: string | null- request_received_at: string | null- send_time: number | null- sent_at: string- status: string- type: string- updated_at: string-}--export interface SearchMessagesRequest {- owners: string[]- types: string[]- statuses: string[]- query: string- sort_by: string- token?: string- sort_descending: boolean- skip: number- limit: number-}-```--```typescript-// web/shared/types/heartbeat.ts-export interface Heartbeat {- id: string- owner: string- phone_number: string- charging: boolean- timestamp: string-}-```--```typescript-// web/shared/types/billing.ts-export interface BillingUsage {- id: string- user_id: string- period_start: string- period_end: string- sent_messages: number- received_messages: number-}-```--```typescript-// web/shared/types/user.ts-export interface User {- id: string- email: string- api_key: string- active_phone_id: string | null- timezone: string- subscription_id: string | null- subscription_name: string | null- subscription_status: string | null- notification_message_status_enabled: boolean- notification_webhooks_enabled: boolean-}-```--- [ ] **Step 2: Copy the auto-generated api.ts**--Copy `web/models/api.ts` from the backup branch to `web/shared/types/api.ts`. This file is auto-generated from Swagger and needs no modification.--- [ ] **Step 3: Commit types**--```bash-git add -A-git commit -m "feat(web): port API model types to shared/types/"-```-------## Task 5: Create useApi Composable--**Files:**-- Create: `web/app/composables/useApi.ts`--- [ ] **Step 1: Create the API composable**--```typescript-// web/app/composables/useApi.ts-import type { UseFetchOptions } from 'nuxt/app'--let authToken: string | null = null-let apiKey: string | null = null--export function setAuthHeader(token: string | null) {- authToken = token-}--export function setApiKey(key: string | null) {- apiKey = key-}--export function useApi() {- const config = useRuntimeConfig()- const baseURL = config.public.apiBaseUrl as string-- const apiFetch = $fetch.create({- baseURL,- headers: {- 'X-Client-Version': 'web',- },- onRequest({ options }) {- const headers = (options.headers ||= {}) as Record<string, string>- if (authToken) {- headers.Authorization = `Bearer ${authToken}`- }- if (apiKey) {- headers['x-api-key'] = apiKey- }- },- })-- return { apiFetch, setAuthHeader, setApiKey }-}-```--- [ ] **Step 2: Create useFilters composable**--```typescript-// web/app/composables/useFilters.ts-import {- formatPhoneNumber,- phoneCountry,- formatTimestamp,- formatMoney,- formatDecimal,- formatBillingPeriod,- humanizeTime,-} from '~/utils/filters'-import { capitalize } from '~/utils/capitalize'--export function useFilters() {- return {- formatPhoneNumber,- phoneCountry,- formatTimestamp,- formatMoney,- formatDecimal,- formatBillingPeriod,- humanizeTime,- capitalize,- }-}-```--- [ ] **Step 3: Commit composables**--```bash-git add -A-git commit -m "feat(web): create useApi and useFilters composables"-```-------## Task 6: Create Pinia Stores — Notifications & App--**Files:**-- Create: `web/app/stores/notifications.ts`-- Create: `web/app/stores/app.ts`--- [ ] **Step 1: Create notifications store**--```typescript-// web/app/stores/notifications.ts-import { defineStore } from 'pinia'--export type NotificationType = 'error' | 'success' | 'info'--export interface Notification {- message: string- timeout: number- active: boolean- type: NotificationType-}--export interface NotificationRequest {- message: string- type: NotificationType-}--const DEFAULT_TIMEOUT = 3000--export const useNotificationsStore = defineStore('notifications', () => {- const notification = ref<Notification>({- active: false,- message: '',- type: 'success',- timeout: DEFAULT_TIMEOUT,- })-- function addNotification(request: NotificationRequest) {- notification.value = {- active: true,- message: request.message,- type: request.type,- timeout: Math.floor(Math.random() * 100) + DEFAULT_TIMEOUT,- }- }-- function disableNotification() {- notification.value.active = false- }-- return {- notification,- addNotification,- disableNotification,- }-})-```--- [ ] **Step 2: Create app store**--```typescript-// web/app/stores/app.ts-import { defineStore } from 'pinia'--export interface AppData {- url: string- name: string- env: string- appDownloadUrl: string- documentationUrl: string- githubUrl: string-}--export const useAppStore = defineStore('app', () => {- const config = useRuntimeConfig()- const polling = ref(false)-- const appData = computed<AppData>(() => {- let url = (config.public.appUrl as string) || ''- if (url.length > 0 && url[url.length - 1] === '/') {- url = url.substring(0, url.length - 1)- }- return {- url,- env: config.public.appEnv as string,- appDownloadUrl: config.public.appDownloadUrl as string,- documentationUrl: config.public.appDocumentationUrl as string,- githubUrl: config.public.appGithubUrl as string,- name: config.public.appName as string,- }- })-- const isLocal = computed(() => config.public.appEnv === 'local')-- function setPolling(value: boolean) {- polling.value = value- }-- return {- polling,- appData,- isLocal,- setPolling,- }-})-```--- [ ] **Step 3: Commit stores**--```bash-git add -A-git commit -m "feat(web): create notifications and app Pinia stores"-```-------## Task 7: Create Pinia Stores — Auth--**Files:**-- Create: `web/app/stores/auth.ts`--- [ ] **Step 1: Create auth store**--```typescript-// web/app/stores/auth.ts-import { defineStore } from 'pinia'-import { useCurrentUser } from 'vuefire'-import { setAuthHeader, setApiKey } from '~/composables/useApi'-import type { User } from '~~/shared/types/user'--export interface AuthUser {- email: string | null- displayName: string | null- id: string-}--export const useAuthStore = defineStore('auth', () => {- const authStateChanged = ref(false)- const authUser = ref<AuthUser | null>(null)- const user = ref<User | null>(null)- const { apiFetch } = useApi()-- async function setAuthUserAction(newUser: AuthUser | null | undefined) {- const userChanged = newUser?.id !== authUser.value?.id- authUser.value = newUser ?? null- authStateChanged.value = true-- if (userChanged && newUser !== null) {- await Promise.all([loadUser(), loadPhones()])- }- }-- async function onAuthStateChanged(firebaseUser: any) {- if (firebaseUser == null) {- authUser.value = null- user.value = null- authStateChanged.value = true- setApiKey('')- return- }- setAuthHeader(await firebaseUser.getIdToken())- const { uid, email, displayName } = firebaseUser- authUser.value = { id: uid, email, displayName }- authStateChanged.value = true- }-- async function onIdTokenChanged(firebaseUser: any) {- if (firebaseUser == null) {- setApiKey('')- return- }- setAuthHeader(await firebaseUser.getIdToken())- }-- async function loadUser() {- const response = await apiFetch<{ data: User }>('/v1/users/me')- user.value = response.data- }-- async function updateUser(payload: { owner?: string; timezone?: string }) {- const phonesStore = usePhonesStore()- if (payload.owner) {- phonesStore.setOwner(payload.owner)- }-- const activePhone = phonesStore.activePhone- if (!activePhone) return-- const response = await apiFetch<{ data: User }>('/v1/users/me', {- method: 'PUT',- body: {- active_phone_id: activePhone.id,- timezone: payload.timezone ?? user.value?.timezone,- },- })-- setApiKey(response.data.api_key)- user.value = response.data- }-- async function deleteUserAccount(): Promise<string> {- const response = await apiFetch<{ message: string }>('/v1/users/me', {- method: 'DELETE',- })- return response.message- }-- async function rotateApiKey(userId: string): Promise<User> {- const response = await apiFetch<{ data: User }>(`/v1/users/${userId}/api-keys`, {- method: 'DELETE',- })- user.value = response.data- setApiKey(response.data.api_key)- return response.data- }-- function resetState() {- user.value = null- authUser.value = null- authStateChanged.value = true- setApiKey('')- }-- // Import usePhonesStore lazily to avoid circular deps- function loadPhones() {- const phonesStore = usePhonesStore()- return phonesStore.loadPhones(false)- }-- return {- authStateChanged,- authUser,- user,- setAuthUserAction,- onAuthStateChanged,- onIdTokenChanged,- loadUser,- updateUser,- deleteUserAccount,- rotateApiKey,- resetState,- }-})--// Lazy import to avoid circular dependency-function usePhonesStore() {- return (await import('~/stores/phones')).usePhonesStore()-}-```--Note: The circular dependency between auth and phones will be resolved by using dynamic imports. The actual implementation should use `const { usePhonesStore } = await import('~/stores/phones')` or restructure to avoid the cycle entirely.--- [ ] **Step 2: Commit**--```bash-git add -A-git commit -m "feat(web): create auth Pinia store"-```-------## Task 8: Create Pinia Stores — Phones--**Files:**-- Create: `web/app/stores/phones.ts`--- [ ] **Step 1: Create phones store**--```typescript-// web/app/stores/phones.ts-import { defineStore } from 'pinia'-import type { EntitiesPhone } from '~~/shared/types/api'-import type { Heartbeat } from '~~/shared/types/heartbeat'--export const usePhonesStore = defineStore('phones', () => {- const phones = ref<EntitiesPhone[]>([])- const owner = ref<string | null>(null)- const heartbeat = ref<Heartbeat | null>(null)- const { apiFetch } = useApi()- const notificationsStore = useNotificationsStore()-- const activePhone = computed<EntitiesPhone | null>(() => {- return phones.value.find((x) => x.phone_number === owner.value) ?? null- })-- function setOwner(value: string) {- owner.value = value- }-- async function loadPhones(force: boolean = false) {- if (phones.value.length > 0 && !force) return-- const response = await apiFetch<{ data: EntitiesPhone[] }>('/v1/phones', {- params: { limit: 100 },- })- phones.value = response.data-- const authStore = useAuthStore()- if (authStore.user?.active_phone_id) {- const phone = response.data.find((x) => x.id === authStore.user?.active_phone_id)- if (phone) {- owner.value = phone.phone_number- }- }-- if (!owner.value && phones.value.length > 0) {- owner.value = phones.value[0].phone_number- }- }-- async function deletePhone(phoneID: string) {- await apiFetch(`/v1/phones/${phoneID}`, { method: 'DELETE' })- await loadPhones(true)- }-- async function updatePhone(phone: EntitiesPhone) {- try {- const response = await apiFetch<{ message: string }>('/v1/phones', {- method: 'PUT',- body: {- fcm_token: phone.fcm_token,- sim: phone.sim,- phone_number: phone.phone_number,- message_expiration_seconds: parseInt(phone.message_expiration_seconds.toString()),- missed_call_auto_reply: phone.missed_call_auto_reply,- 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,- },- })- notificationsStore.addNotification({ message: response.message, type: 'success' })- await loadPhones(true)- } catch (error: any) {- notificationsStore.addNotification({- message: error?.data?.message ?? 'Error while updating phone',- type: 'error',- })- }- }-- async function getHeartbeat(limit = 1): Promise<Heartbeat[]> {- const response = await apiFetch<{ data: Heartbeat[] }>('/v1/heartbeats', {- params: { limit, owner: owner.value },- })- if (response.data.length > 0) {- heartbeat.value = response.data[0]- } else {- heartbeat.value = null- }- return response.data- }-- function resetState() {- phones.value = []- owner.value = null- heartbeat.value = null- }-- return {- phones,- owner,- heartbeat,- activePhone,- setOwner,- loadPhones,- deletePhone,- updatePhone,- getHeartbeat,- resetState,- }-})-```--- [ ] **Step 2: Commit**--```bash-git add -A-git commit -m "feat(web): create phones Pinia store"-```-------## Task 9: Create Pinia Stores — Threads & Messages--**Files:**-- Create: `web/app/stores/threads.ts`-- Create: `web/app/stores/messages.ts`--- [ ] **Step 1: Create threads store**--```typescript-// web/app/stores/threads.ts-import { defineStore } from 'pinia'-import type { MessageThread } from '~~/shared/types/message-thread'-import type { Message } from '~~/shared/types/message'--export const useThreadsStore = defineStore('threads', () => {- const threads = ref<MessageThread[]>([])- const threadId = ref<string | null>(null)- const loadingThreads = ref(true)- const archivedThreads = ref(false)- const { apiFetch } = useApi()- const notificationsStore = useNotificationsStore()-- const currentThread = computed<MessageThread | null>(() => {- return threads.value.find((x) => x.id === threadId.value) ?? null- })-- const hasThread = computed(() => threadId.value != null && !loadingThreads.value)-- function hasThreadId(id: string): boolean {- return threads.value.find((x) => x.id === id) !== undefined- }-- async function loadThreads() {- const phonesStore = usePhonesStore()- if (phonesStore.owner === null && phonesStore.phones.length === 0) {- loadingThreads.value = false- return- }-- const response = await apiFetch<{ data: MessageThread[] }>('/v1/message-threads', {- params: {- owner: phonesStore.owner ?? phonesStore.phones[0]?.phone_number,- limit: 100,- is_archived: archivedThreads.value,- },- })-- phonesStore.getHeartbeat().catch(console.error)- threads.value = [...response.data]- loadingThreads.value = false- }-- async function loadThreadMessages(id: string | null): Promise<Message[]> {- threadId.value = id- const thread = currentThread.value- if (!thread) throw new Error(`Cannot find thread with id ${id}`)-- const response = await apiFetch<{ data: Message[] }>('/v1/messages', {- params: {- contact: thread.contact,- owner: thread.owner,- limit: 50,- },- })- return response.data- }-- function setThreadId(id: string | null) {- threadId.value = id- }-- function toggleArchive() {- archivedThreads.value = !archivedThreads.value- }-- async function updateThread(payload: { threadId: string; isArchived: boolean }) {- await apiFetch(`/v1/message-threads/${payload.threadId}`, {- method: 'PUT',- body: { is_archived: payload.isArchived },- })- archivedThreads.value = payload.isArchived- await loadThreads()- }-- async function deleteThread(id: string) {- await apiFetch(`/v1/message-threads/${id}`, { method: 'DELETE' })- threadId.value = null- notificationsStore.addNotification({- message: 'The message thread has been deleted successfully',- type: 'success',- })- }-- function resetState() {- threads.value = []- threadId.value = null- archivedThreads.value = false- loadingThreads.value = true- }-- return {- threads,- threadId,- loadingThreads,- archivedThreads,- currentThread,- hasThread,- hasThreadId,- loadThreads,- loadThreadMessages,- setThreadId,- toggleArchive,- updateThread,- deleteThread,- resetState,- }-})-```--- [ ] **Step 2: Create messages store**--```typescript-// web/app/stores/messages.ts-import { defineStore } from 'pinia'-import type { EntitiesMessage } from '~~/shared/types/api'-import type { SearchMessagesRequest } from '~~/shared/types/message'--export type SIM = 'SIM1' | 'SIM2' | 'DEFAULT'--export interface SendMessageRequest {- from: string- to: string- content: string- sim: SIM- request_id?: string-}--export const useMessagesStore = defineStore('messages', () => {- const { apiFetch } = useApi()- const notificationsStore = useNotificationsStore()-- async function sendMessage(request: SendMessageRequest) {- try {- const response = await apiFetch<{ message: string }>('/v1/messages/send', {- method: 'POST',- body: request,- })- notificationsStore.addNotification({ message: response.message, type: 'success' })- } catch (e: any) {- notificationsStore.addNotification({- message: e?.data?.message ?? 'Error while sending message',- type: 'error',- })- }- const threadsStore = useThreadsStore()- await threadsStore.loadThreads()- }-- async function deleteMessage(messageId: string) {- await apiFetch(`/v1/messages/${messageId}`, { method: 'DELETE' })- notificationsStore.addNotification({- message: 'The message has been deleted successfully',- type: 'success',- })- }-- async function searchMessages(payload: SearchMessagesRequest): Promise<EntitiesMessage[]> {- const token = payload.token- const params = { ...payload }- delete params.token-- const response = await apiFetch<{ data: EntitiesMessage[] }>('/v1/messages/search', {- params,- headers: token ? { token } : undefined,- })- return response.data- }-- async function sendBulkMessages(document: File): Promise<void> {- const formData = new FormData()- formData.append('document', document)- const response = await apiFetch<{ message?: string }>('/v1/bulk-messages', {- method: 'POST',- body: formData,- })- notificationsStore.addNotification({- message: response.message ?? 'Bulk messages sent successfully',- type: 'success',- })- }-- async function fetchBulkMessageOrders(): Promise<any[]> {- const response = await apiFetch<{ data: any[] }>('/v1/bulk-messages')- return response.data ?? []- }-- return {- sendMessage,- deleteMessage,- searchMessages,- sendBulkMessages,- fetchBulkMessageOrders,- }-})-```--- [ ] **Step 3: Commit**--```bash-git add -A-git commit -m "feat(web): create threads and messages Pinia stores"-```-------## Task 10: Create Pinia Store — Billing--**Files:**-- Create: `web/app/stores/billing.ts`--- [ ] **Step 1: Create billing store**--```typescript-// web/app/stores/billing.ts-import { defineStore } from 'pinia'-import type { BillingUsage } from '~~/shared/types/billing'-import type {- EntitiesWebhook,- EntitiesDiscord,- EntitiesMessageSendSchedule,- EntitiesPhoneAPIKey,- RequestsWebhookStore,- RequestsWebhookUpdate,- RequestsDiscordStore,- RequestsDiscordUpdate,- RequestsMessageSendScheduleStore,- RequestsUserNotificationUpdate,- RequestsUserPaymentInvoice,- ResponsesUserSubscriptionPaymentsResponse,-} from '~~/shared/types/api'--export const useBillingStore = defineStore('billing', () => {- const billingUsage = ref<BillingUsage | null>(null)- const billingUsageHistory = ref<BillingUsage[]>([])- const { apiFetch } = useApi()- const notificationsStore = useNotificationsStore()-- async function loadBillingUsage() {- const response = await apiFetch<{ data: BillingUsage }>('/v1/billing/usage')- billingUsage.value = response.data- }-- async function loadBillingUsageHistory() {- const response = await apiFetch<{ data: BillingUsage[] }>('/v1/billing/usage-history')- billingUsageHistory.value = response.data- }-- async function getSubscriptionUpdateLink(): Promise<string> {- const response = await apiFetch<{ data: string }>('/v1/users/subscription-update-url')- return response.data- }-- async function cancelSubscription(): Promise<string> {- const response = await apiFetch<{ message: string }>('/v1/users/subscription', {- method: 'DELETE',- })- return response.message- }-- async function indexSubscriptionPayments(): Promise<ResponsesUserSubscriptionPaymentsResponse> {- const response = await apiFetch<ResponsesUserSubscriptionPaymentsResponse>(- '/v1/users/subscription/payments',- { params: { limit: 100 } },- )- return response- }-- async function generateSubscriptionPaymentInvoice(- subscriptionInvoiceId: string,- request: RequestsUserPaymentInvoice,- ): Promise<void> {- const response = await apiFetch(- `/v1/users/subscription/invoices/${subscriptionInvoiceId}`,- {- method: 'POST',- body: request,- responseType: 'blob',- },- )-- const pdfBlob = new Blob([response as any], { type: 'application/pdf' })- const url = window.URL.createObjectURL(pdfBlob)- const tempLink = document.createElement('a')- tempLink.href = url- tempLink.setAttribute('download', 'Invoice.pdf')- document.body.appendChild(tempLink)- tempLink.click()- document.body.removeChild(tempLink)- window.URL.revokeObjectURL(url)- }-- // Webhooks- async function createWebhook(payload: RequestsWebhookStore): Promise<EntitiesWebhook> {- const response = await apiFetch<{ data: EntitiesWebhook }>('/v1/webhooks', {- method: 'POST',- body: payload,- })- return response.data- }-- async function getWebhooks(): Promise<EntitiesWebhook[]> {- const response = await apiFetch<{ data: EntitiesWebhook[] }>('/v1/webhooks', {- params: { limit: 100 },- })- return response.data- }-- async function updateWebhook(payload: RequestsWebhookUpdate & { id: string }): Promise<EntitiesWebhook> {- const response = await apiFetch<{ data: EntitiesWebhook }>(`/v1/webhooks/${payload.id}`, {- method: 'PUT',- body: payload,- })- return response.data- }-- async function deleteWebhook(id: string): Promise<void> {- await apiFetch(`/v1/webhooks/${id}`, { method: 'DELETE' })- }-- // Discord- async function createDiscord(payload: RequestsDiscordStore): Promise<EntitiesDiscord> {- const response = await apiFetch<{ data: EntitiesDiscord }>('/v1/discord-integrations', {- method: 'POST',- body: payload,- })- return response.data- }-- async function getDiscordIntegrations(): Promise<EntitiesDiscord[]> {- const response = await apiFetch<{ data: EntitiesDiscord[] }>('/v1/discord-integrations', {- params: { limit: 100 },- })- return response.data- }-- async function updateDiscordIntegration(payload: RequestsDiscordUpdate & { id: string }): Promise<EntitiesDiscord> {- const response = await apiFetch<{ data: EntitiesDiscord }>(`/v1/discord-integrations/${payload.id}`, {- method: 'PUT',- body: payload,- })- return response.data- }-- async function deleteDiscordIntegration(id: string): Promise<void> {- await apiFetch(`/v1/discord-integrations/${id}`, { method: 'DELETE' })- }-- // Send Schedules- async function getSendSchedules(): Promise<EntitiesMessageSendSchedule[]> {- const response = await apiFetch<{ data: EntitiesMessageSendSchedule[] }>('/v1/send-schedules')- return response.data- }-- async function createSendSchedule(payload: RequestsMessageSendScheduleStore): Promise<EntitiesMessageSendSchedule> {- const response = await apiFetch<{ data: EntitiesMessageSendSchedule }>('/v1/send-schedules', {- method: 'POST',- body: payload,- })- return response.data- }-- async function updateSendSchedule(payload: RequestsMessageSendScheduleStore & { id: string }): Promise<EntitiesMessageSendSchedule> {- const response = await apiFetch<{ data: EntitiesMessageSendSchedule }>(`/v1/send-schedules/${payload.id}`, {- method: 'PUT',- body: payload,- })- return response.data- }-- async function deleteSendSchedule(id: string): Promise<void> {- await apiFetch(`/v1/send-schedules/${id}`, { method: 'DELETE' })- }-- // Phone API Keys- async function storePhoneApiKey(name: string): Promise<EntitiesPhoneAPIKey> {- const response = await apiFetch<{ data: EntitiesPhoneAPIKey; message: string }>('/v1/phone-api-keys', {- method: 'POST',- body: { name },- })- notificationsStore.addNotification({ message: response.message, type: 'success' })- return response.data- }-- async function indexPhoneApiKeys(): Promise<EntitiesPhoneAPIKey[]> {- const response = await apiFetch<{ data: EntitiesPhoneAPIKey[] }>('/v1/phone-api-keys', {- params: { limit: 100 },- })- return response.data- }-- async function deletePhoneApiKey(id: string): Promise<void> {- const response = await apiFetch<{ message: string }>(`/v1/phone-api-keys/${id}`, { method: 'DELETE' })- notificationsStore.addNotification({ message: response.message, type: 'success' })- }-- async function deletePhoneFromPhoneApiKey(phoneApiKeyId: string, phoneId: string): Promise<void> {- const response = await apiFetch<{ message: string }>(- `/v1/phone-api-keys/${phoneApiKeyId}/phones/${phoneId}`,- { method: 'DELETE' },- )- notificationsStore.addNotification({ message: response.message, type: 'success' })- }-- // Email notifications- async function saveEmailNotifications(userId: string, payload: RequestsUserNotificationUpdate): Promise<void> {- const authStore = useAuthStore()- const response = await apiFetch<{ data: any }>(`/v1/users/${userId}/notifications`, {- method: 'PUT',- body: payload,- })- authStore.user = response.data- }-- return {- billingUsage,- billingUsageHistory,- loadBillingUsage,- loadBillingUsageHistory,- getSubscriptionUpdateLink,- cancelSubscription,- indexSubscriptionPayments,- generateSubscriptionPaymentInvoice,- createWebhook,- getWebhooks,- updateWebhook,- deleteWebhook,- createDiscord,- getDiscordIntegrations,- updateDiscordIntegration,- deleteDiscordIntegration,- getSendSchedules,- createSendSchedule,- updateSendSchedule,- deleteSendSchedule,- storePhoneApiKey,- indexPhoneApiKeys,- deletePhoneApiKey,- deletePhoneFromPhoneApiKey,- saveEmailNotifications,- }-})-```--- [ ] **Step 2: Commit**--```bash-git add -A-git commit -m "feat(web): create billing Pinia store"-```-------## Task 11: Create Middleware--**Files:**-- Create: `web/app/middleware/auth.ts`-- Create: `web/app/middleware/guest.ts`--- [ ] **Step 1: Create auth middleware**--```typescript-// web/app/middleware/auth.ts-export default defineNuxtRouteMiddleware((to) => {- const authStore = useAuthStore()- if (authStore.authUser === null) {- return navigateTo({ path: '/login', query: { to: to.path } })- }-})-```--- [ ] **Step 2: Create guest middleware**--```typescript-// web/app/middleware/guest.ts-export default defineNuxtRouteMiddleware(() => {- const authStore = useAuthStore()- if (authStore.authUser !== null) {- return navigateTo('/threads')- }-})-```--- [ ] **Step 3: Commit**--```bash-git add -A-git commit -m "feat(web): create auth and guest route middleware"-```-------## Task 12: Port Layouts--**Files:**-- Create: `web/app/layouts/default.vue`-- Create: `web/app/layouts/website.vue`-- Create: `web/app/layouts/error.vue`--**IMPORTANT:** Before writing each layout, call `vuetify-mcp-get_component_api_by_version` for every Vuetify component used (v-app, v-navigation-drawer, v-main, v-app-bar, v-footer, v-container, v-row, v-col, v-btn, v-snackbar, etc.) and `vuetify-mcp-get_v4_breaking_changes` to check for any breaking changes.--- [ ] **Step 1: Create default layout**--```vue-<!-- web/app/layouts/default.vue -->-<script setup lang="ts">-import Pusher from 'pusher-js'-import { useDisplay } from 'vuetify'-import { setAuthHeader } from '~/composables/useApi'-import { useCurrentUser } from 'vuefire'-import { getAuth } from 'firebase/auth'--const route = useRoute()-const config = useRuntimeConfig()-const { lgAndUp } = useDisplay()-const authStore = useAuthStore()-const phonesStore = usePhonesStore()-const threadsStore = useThreadsStore()-const appStore = useAppStore()-const firebaseUser = useCurrentUser()--let poller: ReturnType<typeof setInterval> | null = null-let canPoll = false--const hasDrawer = computed(() => {- return ['threads', 'threads-id'].includes(route.name as string ?? '')-})--onMounted(() => {- setTimeout(() => {- const pusher = new Pusher(config.public.pusherKey as string, {- cluster: config.public.pusherCluster as string,- })-- if (authStore.authUser) {- const channel = pusher.subscribe(authStore.authUser.id)- channel.bind('phone.updated', () => {- canPoll = true- })- }-- startPoller()- }, 10_000)-})--onBeforeUnmount(() => {- if (poller) clearInterval(poller)-})--function startPoller() {- poller = setInterval(async () => {- if (!canPoll || authStore.authUser == null) return-- appStore.setPolling(true)-- if (authStore.authUser && phonesStore.owner) {- const auth = getAuth()- const token = await auth.currentUser?.getIdToken()- if (token) setAuthHeader(token)-- await Promise.all([- phonesStore.loadPhones(true),- threadsStore.loadThreads(),- phonesStore.getHeartbeat(),- ])- }-- canPoll = false- setTimeout(() => appStore.setPolling(false), 1000)- }, 10_000)-}-</script>--<template>- <v-app>- <v-divider v-if="appStore.isLocal" class="py-1 bg-warning" />- <v-navigation-drawer- v-if="lgAndUp && hasDrawer"- :width="400"- permanent- >- <template #prepend>- <v-divider v-if="appStore.isLocal" class="py-1 bg-warning" />- <MessageThreadHeader />- <div class="overflow-y-auto v-navigation-drawer__message-thread">- <MessageThread />- </div>- </template>- </v-navigation-drawer>- <v-main :class="{ 'has-drawer': hasDrawer && lgAndUp }">- <Toast />- <slot v-if="authStore.authStateChanged" />- <LoadingDashboard v-else />- </v-main>- </v-app>-</template>--<style lang="scss">-.v-application {- .w-full {- width: 100%;- }- .h-full {- height: 100%;- }- .has-drawer {- .v-snackbar {- padding-left: 400px;- }- }- .v-navigation-drawer__message-thread {- height: calc(100vh - 120px);- &::-webkit-scrollbar {- width: 8px;- }- &::-webkit-scrollbar-track {- background: #363636;- }- &::-webkit-scrollbar-thumb {- background: #666666;- border-radius: 8px;- }- }- code.hljs {- font-size: 16px;- }-}-</style>-```--- [ ] **Step 2: Create website layout**--```vue-<!-- web/app/layouts/website.vue -->-<script setup lang="ts">-import { useDisplay } from 'vuetify'-import {- mdiGithub,- mdiCircle,- mdiTwitter,- mdiHeart,- mdiShieldStar,- mdiLightbulbOn50,- mdiCreation,- mdiEyeOffOutline,- mdiPost,- mdiCreditCardOutline,- mdiScaleBalance,- mdiEmailOutline,- mdiBookOpenVariant,-} from '@mdi/js'--const router = useRouter()-const route = useRoute()-const { lgAndUp, mdAndUp } = useDisplay()-const authStore = useAuthStore()-const appStore = useAppStore()--function goToPricing() {- if (route.name === 'index') {- document.getElementById('pricing')?.scrollIntoView({ behavior: 'smooth' })- } else {- router.push('/#pricing')- }-}-</script>--<template>- <v-app>- <v-app-bar elevation="2" color="#121212" height="70">- <v-container>- <v-row>- <v-col class="w-full d-flex">- <NuxtLink- to="/"- class="text-decoration-none d-flex"- :class="{ 'mt-5': mdAndUp }"- >- <v-avatar :image="'/img/logo.svg'" :size="33" class="mt-1" />- <h3 v-if="lgAndUp" class="text-h4 ml-1 text-on-surface">- httpSMS- </h3>- </NuxtLink>- <v-spacer />- <v-btn- v-show="lgAndUp"- size="large"- variant="text"- color="primary"- class="my-5 mr-2"- @click="goToPricing"- >- Pricing- </v-btn>- <v-btn- v-show="lgAndUp"- size="large"- variant="text"- color="primary"- class="my-5 mr-2"- :to="{ name: 'blog' }"- >- Blog- </v-btn>- <v-btn- v-show="lgAndUp && authStore.authUser === null"- size="large"- variant="text"- color="primary"- class="my-5 mr-2"- :to="{ name: 'login' }"- >- Login- </v-btn>- <v-btn- v-show="authStore.authUser === null"- color="primary"- :class="{ 'mt-5': mdAndUp, 'mt-1': !mdAndUp }"- :size="lgAndUp ? 'large' : 'default'"- :to="{ name: 'login' }"- >- Get Started- <span v-show="lgAndUp"> For Free</span>- </v-btn>- <v-btn- v-show="authStore.authUser !== null"- color="primary"- :class="{ 'mt-5': mdAndUp, 'mt-1': !mdAndUp }"- :size="lgAndUp ? 'large' : 'default'"- :to="{ name: 'threads' }"- >- Dashboard- </v-btn>- </v-col>- </v-row>- </v-container>- </v-app-bar>- <v-main>- <Toast />- <slot />- </v-main>- <v-footer class="pt-4">- <v-container>- <v-row>- <v-col cols="12" md="3">- <NuxtLink to="/" class="text-decoration-none d-flex">- <v-avatar :image="'/img/logo.svg'" :size="33" class="mt-1" />- <h3 class="text-h4 ml-1 text-on-surface">httpSMS</h3>- </NuxtLink>- <div class="text-subtitle-2 mb-4 text-medium-emphasis">- Made With <v-icon color="#cf1112" :icon="mdiHeart" /> in Tallinn- <v-img- class="d-inline-block"- width="20"- src="https://upload.wikimedia.org/wikipedia/commons/8/8f/Flag_of_Estonia.svg"- />- </div>- <p class="mt-n3">- <v-btn href="https://twitter.com/httpsmsHQ" icon color="#1DA1F2" :icon="mdiTwitter" />- <v-btn :href="appStore.appData.githubUrl" icon size="large" color="#ffffff" :icon="mdiGithub" />- <v-btn href="https://discord.gg/kGk8HVqeEZ" icon size="large" color="#5865f2">- <v-img contain height="24" width="24" src="/img/discord-logo-blue.svg" />- </v-btn>- </p>- </v-col>- <v-col cols="12" md="3">- <h2 class="text-h6 mb-2">Resources</h2>- <ul style="list-style: none" class="pa-0">- <li class="mb-2">- <a class="text-on-surface text-decoration-none" @click.stop="goToPricing">- Pricing <v-icon size="small" :icon="mdiCreditCardOutline" />- </a>- </li>- <li class="mb-2">- <a href="https://httpsms.lemonsqueezy.com/affiliates" class="text-on-surface text-decoration-none">- Affiliates <v-icon color="warning" size="small" :icon="mdiShieldStar" />- </a>- </li>- <li class="mb-2">- <a href="https://status.httpsms.com" class="text-on-surface text-decoration-none">- Site status <v-icon color="success" size="x-small" :icon="mdiCircle" />- </a>- </li>- <li class="mb-2">- <NuxtLink class="text-on-surface text-decoration-none" to="/blog">- Blog <v-icon size="small" :icon="mdiPost" />- </NuxtLink>- </li>- </ul>- </v-col>- <v-col cols="12" md="3">- <h2 class="text-h6 mb-2">Developers</h2>- <ul style="list-style: none" class="pa-0">- <li class="mb-2">- <a :href="appStore.appData.documentationUrl" class="text-on-surface text-decoration-none">- Documentation <v-icon size="small" :icon="mdiBookOpenVariant" />- </a>- </li>- <li class="mb-2">- <a :href="appStore.appData.githubUrl" class="text-on-surface text-decoration-none">- Github <v-icon size="small" :icon="mdiGithub" />- </a>- </li>- <li class="mb-2">- <a href="https://sandbox.httpsms.com" class="text-on-surface text-decoration-none">- Sandbox <v-icon size="small" color="pink" :icon="mdiCreation" />- </a>- </li>- <li class="mb-2">- <a href="https://httpsms.featurebase.app" class="text-on-surface text-decoration-none">- Request Feature <v-icon size="small" color="yellow" :icon="mdiLightbulbOn50" />- </a>- </li>- </ul>- </v-col>- <v-col cols="12" md="3">- <h2 class="text-h6 mb-2">Legal</h2>- <ul style="list-style: none" class="pa-0">- <li class="mb-2">- <NuxtLink class="text-on-surface text-decoration-none" to="/terms-and-conditions">- Terms & Conditions <v-icon size="small" :icon="mdiScaleBalance" />- </NuxtLink>- </li>- <li class="mb-2">- <NuxtLink class="text-on-surface text-decoration-none" to="/privacy-policy">- Privacy Policy <v-icon size="small" :icon="mdiEyeOffOutline" />- </NuxtLink>- </li>- <li class="mt-2">- <a class="text-on-surface text-decoration-none" href="mailto:[email protected]">- Contact Support <v-icon size="small" :icon="mdiEmailOutline" />- </a>- </li>- </ul>- </v-col>- </v-row>- </v-container>- </v-footer>- </v-app>-</template>-```--- [ ] **Step 3: Create error layout**--```vue-<!-- web/app/layouts/error.vue -->-<script setup lang="ts">-const props = defineProps<{- error: {- statusCode: number- message: string- }-}>()-</script>--<template>- <v-app>- <v-main>- <v-container class="text-center mt-16">- <h1 class="text-h1">{{ error.statusCode }}</h1>- <p class="text-h5 mt-4">{{ error.message }}</p>- <v-btn color="primary" class="mt-8" to="/">Go Home</v-btn>- </v-container>- </v-main>- </v-app>-</template>-```--- [ ] **Step 4: Commit**--```bash-git add -A-git commit -m "feat(web): port layouts to Nuxt 4 with Vuetify 4"-```-------## Task 13: Port Components — Toast, LoadingDashboard, LoadingButton, BackButton--**Files:**-- Create: `web/app/components/Toast.vue`-- Create: `web/app/components/LoadingDashboard.vue`-- Create: `web/app/components/LoadingButton.vue`-- Create: `web/app/components/BackButton.vue`--**IMPORTANT:** Call `vuetify-mcp-get_component_api_by_version` for v-snackbar, v-btn, v-progress-circular, v-icon, v-container, v-row, v-col before writing these.--- [ ] **Step 1: Create Toast.vue**--```vue-<!-- web/app/components/Toast.vue -->-<script setup lang="ts">-import { useDisplay } from 'vuetify'-import { mdiCheck, mdiInformation } from '@mdi/js'--const { lgAndUp } = useDisplay()-const notificationsStore = useNotificationsStore()--const notificationActive = computed({- get: () => notificationsStore.notification.active,- set: () => notificationsStore.disableNotification(),-})-</script>--<template>- <v-snackbar- v-model="notificationActive"- :color="notificationsStore.notification.type"- :timeout="notificationsStore.notification.timeout"- >- <v-icon- v-if="notificationsStore.notification.type === 'success'"- :color="notificationsStore.notification.type"- :icon="mdiCheck"- />- <v-icon- v-if="notificationsStore.notification.type === 'info'"- :color="notificationsStore.notification.type"- :icon="mdiInformation"- />- {{ notificationsStore.notification.message }}- <template #actions>- <v-btn- v-if="lgAndUp"- :color="notificationsStore.notification.type"- variant="text"- @click="notificationsStore.disableNotification()"- >- <span class="font-weight-bold">Close</span>- </v-btn>- </template>- </v-snackbar>-</template>-```--- [ ] **Step 2: Create LoadingDashboard.vue**--```vue-<!-- web/app/components/LoadingDashboard.vue -->-<script setup lang="ts">-import { useDisplay } from 'vuetify'-const { mdAndDown } = useDisplay()-</script>--<template>- <v-main>- <v-container fluid class="fill-height">- <v-row align="center" justify="center">- <v-col- cols="12"- md="5"- xl="3"- class="text-center mt-16"- :class="{ 'px-6': mdAndDown, 'px-16': !mdAndDown }"- >- <h2 class="text-h4 text-medium-emphasis mt-16 mb-4">- <img- class="mx-auto d-inline-block"- src="/img/logo.svg"- style="max-width: 32px"- alt="httpSMS Logo"- />- Loading the httpSMS dashboard- </h2>- <v-progress-circular- indeterminate- size="160"- class="mt-8"- color="primary"- />- </v-col>- </v-row>- </v-container>- </v-main>-</template>-```--- [ ] **Step 3: Create LoadingButton.vue**--```vue-<!-- web/app/components/LoadingButton.vue -->-<script setup lang="ts">-const props = withDefaults(defineProps<{- type?: string- block?: boolean- large?: boolean- xLarge?: boolean- tile?: boolean- text?: boolean- small?: boolean- color?: string- icon?: string | null- loading: boolean-}>(), {- type: 'submit',- block: false,- large: false,- xLarge: false,- tile: false,- text: false,- small: false,- color: 'primary',- icon: null,-})--const emit = defineEmits<{- click: []- 'update:loading': [value: boolean]-}>()--const isClicked = ref(false)--watch(() => props.loading, (submitting) => {- if (!submitting && isClicked.value) {- isClicked.value = false- }-})--function onClick() {- isClicked.value = true- emit('click')-}--const size = computed(() => {- if (props.xLarge) return 'x-large'- if (props.large) return 'large'- if (props.small) return 'small'- return 'default'-})-</script>--<template>- <v-btn- :block="block"- :type="type"- :size="size"- :color="color"- :variant="text ? 'text' : 'elevated'"- :disabled="loading"- @click.prevent="onClick"- >- <v-progress-circular- v-if="isClicked"- :size="small ? 20 : 25"- color="grey"- class="mr-2"- indeterminate- />- <v-icon v-if="icon && !loading" start :icon="icon" />- <slot />- </v-btn>-</template>-```--- [ ] **Step 4: Create BackButton.vue**--```vue-<!-- web/app/components/BackButton.vue -->-<script setup lang="ts">-import { useDisplay } from 'vuetify'-import { mdiArrowLeft } from '@mdi/js'-import type { RouteLocationRaw } from 'vue-router'--const props = withDefaults(defineProps<{- route?: RouteLocationRaw- block?: boolean-}>(), {- block: false,-})--const router = useRouter()-const { smAndDown } = useDisplay()--function goBack() {- if (props.route) {- router.push(props.route)- return- }- if (window.history.length > 1) {- router.back()- return- }- router.push({ name: 'index' })-}-</script>--<template>- <v-btn- color="default"- :size="smAndDown ? 'small' : 'default'"- :block="block"- @click="goBack"- >- <v-icon :icon="mdiArrowLeft" />- Go Back- </v-btn>-</template>-```--- [ ] **Step 5: Commit**--```bash-git add -A-git commit -m "feat(web): port Toast, LoadingDashboard, LoadingButton, BackButton components"-```-------## Task 14: Port Components — CopyButton, FixedHeader, BlogAuthorBio, BlogInfo, NuxtLogo--**Files:**-- Create: `web/app/components/CopyButton.vue`-- Create: `web/app/components/FixedHeader.vue`-- Create: `web/app/components/BlogAuthorBio.vue`-- Create: `web/app/components/BlogInfo.vue`-- Create: `web/app/components/NuxtLogo.vue`--**IMPORTANT:** Call `vuetify-mcp-get_component_api_by_version` for each Vuetify component used.--- [ ] **Step 1: Create CopyButton.vue**--```vue-<!-- web/app/components/CopyButton.vue -->-<script setup lang="ts">-import { useDisplay } from 'vuetify'-import { mdiContentCopy } from '@mdi/js'--const props = withDefaults(defineProps<{- value: string- color?: string- block?: boolean- large?: boolean- copyText?: string- notificationText?: string-}>(), {- color: 'default',- block: false,- large: false,- copyText: 'Copy',- notificationText: 'Copied',-})--const { smAndDown } = useDisplay()-const notificationsStore = useNotificationsStore()-const disabled = ref(false)--async function copy() {- disabled.value = true- await navigator.clipboard.writeText(props.value)- notificationsStore.addNotification({ message: props.notificationText, type: 'success' })- setTimeout(() => { disabled.value = false }, 5000)-}-</script>--<template>- <v-btn- :disabled="disabled"- :color="color"- :size="smAndDown ? 'small' : (large ? 'large' : 'default')"- :block="block"- @click="copy"- >- <v-icon start :icon="mdiContentCopy" />- {{ copyText }}- </v-btn>-</template>-```--- [ ] **Step 2: Create FixedHeader.vue**--```vue-<!-- web/app/components/FixedHeader.vue -->-<script setup lang="ts">-import { useDisplay } from 'vuetify'--const { lgAndUp, mdAndDown } = useDisplay()-</script>--<template>- <v-app-bar elevation="0" color="#121212" height="70">- <v-container>- <v-row>- <v-col class="w-full d-flex">- <NuxtLink- :to="{ name: 'index' }"- class="text-on-surface text-h4 text-decoration-none"- :class="{ 'mt-5': mdAndDown, 'mt-4': !mdAndDown }"- >- <v-avatar v-if="lgAndUp" :image="'/img/logo.svg'" :size="30" />- HTTP SMS- </NuxtLink>- <v-spacer />- <v-btn- color="primary"- class="mt-5 mb-5"- :size="lgAndUp ? 'large' : 'default'"- :to="{ name: 'login' }"- >- Get Started- <span v-if="lgAndUp"> For Free</span>- </v-btn>- </v-col>- </v-row>- </v-container>- </v-app-bar>-</template>-```--- [ ] **Step 3: Create BlogAuthorBio.vue**--```vue-<!-- web/app/components/BlogAuthorBio.vue -->-<script setup lang="ts">-import { mdiTwitter, mdiGithub } from '@mdi/js'-</script>--<template>- <div class="d-flex mb-6 mt-8">- <v-avatar image="/img/arnold.png" />- <div class="ml-2">- <p class="text-subtitle-1 mb-n1">Acho Arnold</p>- <a class="mb-n4 text-decoration-none text-on-surface" href="https://twitter.com/acho_arnold">- <v-icon color="#1DA1F2" :icon="mdiTwitter" />- </a>- <a class="ml-2 text-decoration-none text-on-surface" href="https://github.com/AchoArnold">- <v-icon color="#FFFFFF" :icon="mdiGithub" />- </a>- </div>- </div>-</template>-```--- [ ] **Step 4: Create BlogInfo.vue**--```vue-<!-- web/app/components/BlogInfo.vue -->-<script setup lang="ts">-import { mdiBookOpenVariant } from '@mdi/js'--const appStore = useAppStore()-</script>--<template>- <div>- <NuxtLink to="/" class="text-decoration-none d-flex">- <v-avatar :image="'/img/logo.svg'" :size="33" class="mt-1" />- <h3 class="text-h4 text-on-surface ml-1">httpSMS</h3>- </NuxtLink>- <p>- httpSMS is an- <a class="text-decoration-none" href="https://github.com/NdoleStudio/httpsms">open source</a>- application that converts your android phone into an SMS gateway so you- can send and receive SMS messages using a simple HTTP API.- </p>- <v-btn :href="appStore.appData.documentationUrl">- <v-icon start :icon="mdiBookOpenVariant" />- Documentation- </v-btn>- </div>-</template>-```--- [ ] **Step 5: Create NuxtLogo.vue (minimal placeholder)**--```vue-<!-- web/app/components/NuxtLogo.vue -->-<template>- <img src="/img/logo.svg" alt="httpSMS Logo" style="max-width: 100px" />-</template>-```--- [ ] **Step 6: Commit**--```bash-git add -A-git commit -m "feat(web): port CopyButton, FixedHeader, BlogAuthorBio, BlogInfo, NuxtLogo"-```-------## Task 15: Port Components — FirebaseAuth, MessageThread, MessageThreadHeader--**Files:**-- Create: `web/app/components/FirebaseAuth.vue`-- Create: `web/app/components/MessageThread.vue`-- Create: `web/app/components/MessageThreadHeader.vue`--**IMPORTANT:** Call `vuetify-mcp-get_component_api_by_version` for v-select, v-list, v-list-item, v-menu, v-tooltip, v-sheet, v-progress-linear before writing.--- [ ] **Step 1: Create FirebaseAuth.vue**--This component uses FirebaseUI which must be loaded client-side only. In Nuxt 4, wrap with `<ClientOnly>` or use `.client.vue` suffix.--```vue-<!-- web/app/components/FirebaseAuth.vue -->-<script setup lang="ts">-import { getAuth, GoogleAuthProvider, GithubAuthProvider, EmailAuthProvider } from 'firebase/auth'--const props = withDefaults(defineProps<{- to?: string-}>(), { to: '/' })--const router = useRouter()-const authStore = useAuthStore()-const notificationsStore = useNotificationsStore()-const appStore = useAppStore()-const authContainer = ref<HTMLElement | null>(null)-const firebaseUIInitialized = ref(false)-let ui: any = null--onMounted(async () => {- if (!import.meta.client) return-- const firebaseui = await import('firebaseui')- await import('firebaseui/dist/firebaseui.css')-- const auth = getAuth()- ui = new firebaseui.auth.AuthUI(auth)- ui.start('#firebaseui-auth-container', {- callbacks: {- signInSuccessWithAuthResult: (authResult: any) => {- notificationsStore.addNotification({ message: 'Login successful!', type: 'success' })- authStore.onAuthStateChanged(authResult.user)- router.push({ path: props.to })- return false- },- uiShown: () => {- firebaseUIInitialized.value = true- if (authContainer.value) {- Array.from(authContainer.value.getElementsByClassName('firebaseui-idp-text-long'))- .forEach((item: Element) => {- item.textContent = item.textContent?.replace('Sign in with', 'Continue with') || null- })- }- },- },- signInFlow: 'popup',- signInSuccessUrl: window.location.href,- signInOptions: [- GoogleAuthProvider.PROVIDER_ID,- GithubAuthProvider.PROVIDER_ID,- EmailAuthProvider.PROVIDER_ID,- ],- tosUrl: appStore.appData.url + '/terms-and-conditions',- privacyPolicyUrl: appStore.appData.url + '/privacy-policy',- })-})--onBeforeUnmount(() => {- if (ui) ui.delete()-})-</script>--<template>- <div>- <div id="firebaseui-auth-container" ref="authContainer" />- <v-progress-circular- v-if="!firebaseUIInitialized"- class="mx-auto d-block my-16"- :size="80"- :width="5"- color="primary"- indeterminate- />- </div>-</template>-```--- [ ] **Step 2: Create MessageThread.vue**--Port from the existing component. This is a larger component — read the full source from the backup branch and rewrite using `<script setup>`, replacing `$store` with Pinia stores, `$vuetify.breakpoint` with `useDisplay()`, and Vue 2 filters with function calls.--```vue-<!-- web/app/components/MessageThread.vue -->-<script setup lang="ts">-import { useDisplay } from 'vuetify'-import { mdiPlus } from '@mdi/js'-import { formatPhoneNumber } from '~/utils/filters'--const { mdAndDown } = useDisplay()-const threadsStore = useThreadsStore()-const phonesStore = usePhonesStore()-</script>--<template>- <div>- <v-progress-linear- v-if="threadsStore.loadingThreads"- color="primary"- indeterminate- />- <div- v-if="!threadsStore.loadingThreads && threadsStore.archivedThreads"- class="bg-warning py-1 text-center text-uppercase text-subtitle-1"- >- Archived Messages- </div>- <v-sheet- v-if="!threadsStore.loadingThreads && threadsStore.threads.length === 0 && !threadsStore.archivedThreads"- class="text-center mt-8 mx-3"- :color="mdAndDown ? '#121212' : '#363636'"- >- <div v-if="mdAndDown">- <v-img- class="mx-auto mb-4"- max-width="80%"- src="/img/person-texting.svg"- />- <p v-if="phonesStore.owner" class="text-medium-emphasis">- Start sending messages- </p>- </div>- <v-btn- v-if="phonesStore.owner && phonesStore.phones.length !== 0"- color="primary"- :to="{ name: 'messages' }"- >- <v-icon :icon="mdiPlus" />- New Message- </v-btn>- </v-sheet>- <!-- Thread list items would be ported from the full MessageThread.vue source -->- <!-- Each thread item renders as a clickable list item navigating to /threads/[id] -->- </div>-</template>-```--Note: The full MessageThread.vue content should be ported from the backup branch. The pattern above shows the migration approach.--- [ ] **Step 3: Create MessageThreadHeader.vue**--```vue-<!-- web/app/components/MessageThreadHeader.vue -->-<script setup lang="ts">-import { useDisplay } from 'vuetify'-import { getAuth, signOut } from 'firebase/auth'-import {- mdiPlus, mdiAccountCog, mdiLogout, mdiCellphoneKey, mdiDownload,- mdiFinance, mdiBatteryChargingHigh, mdiPackageUp, mdiPackageDown,- mdiDotsVertical, mdiMagnify, mdiCommentTextMultipleOutline, mdiCircle,-} from '@mdi/js'-import { formatPhoneNumber, phoneCountry, humanizeTime } from '~/utils/filters'-import type { EntitiesPhone } from '~~/shared/types/api'--const router = useRouter()-const route = useRoute()-const { mdAndDown, mdAndUp, lgAndUp } = useDisplay()-const authStore = useAuthStore()-const phonesStore = usePhonesStore()-const threadsStore = useThreadsStore()-const appStore = useAppStore()-const notificationsStore = useNotificationsStore()--const selectedMenuItem = ref(-1)--interface SelectItem {- title: string- value: string-}--const owners = computed<SelectItem[]>(() => {- return phonesStore.phones.map((phone: EntitiesPhone) => ({- title: formatPhoneNumber(phone.phone_number),- value: phone.phone_number,- }))-})--async function onOwnerChanged(owner: string) {- await authStore.updateUser({ owner })- if (route.name !== 'threads') {- threadsStore.setThreadId(null)- await router.push({ name: 'threads' })- return- }- await threadsStore.loadThreads()-}--async function toggleArchive() {- threadsStore.toggleArchive()- setTimeout(() => { selectedMenuItem.value = -1 }, 1000)- if (route.name !== 'threads') {- threadsStore.setThreadId(null)- await router.push({ name: 'threads' })- return- }- await threadsStore.loadThreads()-}--async function logout() {- const auth = getAuth()- await signOut(auth)- authStore.resetState()- phonesStore.resetState()- threadsStore.resetState()- notificationsStore.addNotification({ type: 'info', message: 'You have successfully logged out' })- router.push({ name: 'index' })-}-</script>--<template>- <v-sheet- class="pa-4 d-flex"- :elevation="lgAndUp ? 0 : 2"- :color="lgAndUp ? 'grey-darken-4' : 'black'"- >- <div :class="{ 'px-2': mdAndDown }">- <v-toolbar-title>- <div class="d-flex pt-2" style="width: 245px">- <v-select- variant="outlined"- density="compact"- :disabled="owners.length === 0"- placeholder="Phone Numbers"- :class="{ 'mb-n6': !phonesStore.owner }"- :items="owners"- :model-value="phonesStore.owner"- @update:model-value="onOwnerChanged"- />- <div style="width: 50px">- <v-progress-circular- v-if="appStore.polling"- indeterminate- :size="20"- :width="1"- class="mt-3 ml-2"- color="success"- />- </div>- </div>- </v-toolbar-title>- <div v-if="phonesStore.owner" class="d-flex mt-n4">- <p class="text-medium-emphasis mb-n1">- {{ phoneCountry(phonesStore.owner) }}- </p>- <v-tooltip- v-if="phonesStore.heartbeat"- location="end"- >- <template #activator="{ props: tooltipProps }">- <v-btn- v-bind="tooltipProps"- size="x-small"- :to="{ name: 'heartbeats-id', params: { id: phonesStore.owner } }"- color="success"- class="ml-2 mt-1 mb-n1"- icon- >- <v-icon v-if="phonesStore.heartbeat.charging" size="small" class="mt-n1" :icon="mdiBatteryChargingHigh" />- <v-icon v-else size="x-small" :icon="mdiCircle" />- </v-btn>- </template>- <h4>Last Heartbeat</h4>- {{ humanizeTime(phonesStore.heartbeat.timestamp) }} ago- </v-tooltip>- </div>- </div>- <v-spacer />- <v-menu>- <template #activator="{ props: menuProps }">- <v-btn v-bind="menuProps" icon variant="text" class="mt-2">- <v-icon :icon="mdiDotsVertical" />- </v-btn>- </template>- <v-list class="px-2" nav :density="mdAndDown ? 'compact' : 'default'">- <v-list-item @click.prevent="toggleArchive">- <template #prepend>- <v-icon v-if="!threadsStore.archivedThreads" :icon="mdiPackageDown" />- <v-icon v-else :icon="mdiPackageUp" />- </template>- <v-list-item-title>- {{ threadsStore.archivedThreads ? 'Unarchived' : 'Archived' }}- </v-list-item-title>- </v-list-item>- <v-list-item v-if="phonesStore.owner" :to="{ name: 'messages' }">- <template #prepend><v-icon :icon="mdiPlus" /></template>- <v-list-item-title>New Message</v-list-item-title>- </v-list-item>- <v-list-item v-if="phonesStore.owner" :to="{ name: 'bulk-messages' }">- <template #prepend><v-icon :icon="mdiCommentTextMultipleOutline" /></template>- <v-list-item-title>Bulk Messages</v-list-item-title>- </v-list-item>- <v-list-item v-if="phonesStore.owner" :to="{ name: 'search-messages' }">- <template #prepend><v-icon :icon="mdiMagnify" /></template>- <v-list-item-title>Search Messages</v-list-item-title>- </v-list-item>- <v-list-item :to="{ name: 'settings' }">- <template #prepend><v-icon :icon="mdiAccountCog" /></template>- <v-list-item-title>Settings</v-list-item-title>- </v-list-item>- <v-list-item :to="{ name: 'phone-api-keys' }">- <template #prepend><v-icon :icon="mdiCellphoneKey" /></template>- <v-list-item-title>Phone API Keys</v-list-item-title>- </v-list-item>- <v-list-item v-if="phonesStore.owner" :href="appStore.appData.appDownloadUrl">- <template #prepend><v-icon :icon="mdiDownload" /></template>- <v-list-item-title>Install App</v-list-item-title>- </v-list-item>- <v-list-item :to="{ name: 'billing' }">- <template #prepend><v-icon :icon="mdiFinance" /></template>- <v-list-item-title>Usage & Billing</v-list-item-title>- </v-list-item>- <v-list-item @click.prevent="logout">- <template #prepend><v-icon :icon="mdiLogout" /></template>- <v-list-item-title>Logout</v-list-item-title>- </v-list-item>- </v-list>- </v-menu>- </v-sheet>-</template>-```--- [ ] **Step 4: Commit**--```bash-git add -A-git commit -m "feat(web): port FirebaseAuth, MessageThread, MessageThreadHeader components"-```-------## Task 16: Port Pages — Login & Index (Homepage)--**Files:**-- Create: `web/app/pages/login.vue`-- Create: `web/app/pages/index.vue`--**IMPORTANT:** Call `vuetify-mcp-get_component_api_by_version` for all Vuetify components used. Port from the backup branch source, converting class-based syntax to `<script setup>`, Vuex to Pinia, `$vuetify.breakpoint` to `useDisplay()`, `nuxt-link` to `NuxtLink`, `require()` for images to static `/img/` paths.--- [ ] **Step 1: Create login.vue**--Read the source from backup branch `web/pages/login.vue`, then rewrite with:-- `<script setup lang="ts">`-- `useDisplay()` for breakpoints-- `useAuthStore()` instead of `$store`-- `definePageMeta({ layout: 'website', middleware: ['guest'] })`-- Vuetify 4 component API--- [ ] **Step 2: Create index.vue (homepage)**--Read the source from backup branch `web/pages/index.vue`, then rewrite with:-- `<script setup lang="ts">`-- `definePageMeta({ layout: 'website' })`-- `useDisplay()` for all breakpoint references-- Static image paths (`/img/...`) instead of `require()`-- Vuetify 4 component API (v-btn `size` prop instead of `large`/`small`, `variant` instead of `text`)--- [ ] **Step 3: Commit**--```bash-git add -A-git commit -m "feat(web): port login and homepage pages"-```-------## Task 17: Port Pages — Threads, Messages, Search, Bulk Messages--**Files:**-- Create: `web/app/pages/threads/index.vue`-- Create: `web/app/pages/threads/[id]/index.vue`-- Create: `web/app/pages/messages/index.vue`-- Create: `web/app/pages/search-messages/index.vue`-- Create: `web/app/pages/bulk-messages/index.vue`--For each page, apply the same migration pattern:-1. Read original source from backup branch-2. Rewrite with `<script setup lang="ts">`-3. Replace `$store` with Pinia stores-4. Replace `$vuetify.breakpoint` with `useDisplay()`-5. Replace `nuxt-link` with `NuxtLink`-6. Replace filters (`| filterName`) with function calls-7. Use Vuetify 4 component API-8. Add `definePageMeta({ middleware: ['auth'] })` for authenticated pages--- [ ] **Step 1: Port threads/index.vue**-- [ ] **Step 2: Port threads/[id]/index.vue** (rename from `_id`)-- [ ] **Step 3: Port messages/index.vue**-- [ ] **Step 4: Port search-messages/index.vue**-- [ ] **Step 5: Port bulk-messages/index.vue**-- [ ] **Step 6: Commit**--```bash-git add -A-git commit -m "feat(web): port threads, messages, search, and bulk messages pages"-```-------## Task 18: Port Pages — Settings, Billing, Heartbeats, Phone API Keys--**Files:**-- Create: `web/app/pages/settings/index.vue`-- Create: `web/app/pages/billing/index.vue`-- Create: `web/app/pages/heartbeats/[id].vue`-- Create: `web/app/pages/phone-api-keys/index.vue`--Same migration pattern as Task 17.--- [ ] **Step 1: Port settings/index.vue**-- [ ] **Step 2: Port billing/index.vue**-- [ ] **Step 3: Port heartbeats/[id].vue** (rename from `_id.vue`)-- [ ] **Step 4: Port phone-api-keys/index.vue**-- [ ] **Step 5: Commit**--```bash-git add -A-git commit -m "feat(web): port settings, billing, heartbeats, phone-api-keys pages"-```-------## Task 19: Port Pages — Blog, Legal--**Files:**-- Create: `web/app/pages/blog/index.vue`-- Create: `web/app/pages/blog/how-to-send-sms-messages-from-excel.vue`-- Create: `web/app/pages/blog/grant-send-and-read-sms-permissions-on-android.vue`-- Create: `web/app/pages/blog/forward-incoming-sms-from-phone-to-webhook.vue`-- Create: `web/app/pages/blog/end-to-end-encryption-to-sms-messages.vue`-- Create: `web/app/pages/blog/send-bulk-sms-from-csv-file-with-no-code.vue`-- Create: `web/app/pages/blog/send-sms-from-android-phone-with-python.vue`-- Create: `web/app/pages/blog/send-sms-when-new-row-is-added-to-google-sheets-using-zapier.vue`-- Create: `web/app/pages/privacy-policy/index.vue`-- Create: `web/app/pages/terms-and-conditions/index.vue`--Same migration pattern. Blog pages use `layout: 'website'` and are mostly static content with Vuetify components.--- [ ] **Step 1: Port blog/index.vue**-- [ ] **Step 2: Port all blog article pages** (7 files)-- [ ] **Step 3: Port privacy-policy/index.vue**-- [ ] **Step 4: Port terms-and-conditions/index.vue**-- [ ] **Step 5: Commit**--```bash-git add -A-git commit -m "feat(web): port blog and legal pages"-```-------## Task 20: Port Static Assets & Client Plugins--**Files:**-- Copy: `web/public/` (from old `web/static/`)-- Create: `web/app/plugins/chart.client.ts`-- Create: `web/app/plugins/vue-glow.client.ts`--- [ ] **Step 1: Copy static assets to public/**--```bash-# Copy from backup branch: static/ → public/-# Includes: favicon.ico, integrations.js, header.png, templates/, img/-```--- [ ] **Step 2: Move images from assets/img/ to public/img/**--Images referenced with static paths (`/img/logo.svg`, etc.) go in `public/img/`. Images that need Vite processing stay in `app/assets/img/`.--- [ ] **Step 3: Create chart.client.ts**--```typescript-// web/app/plugins/chart.client.ts-import {- Chart,- CategoryScale,- LinearScale,- PointElement,- LineElement,- Title,- Tooltip,- Legend,- BarElement,- Filler,-} from 'chart.js'--export default defineNuxtPlugin(() => {- Chart.register(- CategoryScale,- LinearScale,- PointElement,- LineElement,- BarElement,- Title,- Tooltip,- Legend,- Filler,- )-})-```--- [ ] **Step 4: Create vue-glow.client.ts**--```typescript-// web/app/plugins/vue-glow.client.ts-import VueGlow from 'vue-glow'--export default defineNuxtPlugin((nuxtApp) => {- nuxtApp.vueApp.use(VueGlow)-})-```--- [ ] **Step 5: Commit**--```bash-git add -A-git commit -m "feat(web): port static assets and client plugins"-```-------## Task 21: Update Docker & Build Config--**Files:**-- Modify: `web/Dockerfile`-- Modify: `web/nginx.conf`-- Create: `web/.env.production`--- [ ] **Step 1: Update Dockerfile for Nuxt 4**--```dockerfile-# web/Dockerfile-FROM node:20-alpine AS builder--RUN corepack enable && corepack prepare pnpm@latest --activate--WORKDIR /app-COPY package.json pnpm-lock.yaml ./-RUN pnpm install --frozen-lockfile--COPY . .-RUN pnpm run generate--FROM nginx:alpine-COPY --from=builder /app/.output/public /usr/share/nginx/html-COPY nginx.conf /etc/nginx/conf.d/default.conf--EXPOSE 80-CMD ["nginx", "-g", "daemon off;"]-```--- [ ] **Step 2: Keep nginx.conf** (should work as-is for static files)--- [ ] **Step 3: Create .env.production** (copy from backup, same vars)--- [ ] **Step 4: Update package.json scripts**--Ensure `package.json` has:-```json-{- "scripts": {- "dev": "nuxt dev",- "build": "nuxt build",- "generate": "nuxt generate",- "preview": "nuxt preview",- "lint": "eslint .",- "typecheck": "nuxt typecheck"- }-}-```--- [ ] **Step 5: Commit**--```bash-git add -A-git commit -m "feat(web): update Dockerfile and build configuration for Nuxt 4"-```-------## Task 22: Verify Build Compiles--- [ ] **Step 1: Install dependencies**--```bash-cd C:\Users\Arnold\Work\NdoleStudio\httpsms.com\web-pnpm install-```--- [ ] **Step 2: Run TypeScript check**--```bash-pnpm typecheck-```--Expected: No TypeScript errors. If there are errors, fix them.--- [ ] **Step 3: Run dev server**--```bash-pnpm dev-```--Expected: Dev server starts on port 3000 without errors.--- [ ] **Step 4: Run static generation**--```bash-pnpm generate-```--Expected: All pages generate successfully. Fix any SSR/prerender errors.--- [ ] **Step 5: Commit any fixes**--```bash-git add -A-git commit -m "fix(web): resolve TypeScript and build errors"-```-------## Task 23: Verify ALL Layouts Render Correctly--- [ ] **Step 1: Start dev server**--```bash-cd C:\Users\Arnold\Work\NdoleStudio\httpsms.com\web-pnpm dev-```--- [ ] **Step 2: Verify default layout**--Navigate to `http://localhost:3000/threads` (or any auth-required page in logged-in state). Confirm:-- `v-app` renders with dark theme-- Navigation drawer appears on large screens-- Toast component is present-- No console errors--- [ ] **Step 3: Verify website layout**--Navigate to `http://localhost:3000/`. Confirm:-- App bar with logo, navigation buttons renders-- Footer with 4 columns renders-- Dark theme is active-- Responsive breakpoints work (resize browser)--- [ ] **Step 4: Verify error layout**--Navigate to `http://localhost:3000/nonexistent-page`. Confirm:-- Error page renders with status code and message-- "Go Home" button works-------## Task 24: Verify ALL Components Render Correctly--- [ ] **Step 1: Verify Toast component**--Trigger a notification via the store (e.g., login success). Confirm snackbar appears with correct color, message, and auto-dismisses.--- [ ] **Step 2: Verify LoadingDashboard**--Load the app without being authenticated — confirm the loading spinner and text appear.--- [ ] **Step 3: Verify LoadingButton**--Navigate to any page with a form submit button. Confirm:-- Button shows spinner when clicked-- Disabled state works during loading--- [ ] **Step 4: Verify BackButton**--Navigate to a page with a back button. Confirm it navigates back correctly.--- [ ] **Step 5: Verify CopyButton**--Navigate to settings/API key page. Click copy. Confirm:-- Text is copied to clipboard-- Success notification appears-- Button is temporarily disabled--- [ ] **Step 6: Verify FixedHeader**--Navigate to a blog post page that uses FixedHeader. Confirm app bar renders with logo and "Get Started" button.--- [ ] **Step 7: Verify BlogAuthorBio**--Navigate to any blog post. Confirm author avatar, name, and social links render.--- [ ] **Step 8: Verify BlogInfo**--Navigate to any blog post. Confirm httpSMS description and documentation button render.--- [ ] **Step 9: Verify FirebaseAuth**--Navigate to `/login`. Confirm:-- FirebaseUI widget loads-- Shows Google, GitHub, Email auth options-- Loading spinner shows before widget init--- [ ] **Step 10: Verify MessageThread**--Navigate to `/threads` when logged in. Confirm:-- Thread list renders-- Empty state shows "New Message" button when no threads-- Loading indicator works--- [ ] **Step 11: Verify MessageThreadHeader**--Navigate to `/threads`. Confirm:-- Phone number selector works-- Heartbeat indicator shows-- Menu opens with all items (Archive, New Message, Settings, etc.)-- Logout works-------## Task 25: Verify ALL Pages Render Correctly--- [ ] **Step 1: Verify pages/index.vue (homepage)**--Navigate to `/`. Confirm:-- Hero section with heading, buttons renders-- "Get Started" and "Live Demo" buttons are clickable-- Images load-- Pricing section exists-- Responsive layout works--- [ ] **Step 2: Verify pages/login.vue**--Navigate to `/login`. Confirm:-- FirebaseAuth component loads-- Guest middleware redirects if already logged in-- Login form appears--- [ ] **Step 3: Verify pages/threads/index.vue**--Navigate to `/threads` (authenticated). Confirm:-- Auth middleware protects the page-- Thread list loads-- Navigation drawer shows on desktop--- [ ] **Step 4: Verify pages/threads/[id]/index.vue**--Navigate to `/threads/some-id`. Confirm:-- Messages for the thread load-- Message input area renders-- Send button works--- [ ] **Step 5: Verify pages/messages/index.vue**--Navigate to `/messages`. Confirm:-- New message form renders-- Phone number inputs work-- Send functionality works--- [ ] **Step 6: Verify pages/search-messages/index.vue**--Navigate to `/search-messages`. Confirm:-- Search form renders-- Results display correctly--- [ ] **Step 7: Verify pages/bulk-messages/index.vue**--Navigate to `/bulk-messages`. Confirm:-- File upload area renders-- CSV template download link works-- Submit button works--- [ ] **Step 8: Verify pages/settings/index.vue**--Navigate to `/settings`. Confirm:-- All settings sections render-- API key display and rotation work-- Webhook management works--- [ ] **Step 9: Verify pages/billing/index.vue**--Navigate to `/billing`. Confirm:-- Usage chart renders-- Subscription info displays-- Payment history loads--- [ ] **Step 10: Verify pages/heartbeats/[id].vue**--Navigate to `/heartbeats/+1234567890`. Confirm:-- Heartbeat history chart renders-- Phone info displays--- [ ] **Step 11: Verify pages/phone-api-keys/index.vue**--Navigate to `/phone-api-keys`. Confirm:-- API keys list renders-- Create new key works-- Delete key works--- [ ] **Step 12: Verify pages/privacy-policy/index.vue**--Navigate to `/privacy-policy`. Confirm page content renders with website layout.--- [ ] **Step 13: Verify pages/terms-and-conditions/index.vue**--Navigate to `/terms-and-conditions`. Confirm page content renders with website layout.--- [ ] **Step 14: Verify pages/blog/index.vue**--Navigate to `/blog`. Confirm blog post listing renders.--- [ ] **Step 15: Verify all blog article pages**--Navigate to each blog article URL and confirm:-- Content renders-- Code highlighting works-- BlogAuthorBio component shows-- BlogInfo component shows-- Website layout is applied--Blog articles to check:-- `/blog/how-to-send-sms-messages-from-excel`-- `/blog/grant-send-and-read-sms-permissions-on-android`-- `/blog/forward-incoming-sms-from-phone-to-webhook`-- `/blog/end-to-end-encryption-to-sms-messages`-- `/blog/send-bulk-sms-from-csv-file-with-no-code`-- `/blog/send-sms-from-android-phone-with-python`-- `/blog/send-sms-when-new-row-is-added-to-google-sheets-using-zapier`-------## Task 26: Final Build Verification & Commit--- [ ] **Step 1: Run full TypeScript check**--```bash-cd C:\Users\Arnold\Work\NdoleStudio\httpsms.com\web-pnpm typecheck-```--Expected: 0 errors.--- [ ] **Step 2: Run lint**--```bash-pnpm lint-```--Expected: No lint errors (or only auto-fixable ones).--- [ ] **Step 3: Run static generation**--```bash-pnpm generate-```--Expected: All pages pre-render successfully.--- [ ] **Step 4: Final commit**--```bash-git add -A-git commit -m "feat(web): complete Nuxt 4 + Vuetify 4 migration--Migrated from:-- Nuxt 2.18.1 → Nuxt 4.x-- Vue 2.7 → Vue 3.x-- Vuetify 2.7 → Vuetify 4.x-- Vuex 3 → Pinia-- vue-property-decorator → <script setup lang=\"ts\">-- @nuxtjs/firebase → nuxt-vuefire--All components and pages verified to render correctly."-```diff --git a/docs/superpowers/plans/2026-07-18-message-thread-archive-ui.md b/docs/superpowers/plans/2026-07-18-message-thread-archive-ui.mddeleted file mode 100644index 3803169c..00000000--- a/docs/superpowers/plans/2026-07-18-message-thread-archive-ui.md+++ /dev/null@@ -1,241 +0,0 @@-# Message Thread Archive UI Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Highlight the active message thread with the primary color and make archive actions return to the current filtered thread list with a success notification.--**Architecture:** Keep archive state transitions in the Pinia threads store: perform the API request, remove the moved thread from the visible collection, clear the selection, and notify. Keep route navigation in the thread page, and use Vuetify's built-in active-item color handling for the list styling.--**Tech Stack:** Nuxt 4, Vue 3, Pinia 3, Vuetify 4, TypeScript, pnpm--## Global Constraints--- Preserve the current `archivedThreads` filter after archive and unarchive actions.-- Show exactly `Archived` or `Unarchived` as a success notification after a successful update.-- Do not change local thread state or navigate when the API request fails.-- Use existing dependencies and validation commands only; the web package has no configured automated test runner.-- Include the repository's `Co-authored-by` and `Copilot-Session` trailers in every commit.-------### Task 1: Active Thread Primary Color--**Files:**-- Modify: `web/app/components/MessageThread.vue:94-100`--**Interfaces:**-- Consumes: `threadsStore.threadId` and each thread's route-backed `v-list-item`-- Produces: Vuetify active-item styling through `color="primary"`--- [ ] **Step 1: Run the source assertion to verify the active color is missing**--Run from `web/`:--```powershell-node -e "const fs=require('fs');const s=fs.readFileSync('app/components/MessageThread.vue','utf8');if(!/<v-list-item[\s\S]*?color=\"primary\"[\s\S]*?:active=\"threadsStore\.threadId === thread\.id\"/.test(s))throw new Error('active thread primary color missing')"-```--Expected: FAIL with `Error: active thread primary color missing`.--- [ ] **Step 2: Add the primary color to every rendered thread item**--Change the list item to:--```vue-<v-list-item- v-for="thread in threadsStore.threads"- :key="thread.id"- color="primary"- :to="{ name: 'threads-id', params: { id: thread.id } }"- :active="threadsStore.threadId === thread.id"->-```--- [ ] **Step 3: Re-run the source assertion**--Run from `web/`:--```powershell-node -e "const fs=require('fs');const s=fs.readFileSync('app/components/MessageThread.vue','utf8');if(!/<v-list-item[\s\S]*?color=\"primary\"[\s\S]*?:active=\"threadsStore\.threadId === thread\.id\"/.test(s))throw new Error('active thread primary color missing')"-```--Expected: exit code 0.--- [ ] **Step 4: Lint the component**--Run from `web/`:--```powershell-pnpm exec eslint app/components/MessageThread.vue-pnpm exec stylelint app/components/MessageThread.vue-pnpm exec prettier --check app/components/MessageThread.vue-```--Expected: all commands exit with code 0.--- [ ] **Step 5: Commit**--```powershell-git add web/app/components/MessageThread.vue-git commit -m "fix(web): highlight active thread" -m "Co-authored-by: Copilot <[email protected]>`nCopilot-Session: bf7ad4f0-3e1b-4f2d-9587-fe5b0dfae6dc"-```--### Task 2: Archive Without Switching Filters--**Files:**-- Modify: `web/app/stores/threads.ts:78-91`-- Modify: `web/app/pages/threads/[id]/index.vue:146-166`--**Interfaces:**-- Consumes: `updateThread({ threadId: string, isArchived: boolean }): Promise<void>`-- Produces: successful archive updates that remove the moved thread, clear `threadId`, notify, and allow the page to navigate to `/threads`--- [ ] **Step 1: Run source assertions to verify the required behavior is missing**--Run from `web/`:--```powershell-node -e "const fs=require('fs');const s=fs.readFileSync('app/stores/threads.ts','utf8');for(const x of [\"threads.value = threads.value.filter\",'threadId.value = null',\"payload.isArchived ? 'Archived' : 'Unarchived'\"])if(!s.includes(x))throw new Error('archive state transition missing: '+x)"-node -e "const fs=require('fs');const s=fs.readFileSync('app/pages/threads/[id]/index.vue','utf8');const matches=s.match(/await router\.push\('\/threads'\)/g)||[];if(matches.length<3)throw new Error('archive navigation missing')"-```--Expected: both commands FAIL because the store still switches `archivedThreads` and the archive actions do not navigate.--- [ ] **Step 2: Replace the store's archive-filter switch and reload**--Replace the statements after the successful `apiFetch` call in `updateThread` with:--```ts-threads.value = threads.value.filter(- (thread) => thread.id !== payload.threadId,-)-threadId.value = null-notificationsStore.addNotification({- message: payload.isArchived ? 'Archived' : 'Unarchived',- type: 'success',-})-```--The complete function must remain:--```ts-async function updateThread(payload: {- threadId: string- isArchived: boolean-}) {- await apiFetch(`/v1/message-threads/${payload.threadId}`, {- method: 'PUT',- body: { is_archived: payload.isArchived },- })- threads.value = threads.value.filter(- (thread) => thread.id !== payload.threadId,- )- threadId.value = null- notificationsStore.addNotification({- message: payload.isArchived ? 'Archived' : 'Unarchived',- type: 'success',- })-}-```--- [ ] **Step 3: Route to the current filtered list after archive**--Change `archiveThread` to:--```ts-async function archiveThread() {- await threadsStore.updateThread({- threadId: threadsStore.currentThread!.id,- isArchived: true,- })- await router.push('/threads')-}-```--- [ ] **Step 4: Route to the current filtered list after unarchive**--Change `unArchiveThread` to:--```ts-async function unArchiveThread() {- await threadsStore.updateThread({- threadId: threadsStore.currentThread!.id,- isArchived: false,- })- await router.push('/threads')-}-```--- [ ] **Step 5: Re-run the source assertions**--Run from `web/`:--```powershell-node -e "const fs=require('fs');const s=fs.readFileSync('app/stores/threads.ts','utf8');for(const x of [\"threads.value = threads.value.filter\",'threadId.value = null',\"payload.isArchived ? 'Archived' : 'Unarchived'\"])if(!s.includes(x))throw new Error('archive state transition missing: '+x);if(s.includes('archivedThreads.value = payload.isArchived'))throw new Error('archive filter still switches')"-node -e "const fs=require('fs');const s=fs.readFileSync('app/pages/threads/[id]/index.vue','utf8');const matches=s.match(/await router\.push\('\/threads'\)/g)||[];if(matches.length<3)throw new Error('archive navigation missing')"-```--Expected: both commands exit with code 0.--- [ ] **Step 6: Lint the changed behavior**--Run from `web/`:--```powershell-pnpm exec eslint app/stores/threads.ts "app/pages/threads/[id]/index.vue"-pnpm exec stylelint "app/pages/threads/[id]/index.vue"-pnpm exec prettier --check app/stores/threads.ts "app/pages/threads/[id]/index.vue"-```--Expected: all commands exit with code 0.--- [ ] **Step 7: Commit**--```powershell-git add web/app/stores/threads.ts "web/app/pages/threads/[id]/index.vue"-git commit -m "fix(web): preserve thread archive filter" -m "Co-authored-by: Copilot <[email protected]>`nCopilot-Session: bf7ad4f0-3e1b-4f2d-9587-fe5b0dfae6dc"-```--### Task 3: Production Validation--**Files:**-- Verify: `web/app/components/MessageThread.vue`-- Verify: `web/app/stores/threads.ts`-- Verify: `web/app/pages/threads/[id]/index.vue`--**Interfaces:**-- Consumes: completed UI and archive behavior from Tasks 1 and 2-- Produces: lint-clean, production-generated frontend output--- [ ] **Step 1: Run all targeted lint checks together**--Run from `web/`:--```powershell-pnpm exec eslint app/components/MessageThread.vue app/stores/threads.ts "app/pages/threads/[id]/index.vue"-pnpm exec stylelint app/components/MessageThread.vue "app/pages/threads/[id]/index.vue"-pnpm exec prettier --check app/components/MessageThread.vue app/stores/threads.ts "app/pages/threads/[id]/index.vue"-```--Expected: all commands exit with code 0.--- [ ] **Step 2: Generate the production static site**--Run from `web/`:--```powershell-pnpm generate-```--Expected: Nuxt generation completes successfully and writes the static output.--- [ ] **Step 3: Check the final diff**--Run from the repository root:--```powershell-git diff main...HEAD --check-git status --short-```--Expected: no whitespace errors and a clean working tree.diff --git a/docs/superpowers/plans/2026-07-18-read-receipts.md b/docs/superpowers/plans/2026-07-18-read-receipts.mddeleted file mode 100644index 1887a151..00000000--- a/docs/superpowers/plans/2026-07-18-read-receipts.md+++ /dev/null@@ -1,1760 +0,0 @@-# Message Thread Read Receipts Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Persist message-thread read state, mark inbound SMS and missed calls unread, automatically mark opened threads read, and highlight unread threads in the web UI.--**Architecture:** Store `is_read` plus an internal `last_read_at` watermark on each message thread. Replace full-row thread saves with field-scoped GORM updates so concurrent event listeners cannot overwrite a newer read action; inbound updates compare CloudEvent creation time against the stored watermark. Extend the existing thread update endpoint with optional archive/read fields, then have the Nuxt store call it automatically when the thread page opens or refreshes after inbound realtime events.--**Tech Stack:** Go 1.25, Fiber v3, GORM/PostgreSQL, CloudEvents, Pusher, Nuxt 4 SPA, Vue 3, Pinia, Vuetify 4, TypeScript.--## Global Constraints--- Work only in `C:\Users\achoa\Work\NdoleStudio\httpsms-read-receipts` on branch `feat/read-receipts`, based on `origin/main`.-- Existing message threads must migrate as read.-- Only incoming SMS and missed-call activity marks a thread unread.-- Outbound messages and delivery/status events preserve the existing read state.-- Opening a thread marks it read automatically; inbound activity while it is open must leave it read.-- Do not add a new endpoint or a manual read/unread control.-- Use the existing `PUT /v1/message-threads/{messageThreadID}` endpoint with optional `is_archived` and `is_read`.-- Use GORM query builders with `WithContext(ctx)`; do not use raw SQL.-- Wrap API errors with `stacktrace.Propagate`/`PropagateWithCode`.-- Web code uses single quotes, no semicolons, and 2-space indentation.-- Every commit must end with:--```text-Co-authored-by: Copilot <[email protected]>-Copilot-Session: bf00a0ac-e11f-4015-b295-3cdd9b491229-```--- Add end-to-end coverage in the existing `tests/` integration project.--## File Structure--- `api/pkg/entities/message_thread.go`: persisted read fields.-- `api/pkg/entities/message_thread_test.go`: schema-default regression tests.-- `api/pkg/repositories/message_thread_repository.go`: field-scoped update parameter types and interface methods.-- `api/pkg/repositories/gorm_message_thread_repository.go`: transactional activity updates, conditional unread transition, partial user-status update, and partial deleted-message update.-- `api/pkg/repositories/gorm_message_thread_repository_test.go`: update-map ownership tests.-- `api/pkg/services/message_thread_service.go`: read-state business rules and repository orchestration.-- `api/pkg/services/message_thread_service_test.go`: service behavior with a repository stub.-- `api/pkg/requests/message_thread_update_request.go`: optional archive/read request fields.-- `api/pkg/requests/message_thread_update_request_test.go`: request-to-service conversion tests.-- `api/pkg/validators/message_thread_handler_validator.go`: require at least one update field.-- `api/pkg/validators/message_thread_handler_validator_test.go`: empty-payload and valid-payload tests.-- `api/pkg/responses/message_thead_responses.go`: single-thread Swagger response.-- `api/pkg/handlers/message_thread_handler.go`: not-found mapping and corrected Swagger response.-- `api/pkg/listeners/message_thread_listener.go`: incoming SMS and missed-call unread updates.-- `api/pkg/listeners/websocket_listener.go`: missed-call Pusher publication.-- `api/pkg/listeners/read_receipts_test_helpers_test.go`: listener logger and repository test doubles.-- `api/pkg/listeners/message_thread_listener_test.go`: listener route and payload tests.-- `api/pkg/listeners/websocket_listener_test.go`: missed-call route registration test.-- `api/docs/docs.go`, `api/docs/swagger.json`, `api/docs/swagger.yaml`: regenerated API documentation.-- `web/shared/types/api.ts`: regenerated thread/request types.-- `web/app/stores/threads.ts`: automatic read update and local state replacement.-- `web/app/pages/threads/[id]/index.vue`: non-blocking read calls and missed-call realtime refresh.-- `web/app/components/MessageThread.vue`: unread visual treatment.-- `tests/read_receipts_test.go`: Docker-stack read/unread lifecycle coverage.-- `tests/README.md`: integration coverage documentation.-------### Task 1: Add the read-state API contract--**Files:**--- Modify: `api/pkg/entities/message_thread.go`-- Create: `api/pkg/entities/message_thread_test.go`-- Modify: `api/pkg/requests/message_thread_update_request.go`-- Create: `api/pkg/requests/message_thread_update_request_test.go`-- Modify: `api/pkg/validators/message_thread_handler_validator.go`-- Create: `api/pkg/validators/message_thread_handler_validator_test.go`-- Modify: `api/pkg/responses/message_thead_responses.go`-- Modify: `api/pkg/services/message_thread_service.go`--**Interfaces:**--- Produces: `MessageThread.IsRead bool`, `MessageThread.LastReadAt time.Time`-- Produces: `MessageThreadUpdate.IsArchived *bool`, `MessageThreadUpdate.IsRead *bool`-- Produces: `MessageThreadStatusParams.IsArchived *bool`, `MessageThreadStatusParams.IsRead *bool`-- Produces: `responses.MessageThreadResponse`--- [ ] **Step 1: Write failing entity schema tests**--Create `api/pkg/entities/message_thread_test.go`:--```go-package entities--import (- "reflect"- "testing"-- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--func TestMessageThreadReadFieldsHaveBackwardCompatibleDefaults(t *testing.T) {- threadType := reflect.TypeOf(MessageThread{})-- isRead, ok := threadType.FieldByName("IsRead")- require.True(t, ok)- assert.Contains(t, isRead.Tag.Get("gorm"), "not null")- assert.Contains(t, isRead.Tag.Get("gorm"), "default:true")- assert.Equal(t, "is_read", isRead.Tag.Get("json"))-- lastReadAt, ok := threadType.FieldByName("LastReadAt")- require.True(t, ok)- assert.Contains(t, lastReadAt.Tag.Get("gorm"), "not null")- assert.Contains(t, lastReadAt.Tag.Get("gorm"), "default:CURRENT_TIMESTAMP")- assert.Equal(t, "-", lastReadAt.Tag.Get("json"))-}-```--- [ ] **Step 2: Write failing request and validator tests**--Create `api/pkg/requests/message_thread_update_request_test.go`:--```go-package requests--import (- "testing"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/google/uuid"- "github.com/stretchr/testify/assert"-)--func TestMessageThreadUpdateToUpdateParamsPreservesOptionalFields(t *testing.T) {- threadID := uuid.New()- isRead := true- input := MessageThreadUpdate{- MessageThreadID: threadID.String(),- IsRead: &isRead,- }-- params := input.ToUpdateParams(entities.UserID("user-id"))-- assert.Equal(t, threadID, params.MessageThreadID)- assert.Equal(t, entities.UserID("user-id"), params.UserID)- assert.Nil(t, params.IsArchived)- assert.Same(t, &isRead, params.IsRead)-}-```--Create `api/pkg/validators/message_thread_handler_validator_test.go`:--```go-package validators--import (- "context"- "testing"-- "github.com/NdoleStudio/httpsms/pkg/requests"- "github.com/google/uuid"- "github.com/stretchr/testify/assert"-)--func TestValidateUpdateRequiresAtLeastOneStatusField(t *testing.T) {- validator := &MessageThreadHandlerValidator{}- request := requests.MessageThreadUpdate{- MessageThreadID: uuid.NewString(),- }-- errors := validator.ValidateUpdate(context.Background(), request)-- assert.NotEmpty(t, errors.Get("payload"))-}--func TestValidateUpdateAcceptsReadOnlyUpdate(t *testing.T) {- validator := &MessageThreadHandlerValidator{}- isRead := true- request := requests.MessageThreadUpdate{- MessageThreadID: uuid.NewString(),- IsRead: &isRead,- }-- errors := validator.ValidateUpdate(context.Background(), request)-- assert.Empty(t, errors)-}-```--- [ ] **Step 3: Run the focused tests and confirm they fail**--Run:--```powershell-Set-Location 'C:\Users\achoa\Work\NdoleStudio\httpsms-read-receipts\api'-go test ./pkg/entities ./pkg/requests ./pkg/validators-```--Expected: compile failures because the read fields and optional request fields do not exist.--- [ ] **Step 4: Add the persisted fields and optional request contract**--Add to `entities.MessageThread` after `IsArchived`:--```go-IsRead bool `json:"is_read" gorm:"not null;default:true" example:"true"`-LastReadAt time.Time `json:"-" gorm:"not null;default:CURRENT_TIMESTAMP"`-```--Change `requests.MessageThreadUpdate` and its conversion:--```go-type MessageThreadUpdate struct {- request- IsArchived *bool `json:"is_archived,omitempty" example:"true"`- IsRead *bool `json:"is_read,omitempty" example:"true"`-- MessageThreadID string `json:"messageThreadID" swaggerignore:"true"`-}--func (input *MessageThreadUpdate) ToUpdateParams(userID entities.UserID) services.MessageThreadStatusParams {- return services.MessageThreadStatusParams{- UserID: userID,- MessageThreadID: uuid.MustParse(input.MessageThreadID),- IsArchived: input.IsArchived,- IsRead: input.IsRead,- }-}-```--Change the service parameter type:--```go-type MessageThreadStatusParams struct {- IsArchived *bool- IsRead *bool- UserID entities.UserID- MessageThreadID uuid.UUID-}-```--After `v.ValidateStruct()` in `ValidateUpdate`, add an explicit payload check:--```go-errors := v.ValidateStruct()-if request.IsArchived == nil && request.IsRead == nil {- errors.Add("payload", "at least one of is_archived or is_read is required")-}-return errors-```--Add a single-thread response beside `MessageThreadsResponse`:--```go-// MessageThreadResponse is the payload containing entities.MessageThread-type MessageThreadResponse struct {- response- Data entities.MessageThread `json:"data"`-}-```--- [ ] **Step 5: Run focused tests**--Run:--```powershell-go test ./pkg/entities ./pkg/requests ./pkg/validators-```--Expected: PASS.--- [ ] **Step 6: Commit the contract**--```powershell-git add api/pkg/entities/message_thread.go api/pkg/entities/message_thread_test.go api/pkg/requests/message_thread_update_request.go api/pkg/requests/message_thread_update_request_test.go api/pkg/validators/message_thread_handler_validator.go api/pkg/validators/message_thread_handler_validator_test.go api/pkg/responses/message_thead_responses.go api/pkg/services/message_thread_service.go-@'-feat(api): add thread read state contract--Co-authored-by: Copilot <[email protected]>-Copilot-Session: bf00a0ac-e11f-4015-b295-3cdd9b491229-'@ | git commit -F --```--### Task 2: Add atomic thread persistence operations--**Files:**--- Modify: `api/pkg/repositories/message_thread_repository.go`-- Modify: `api/pkg/repositories/gorm_message_thread_repository.go`-- Create: `api/pkg/repositories/gorm_message_thread_repository_test.go`--**Interfaces:**--- Produces: `repositories.MessageThreadActivityUpdate`-- Produces: `repositories.MessageThreadStatusUpdate`-- Produces: `repositories.MessageThreadDeletedUpdate`-- Produces: `MessageThreadRepository.UpdateActivity`, `UpdateStatus`, `UpdateAfterDeletedMessage`-- Removes: `MessageThreadRepository.Update`--- [ ] **Step 1: Write failing update-map ownership tests**--Create `api/pkg/repositories/gorm_message_thread_repository_test.go`:--```go-package repositories--import (- "testing"- "time"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/google/uuid"- "github.com/stretchr/testify/assert"-)--func TestMessageThreadActivityUpdatesOwnOnlyMessageColumns(t *testing.T) {- messageID := uuid.New()- updates := messageThreadActivityUpdates(MessageThreadActivityUpdate{- Timestamp: time.Date(2026, 7, 18, 7, 0, 0, 0, time.UTC),- MessageID: messageID,- Content: "hello",- Status: entities.MessageStatusReceived,- })-- assert.Equal(t, map[string]any{- "order_timestamp": time.Date(2026, 7, 18, 7, 0, 0, 0, time.UTC),- "last_message_id": messageID,- "last_message_content": "hello",- "status": entities.MessageStatusReceived,- }, updates)- assert.NotContains(t, updates, "is_read")- assert.NotContains(t, updates, "is_archived")- assert.NotContains(t, updates, "last_read_at")-}--func TestMessageThreadStatusUpdatesReadOnly(t *testing.T) {- isRead := true- readAt := time.Date(2026, 7, 18, 7, 1, 0, 0, time.UTC)-- updates := messageThreadStatusUpdates(MessageThreadStatusUpdate{- IsRead: &isRead,- ReadAt: readAt,- })-- assert.Equal(t, map[string]any{- "is_read": true,- "last_read_at": readAt,- }, updates)- assert.NotContains(t, updates, "is_archived")-}--func TestMessageThreadStatusUpdatesArchiveOnly(t *testing.T) {- isArchived := true-- updates := messageThreadStatusUpdates(MessageThreadStatusUpdate{- IsArchived: &isArchived,- })-- assert.Equal(t, map[string]any{"is_archived": true}, updates)- assert.NotContains(t, updates, "is_read")- assert.NotContains(t, updates, "last_read_at")-}-```--- [ ] **Step 2: Run the repository test and confirm it fails**--Run:--```powershell-go test ./pkg/repositories -run MessageThread -v-```--Expected: compile failures because the parameter types and helper functions do not exist.--- [ ] **Step 3: Define repository update parameters and methods**--In `message_thread_repository.go`, add:--```go-type MessageThreadActivityUpdate struct {- MessageThreadID uuid.UUID- UserID entities.UserID- Timestamp time.Time- MessageID uuid.UUID- Content string- Status entities.MessageStatus- MarksUnread bool- EventTimestamp time.Time-}--type MessageThreadStatusUpdate struct {- IsArchived *bool- IsRead *bool- ReadAt time.Time-}--type MessageThreadDeletedUpdate struct {- MessageThreadID uuid.UUID- UserID entities.UserID- LastMessageID *uuid.UUID- LastMessageContent *string- LastMessageStatus entities.MessageStatus-}-```--Add the `time` import. Replace `Update` and the old deleted-message method in the interface with:--```go-UpdateActivity(ctx context.Context, params MessageThreadActivityUpdate) error-UpdateStatus(ctx context.Context, userID entities.UserID, messageThreadID uuid.UUID, params MessageThreadStatusUpdate) error-UpdateAfterDeletedMessage(ctx context.Context, params MessageThreadDeletedUpdate) error-```--- [ ] **Step 4: Implement field-scoped GORM updates**--Add these helpers to `gorm_message_thread_repository.go`:--```go-func messageThreadActivityUpdates(params MessageThreadActivityUpdate) map[string]any {- return map[string]any{- "order_timestamp": params.Timestamp,- "last_message_id": params.MessageID,- "last_message_content": params.Content,- "status": params.Status,- }-}--func messageThreadStatusUpdates(params MessageThreadStatusUpdate) map[string]any {- updates := make(map[string]any)- if params.IsArchived != nil {- updates["is_archived"] = *params.IsArchived- }- if params.IsRead != nil {- updates["is_read"] = *params.IsRead- if *params.IsRead {- updates["last_read_at"] = params.ReadAt- }- }- return updates-}-```--Replace the full-row `Update` implementation with:--```go-func (repository *gormMessageThreadRepository) UpdateActivity(ctx context.Context, params MessageThreadActivityUpdate) error {- ctx, span := repository.tracer.Start(ctx)- defer span.End()-- err := repository.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {- query := tx.Model(&entities.MessageThread{}).- Where("user_id = ?", params.UserID).- Where("id = ?", params.MessageThreadID)-- result := query.Updates(messageThreadActivityUpdates(params))- if result.Error != nil {- return result.Error- }- if result.RowsAffected == 0 {- return stacktrace.PropagateWithCode(- gorm.ErrRecordNotFound,- ErrCodeNotFound,- fmt.Sprintf("thread with id [%s] not found", params.MessageThreadID),- )- }-- if !params.MarksUnread {- return nil- }-- return tx.Model(&entities.MessageThread{}).- Where("user_id = ?", params.UserID).- Where("id = ?", params.MessageThreadID).- Where("last_read_at < ?", params.EventTimestamp).- Update("is_read", false).- Error- })- if err != nil {- msg := fmt.Sprintf("cannot update message activity for thread [%s]", params.MessageThreadID)- return repository.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, stacktrace.GetCode(err), msg))- }- return nil-}--func (repository *gormMessageThreadRepository) UpdateStatus(- ctx context.Context,- userID entities.UserID,- messageThreadID uuid.UUID,- params MessageThreadStatusUpdate,-) error {- ctx, span := repository.tracer.Start(ctx)- defer span.End()-- result := repository.db.WithContext(ctx).- Model(&entities.MessageThread{}).- Where("user_id = ?", userID).- Where("id = ?", messageThreadID).- Updates(messageThreadStatusUpdates(params))- if result.Error != nil {- msg := fmt.Sprintf("cannot update status for thread [%s]", messageThreadID)- return repository.tracer.WrapErrorSpan(span, stacktrace.Propagate(result.Error, msg))- }- if result.RowsAffected == 0 {- msg := fmt.Sprintf("thread with id [%s] not found", messageThreadID)- return repository.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(gorm.ErrRecordNotFound, ErrCodeNotFound, msg))- }- return nil-}--func (repository *gormMessageThreadRepository) UpdateAfterDeletedMessage(ctx context.Context, params MessageThreadDeletedUpdate) error {- ctx, span := repository.tracer.Start(ctx)- defer span.End()-- result := repository.db.WithContext(ctx).- Model(&entities.MessageThread{}).- Where("user_id = ?", params.UserID).- Where("id = ?", params.MessageThreadID).- Updates(map[string]any{- "last_message_id": params.LastMessageID,- "last_message_content": params.LastMessageContent,- "status": params.LastMessageStatus,- })- if result.Error != nil {- msg := fmt.Sprintf("cannot update deleted-message metadata for thread [%s]", params.MessageThreadID)- return repository.tracer.WrapErrorSpan(span, stacktrace.Propagate(result.Error, msg))- }- return nil-}-```--Delete the old `Save(thread)` method and the old unused `UpdateAfterDeletedMessage(userID, messageID)` implementation.--- [ ] **Step 5: Run repository tests**--Run:--```powershell-go test ./pkg/repositories -run MessageThread -v-```--Expected: PASS.--- [ ] **Step 6: Commit atomic persistence**--```powershell-git add api/pkg/repositories/message_thread_repository.go api/pkg/repositories/gorm_message_thread_repository.go api/pkg/repositories/gorm_message_thread_repository_test.go-@'-refactor(api): make thread updates atomic--Co-authored-by: Copilot <[email protected]>-Copilot-Session: bf00a0ac-e11f-4015-b295-3cdd9b491229-'@ | git commit -F --```--### Task 3: Apply read rules in services and listeners--**Files:**--- Modify: `api/pkg/services/message_thread_service.go`-- Create: `api/pkg/services/message_thread_service_test.go`-- Modify: `api/pkg/listeners/message_thread_listener.go`-- Create: `api/pkg/listeners/read_receipts_test_helpers_test.go`-- Create: `api/pkg/listeners/message_thread_listener_test.go`-- Modify: `api/pkg/listeners/websocket_listener.go`-- Create: `api/pkg/listeners/websocket_listener_test.go`--**Interfaces:**--- Consumes: repository update types and methods from Task 2.-- Produces: `MessageThreadUpdateParams.MarksUnread bool`-- Produces: `MessageThreadUpdateParams.EventTimestamp time.Time`-- Produces: missed-call thread and websocket listeners.--- [ ] **Step 1: Write failing service behavior tests**--Create `api/pkg/services/message_thread_service_test.go`. Implement a repository stub with all interface methods returning zero values by default and function hooks for the methods under test:--```go-package services--import (- "context"- "testing"- "time"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/repositories"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/google/uuid"- "github.com/palantir/stacktrace"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"- "gorm.io/gorm"-)--type messageThreadRepositoryStub struct {- loadByOwnerContact func(context.Context, entities.UserID, string, string) (*entities.MessageThread, error)- load func(context.Context, entities.UserID, uuid.UUID) (*entities.MessageThread, error)- store func(context.Context, *entities.MessageThread) error- updateActivity func(context.Context, repositories.MessageThreadActivityUpdate) error- updateStatus func(context.Context, entities.UserID, uuid.UUID, repositories.MessageThreadStatusUpdate) error-}--func (stub *messageThreadRepositoryStub) Store(ctx context.Context, thread *entities.MessageThread) error {- if stub.store != nil {- return stub.store(ctx, thread)- }- return nil-}--func (stub *messageThreadRepositoryStub) UpdateActivity(ctx context.Context, params repositories.MessageThreadActivityUpdate) error {- if stub.updateActivity != nil {- return stub.updateActivity(ctx, params)- }- return nil-}--func (stub *messageThreadRepositoryStub) UpdateStatus(ctx context.Context, userID entities.UserID, threadID uuid.UUID, params repositories.MessageThreadStatusUpdate) error {- if stub.updateStatus != nil {- return stub.updateStatus(ctx, userID, threadID, params)- }- return nil-}--func (stub *messageThreadRepositoryStub) UpdateAfterDeletedMessage(context.Context, repositories.MessageThreadDeletedUpdate) error {- return nil-}--func (stub *messageThreadRepositoryStub) LoadByOwnerContact(ctx context.Context, userID entities.UserID, owner string, contact string) (*entities.MessageThread, error) {- return stub.loadByOwnerContact(ctx, userID, owner, contact)-}--func (stub *messageThreadRepositoryStub) Load(ctx context.Context, userID entities.UserID, id uuid.UUID) (*entities.MessageThread, error) {- return stub.load(ctx, userID, id)-}--func (stub *messageThreadRepositoryStub) Index(context.Context, entities.UserID, string, bool, repositories.IndexParams) (*[]entities.MessageThread, error) {- threads := []entities.MessageThread{}- return &threads, nil-}--func (stub *messageThreadRepositoryStub) Delete(context.Context, entities.UserID, uuid.UUID) error {- return nil-}--func (stub *messageThreadRepositoryStub) DeleteAllForUser(context.Context, entities.UserID) error {- return nil-}--func newMessageThreadServiceForTest(repository repositories.MessageThreadRepository) *MessageThreadService {- logger := &noopLogger{}- tracer := telemetry.NewOtelLogger("test", logger)- return NewMessageThreadService(logger, tracer, repository, nil)-}-```--Add these tests below the stub:--```go-func TestUpdateThreadPassesUnreadWatermarkForInboundActivity(t *testing.T) {- threadID := uuid.New()- eventTimestamp := time.Date(2026, 7, 18, 7, 0, 0, 0, time.UTC)- var captured repositories.MessageThreadActivityUpdate- repository := &messageThreadRepositoryStub{- loadByOwnerContact: func(context.Context, entities.UserID, string, string) (*entities.MessageThread, error) {- return &entities.MessageThread{ID: threadID}, nil- },- updateActivity: func(_ context.Context, params repositories.MessageThreadActivityUpdate) error {- captured = params- return nil- },- }-- service := newMessageThreadServiceForTest(repository)- err := service.UpdateThread(context.Background(), MessageThreadUpdateParams{- UserID: entities.UserID("user-id"),- Owner: "+18005550199",- Contact: "+18005550100",- MessageID: uuid.New(),- Content: "hello",- Status: entities.MessageStatusReceived,- Timestamp: eventTimestamp,- MarksUnread: true,- EventTimestamp: eventTimestamp,- })-- require.NoError(t, err)- assert.True(t, captured.MarksUnread)- assert.Equal(t, eventTimestamp, captured.EventTimestamp)-}--func TestUpdateThreadPreservesReadStateForOutboundActivity(t *testing.T) {- var captured repositories.MessageThreadActivityUpdate- repository := &messageThreadRepositoryStub{- loadByOwnerContact: func(context.Context, entities.UserID, string, string) (*entities.MessageThread, error) {- return &entities.MessageThread{ID: uuid.New(), IsRead: false}, nil- },- updateActivity: func(_ context.Context, params repositories.MessageThreadActivityUpdate) error {- captured = params- return nil- },- }-- service := newMessageThreadServiceForTest(repository)- err := service.UpdateThread(context.Background(), MessageThreadUpdateParams{- UserID: entities.UserID("user-id"),- Owner: "+18005550199",- Contact: "+18005550100",- MessageID: uuid.New(),- Content: "outbound",- Status: entities.MessageStatusSent,- Timestamp: time.Now().UTC(),- })-- require.NoError(t, err)- assert.False(t, captured.MarksUnread)-}--func TestCreateThreadSetsReadStateFromActivityDirection(t *testing.T) {- tests := []struct {- name string- marksUnread bool- wantRead bool- }{- {name: "inbound", marksUnread: true, wantRead: false},- {name: "outbound", marksUnread: false, wantRead: true},- }-- for _, test := range tests {- t.Run(test.name, func(t *testing.T) {- var stored *entities.MessageThread- repository := &messageThreadRepositoryStub{- loadByOwnerContact: func(context.Context, entities.UserID, string, string) (*entities.MessageThread, error) {- return nil, stacktrace.PropagateWithCode(gorm.ErrRecordNotFound, repositories.ErrCodeNotFound, "not found")- },- store: func(_ context.Context, thread *entities.MessageThread) error {- stored = thread- return nil- },- }-- service := newMessageThreadServiceForTest(repository)- err := service.UpdateThread(context.Background(), MessageThreadUpdateParams{- UserID: entities.UserID("user-id"),- Owner: "+18005550199",- Contact: "+18005550100",- MessageID: uuid.New(),- Content: "hello",- Status: entities.MessageStatusReceived,- Timestamp: time.Now().UTC(),- MarksUnread: test.marksUnread,- })-- require.NoError(t, err)- require.NotNil(t, stored)- assert.Equal(t, test.wantRead, stored.IsRead)- assert.False(t, stored.LastReadAt.IsZero())- })- }-}--func TestUpdateStatusChangesOnlyRequestedState(t *testing.T) {- threadID := uuid.New()- isRead := true- var captured repositories.MessageThreadStatusUpdate- repository := &messageThreadRepositoryStub{- updateStatus: func(_ context.Context, _ entities.UserID, _ uuid.UUID, params repositories.MessageThreadStatusUpdate) error {- captured = params- return nil- },- load: func(context.Context, entities.UserID, uuid.UUID) (*entities.MessageThread, error) {- return &entities.MessageThread{ID: threadID, IsArchived: true, IsRead: true}, nil- },- }-- service := newMessageThreadServiceForTest(repository)- thread, err := service.UpdateStatus(context.Background(), MessageThreadStatusParams{- UserID: entities.UserID("user-id"),- MessageThreadID: threadID,- IsRead: &isRead,- })-- require.NoError(t, err)- assert.Nil(t, captured.IsArchived)- assert.Same(t, &isRead, captured.IsRead)- assert.False(t, captured.ReadAt.IsZero())- assert.True(t, thread.IsArchived)-}--func TestUpdateStatusPreservesNotFoundCode(t *testing.T) {- repository := &messageThreadRepositoryStub{- updateStatus: func(context.Context, entities.UserID, uuid.UUID, repositories.MessageThreadStatusUpdate) error {- return stacktrace.PropagateWithCode(gorm.ErrRecordNotFound, repositories.ErrCodeNotFound, "not found")- },- }-- service := newMessageThreadServiceForTest(repository)- isRead := true- _, err := service.UpdateStatus(context.Background(), MessageThreadStatusParams{- UserID: entities.UserID("user-id"),- MessageThreadID: uuid.New(),- IsRead: &isRead,- })-- assert.Equal(t, repositories.ErrCodeNotFound, stacktrace.GetCode(err))-}-```--- [ ] **Step 2: Run service tests and confirm they fail**--Run:--```powershell-go test ./pkg/services -run 'Test(UpdateThread|CreateThread|UpdateStatus)' -v-```--Expected: compile failures because the new update parameters and repository calls are not wired.--- [ ] **Step 3: Implement service read rules**--Extend `MessageThreadUpdateParams`:--```go-MarksUnread bool-EventTimestamp time.Time-```--Replace the existing full-row update in `UpdateThread` with:--```go-if err = service.repository.UpdateActivity(ctx, repositories.MessageThreadActivityUpdate{- MessageThreadID: thread.ID,- UserID: params.UserID,- Timestamp: params.Timestamp,- MessageID: params.MessageID,- Content: params.Content,- Status: params.Status,- MarksUnread: params.MarksUnread,- EventTimestamp: params.EventTimestamp,-}); 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.PropagateWithCode(err, stacktrace.GetCode(err), msg))-}-```--In `createThread`, create one `now := time.Now().UTC()` and initialize:--```go-IsRead: !params.MarksUnread,-LastReadAt: now,-CreatedAt: now,-UpdatedAt: now,-```--Replace `UpdateStatus` with a partial repository update followed by a reload:--```go-func (service *MessageThreadService) UpdateStatus(ctx context.Context, params MessageThreadStatusParams) (*entities.MessageThread, error) {- ctx, span := service.tracer.Start(ctx)- defer span.End()-- update := repositories.MessageThreadStatusUpdate{- IsArchived: params.IsArchived,- IsRead: params.IsRead,- ReadAt: time.Now().UTC(),- }- if err := service.repository.UpdateStatus(ctx, params.UserID, params.MessageThreadID, update); err != nil {- msg := fmt.Sprintf("cannot update message thread with id [%s]", params.MessageThreadID)- return nil, service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, stacktrace.GetCode(err), msg))- }-- thread, err := service.repository.Load(ctx, params.UserID, params.MessageThreadID)- if err != nil {- msg := fmt.Sprintf("cannot reload message thread with id [%s]", params.MessageThreadID)- return nil, service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, stacktrace.GetCode(err), msg))- }- return thread, nil-}-```--In `UpdateAfterDeletedMessage`, replace the full-row update with:--```go-if err = service.repository.UpdateAfterDeletedMessage(ctx, repositories.MessageThreadDeletedUpdate{- MessageThreadID: thread.ID,- UserID: thread.UserID,- LastMessageID: payload.PreviousMessageID,- LastMessageContent: payload.PreviousMessageContent,- LastMessageStatus: *payload.PreviousMessageStatus,-}); err != nil {- msg := fmt.Sprintf("cannot update thread with ID [%s] for user with ID [%s]", thread.ID, thread.UserID)- return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))-}-```--- [ ] **Step 4: Add inbound and missed-call listener behavior**--In `NewMessageThreadListener`, register:--```go-events.MessageCallMissed: l.OnMessageCallMissed,-```--In `OnMessagePhoneReceived`, add:--```go-MarksUnread: true,-EventTimestamp: event.Time(),-```--Add:--```go-func (listener *MessageThreadListener) OnMessageCallMissed(ctx context.Context, event cloudevents.Event) error {- ctx, span := listener.tracer.Start(ctx)- defer span.End()-- var payload events.MessageCallMissedPayload- if err := event.DataAs(&payload); err != nil {- msg := fmt.Sprintf("cannot decode [%s] into [%T]", event.Data(), payload)- return listener.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))- }-- params := services.MessageThreadUpdateParams{- Owner: payload.Owner,- Contact: payload.Contact,- UserID: payload.UserID,- Status: entities.MessageStatusReceived,- Timestamp: payload.Timestamp,- Content: "Missed phone call",- MessageID: payload.MessageID,- MarksUnread: true,- EventTimestamp: event.Time(),- }- if err := listener.service.UpdateThread(ctx, params); err != nil {- msg := fmt.Sprintf("cannot update thread for missed call [%s] on event [%s]", payload.MessageID, event.ID())- return listener.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))- }- return nil-}-```--In `NewWebsocketListener`, register:--```go-events.MessageCallMissed: l.onMessageCallMissed,-```--Add:--```go-func (listener *WebsocketListener) onMessageCallMissed(ctx context.Context, event cloudevents.Event) error {- ctx, span, _ := listener.tracer.StartWithLogger(ctx, listener.logger)- defer span.End()-- var payload events.MessageCallMissedPayload- if err := event.DataAs(&payload); err != nil {- msg := fmt.Sprintf("cannot decode [%s] into [%T]", event.Data(), payload)- return listener.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))- }-- if err := listener.client.Trigger(payload.UserID.String(), event.Type(), event.ID()); err != nil {- msg := fmt.Sprintf("cannot trigger websocket [%s] event with ID [%s] for user with ID [%s]", event.Type(), event.ID(), payload.UserID)- return listener.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))- }- return nil-}-```--- [ ] **Step 5: Add listener tests**--Create `api/pkg/listeners/read_receipts_test_helpers_test.go`:--```go-package listeners--import (- "context"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/repositories"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/google/uuid"- "go.opentelemetry.io/otel/trace"-)--type noopListenerLogger struct{}--func (logger *noopListenerLogger) Error(error) {}-func (logger *noopListenerLogger) WithService(string) telemetry.Logger { return logger }-func (logger *noopListenerLogger) WithString(string, string) telemetry.Logger { return logger }-func (logger *noopListenerLogger) WithSpan(trace.SpanContext) telemetry.Logger { return logger }-func (logger *noopListenerLogger) Trace(string) {}-func (logger *noopListenerLogger) Info(string) {}-func (logger *noopListenerLogger) Warn(error) {}-func (logger *noopListenerLogger) Debug(string) {}-func (logger *noopListenerLogger) Fatal(error) {}-func (logger *noopListenerLogger) Printf(string, ...interface{}) {}--type listenerMessageThreadRepository struct {- activity repositories.MessageThreadActivityUpdate-}--func (repository *listenerMessageThreadRepository) Store(context.Context, *entities.MessageThread) error {- return nil-}--func (repository *listenerMessageThreadRepository) UpdateActivity(_ context.Context, params repositories.MessageThreadActivityUpdate) error {- repository.activity = params- return nil-}--func (repository *listenerMessageThreadRepository) UpdateStatus(context.Context, entities.UserID, uuid.UUID, repositories.MessageThreadStatusUpdate) error {- return nil-}--func (repository *listenerMessageThreadRepository) UpdateAfterDeletedMessage(context.Context, repositories.MessageThreadDeletedUpdate) error {- return nil-}--func (repository *listenerMessageThreadRepository) LoadByOwnerContact(context.Context, entities.UserID, string, string) (*entities.MessageThread, error) {- return &entities.MessageThread{ID: uuid.New()}, nil-}--func (repository *listenerMessageThreadRepository) Load(context.Context, entities.UserID, uuid.UUID) (*entities.MessageThread, error) {- return &entities.MessageThread{}, nil-}--func (repository *listenerMessageThreadRepository) Index(context.Context, entities.UserID, string, bool, repositories.IndexParams) (*[]entities.MessageThread, error) {- threads := []entities.MessageThread{}- return &threads, nil-}--func (repository *listenerMessageThreadRepository) Delete(context.Context, entities.UserID, uuid.UUID) error {- return nil-}--func (repository *listenerMessageThreadRepository) DeleteAllForUser(context.Context, entities.UserID) error {- return nil-}-```--Create `api/pkg/listeners/message_thread_listener_test.go`:--```go-package listeners--import (- "context"- "testing"- "time"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/events"- "github.com/NdoleStudio/httpsms/pkg/services"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- cloudevents "github.com/cloudevents/sdk-go/v2"- "github.com/google/uuid"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--func TestMessageThreadListenerMarksMissedCallUnread(t *testing.T) {- repository := &listenerMessageThreadRepository{}- logger := &noopListenerLogger{}- tracer := telemetry.NewOtelLogger("test", logger)- service := services.NewMessageThreadService(logger, tracer, repository, nil)- _, routes := NewMessageThreadListener(logger, tracer, service)-- event := cloudevents.NewEvent()- event.SetID(uuid.NewString())- event.SetSource("/v1/messages/call-missed")- event.SetType(events.MessageCallMissed)- event.SetTime(time.Date(2026, 7, 18, 7, 0, 0, 0, time.UTC))- require.NoError(t, event.SetData(cloudevents.ApplicationJSON, events.MessageCallMissedPayload{- MessageID: uuid.New(),- UserID: entities.UserID("user-id"),- Owner: "+18005550199",- Contact: "+18005550100",- Timestamp: time.Date(2026, 7, 18, 6, 59, 0, 0, time.UTC),- }))-- err := routes[events.MessageCallMissed](context.Background(), event)-- require.NoError(t, err)- assert.True(t, repository.activity.MarksUnread)- assert.Equal(t, "Missed phone call", repository.activity.Content)- assert.Equal(t, event.Time(), repository.activity.EventTimestamp)-}-```--Create `api/pkg/listeners/websocket_listener_test.go`:--```go-package listeners--import (- "testing"-- "github.com/NdoleStudio/httpsms/pkg/events"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/pusher/pusher-http-go/v5"- "github.com/stretchr/testify/assert"-)--func TestWebsocketListenerRegistersMissedCalls(t *testing.T) {- logger := &noopListenerLogger{}- tracer := telemetry.NewOtelLogger("test", logger)- _, routes := NewWebsocketListener(logger, tracer, &pusher.Client{})-- assert.Contains(t, routes, events.MessageCallMissed)-}-```--- [ ] **Step 6: Run service and listener tests**--Run:--```powershell-go test ./pkg/services ./pkg/listeners -run 'MessageThread|MissedCall|UpdateStatus|CreateThread' -v-```--Expected: PASS.--- [ ] **Step 7: Commit service and realtime behavior**--```powershell-git add api/pkg/services/message_thread_service.go api/pkg/services/message_thread_service_test.go api/pkg/listeners/message_thread_listener.go api/pkg/listeners/read_receipts_test_helpers_test.go api/pkg/listeners/message_thread_listener_test.go api/pkg/listeners/websocket_listener.go api/pkg/listeners/websocket_listener_test.go-@'-feat(api): track unread inbound threads--Co-authored-by: Copilot <[email protected]>-Copilot-Session: bf00a0ac-e11f-4015-b295-3cdd9b491229-'@ | git commit -F --```--### Task 4: Finish the HTTP behavior and regenerate Swagger--**Files:**--- Modify: `api/pkg/handlers/message_thread_handler.go`-- Modify: `api/docs/docs.go`-- Modify: `api/docs/swagger.json`-- Modify: `api/docs/swagger.yaml`--**Interfaces:**--- Consumes: `responses.MessageThreadResponse` from Task 1.-- Produces: 404 behavior for missing thread updates.-- Produces: Swagger schema fields `is_read`, optional `is_archived`, optional `is_read`.--- [ ] **Step 1: Update the handler error mapping and annotations**--Change the update annotation:--```go-// @Success 200 {object} responses.MessageThreadResponse-// @Failure 404 {object} responses.NotFound-```--Change the error block:--```go-thread, err := h.service.UpdateStatus(ctx, request.ToUpdateParams(h.userIDFomContext(c)))-if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {- return h.responseNotFound(c, fmt.Sprintf("cannot find message thread with ID [%s]", request.MessageThreadID))-}-if err != nil {- msg := fmt.Sprintf("cannot update message thread with params [%+#v]", request)- ctxLogger.Error(stacktrace.Propagate(err, msg))- return h.responseInternalServerError(c)-}-```--- [ ] **Step 2: Regenerate Swagger**--Run:--```powershell-Set-Location 'C:\Users\achoa\Work\NdoleStudio\httpsms-read-receipts\api'-swag init --requiredByDefault --parseDependency --parseInternal-```--Expected: `api/docs/docs.go`, `api/docs/swagger.json`, and `api/docs/swagger.yaml` update successfully.--- [ ] **Step 3: Run the full API suite**--Run:--```powershell-go test -vet=off ./pkg/entities ./pkg/repositories ./pkg/requests ./pkg/services ./pkg/validators ./pkg/listeners-go test -vet=off ./pkg/handlers -run '^$'-```--Expected: PASS. Vet is disabled because clean `origin/main` has unrelated Go-1.25 non-constant-format vet failures. Handler tests are compile-checked only-because the pre-existing suite expects an API server on `localhost:8000`; Task-7 provides the HTTP integration coverage against the Docker stack.--- [ ] **Step 4: Commit HTTP and documentation changes**--```powershell-git add api/pkg/handlers/message_thread_handler.go api/docs/docs.go api/docs/swagger.json api/docs/swagger.yaml-@'-docs(api): publish thread read state--Co-authored-by: Copilot <[email protected]>-Copilot-Session: bf00a0ac-e11f-4015-b295-3cdd9b491229-'@ | git commit -F --```--### Task 5: Add automatic read updates to the web store--**Files:**--- Modify: `web/shared/types/api.ts`-- Modify: `web/app/stores/threads.ts`--**Interfaces:**--- Consumes: API `PUT /v1/message-threads/{id}` with `{ is_read: true }`.-- Produces: `markThreadRead(threadId: string, force?: boolean): Promise<void>`.--- [ ] **Step 1: Regenerate TypeScript API models**--Run:--```powershell-Set-Location 'C:\Users\achoa\Work\NdoleStudio\httpsms-read-receipts\web'-pnpm api:models-```--Expected: `EntitiesMessageThread.is_read: boolean` and optional fields on `RequestsMessageThreadUpdate`.--- [ ] **Step 2: Add a typed local replacement helper**--In `web/app/stores/threads.ts`, add:--```ts-function replaceThread(updatedThread: EntitiesMessageThread) {- const index = threads.value.findIndex(- (thread) => thread.id === updatedThread.id,- );- if (index !== -1) threads.value[index] = updatedThread;-}-```--- [ ] **Step 3: Implement non-silent automatic read persistence**--Add:--```ts-async function markThreadRead(threadId: string, force = false) {- const thread = threads.value.find((item) => item.id === threadId);- if (!thread) throw new Error(`Cannot find thread with id ${threadId}`);- if (!force && thread.is_read) return;-- try {- const response = await apiFetch<{ data: EntitiesMessageThread }>(- `/v1/message-threads/${threadId}`,- {- method: "PUT",- body: { is_read: true },- },- );- replaceThread(response.data);- } catch (error) {- notificationsStore.addNotification({- message: "The message thread could not be marked as read",- type: "error",- });- await loadThreads();- throw error;- }-}-```--Add `markThreadRead` to the returned store API.--Keep archive updates independent:--```ts-body: { is_archived: payload.isArchived },-```--Do not send `is_read` from `updateThread`.--- [ ] **Step 4: Run web static checks**--Run:--```powershell-pnpm lint:js-pnpm lint:prettier-```--Expected: PASS.--- [ ] **Step 5: Commit store and generated types**--```powershell-git add web/shared/types/api.ts web/app/stores/threads.ts-@'-feat(web): persist opened threads as read--Co-authored-by: Copilot <[email protected]>-Copilot-Session: bf00a0ac-e11f-4015-b295-3cdd9b491229-'@ | git commit -F --```--### Task 6: Mark opened threads read and highlight unread threads--**Files:**--- Modify: `web/app/pages/threads/[id]/index.vue`-- Modify: `web/app/components/MessageThread.vue`--**Interfaces:**--- Consumes: `threadsStore.markThreadRead(threadId, force)`.-- Produces: automatic initial and realtime read updates.-- Produces: shared unread list styling on mobile and desktop.--- [ ] **Step 1: Make read updates independent from message loading**--In `web/app/pages/threads/[id]/index.vue`, add:--```ts-async function markCurrentThreadRead(force = false) {- const threadId = route.params.id as string;- try {- await threadsStore.markThreadRead(threadId, force);- } catch (error) {- console.error(error);- }-}-```--At the start of `loadMessages`, after computing `threadId`, call without awaiting:--```ts-void markCurrentThreadRead();-```--This lets message loading continue even if the read update fails.--- [ ] **Step 2: Force a newer read watermark after inbound realtime events**--Change the incoming SMS binding:--```ts-webhookChannel.bind("message.phone.received", () => {- if (!loadingMessages.value) {- void markCurrentThreadRead(true);- loadMessages(false);- }-});-```--Add the missed-call binding with the same behavior:--```ts-webhookChannel.bind("message.call.missed", () => {- if (!loadingMessages.value) {- void markCurrentThreadRead(true);- loadMessages(false);- }-});-```--The forced call is required because the local thread may still say `is_read:-true` when the concurrent backend listener has not committed its unread update.--- [ ] **Step 3: Add unread presentation**--In `MessageThread.vue`, add the class binding to `v-list-item`:--```vue-:class="{ 'message-thread--unread': !thread.is_read }"-```--Change title and subtitle class bindings:--```vue-<v-list-item-title :class="{ 'font-weight-bold': !thread.is_read }">- {{ formatPhoneNumber(thread.contact) }}-</v-list-item-title>-<v-list-item-subtitle- class="text-truncate mt-1"- :class="{ 'font-weight-bold': !thread.is_read }"- style="max-width: 250px"->-```--Add:--```vue-<style scoped>-.message-thread--unread {- background: rgba(var(--v-theme-primary), 0.1);-}-</style>-```--- [ ] **Step 4: Run web validation**--Run:--```powershell-Set-Location 'C:\Users\achoa\Work\NdoleStudio\httpsms-read-receipts\web'-pnpm lint-pnpm run generate-```--Expected: both commands PASS.--- [ ] **Step 5: Commit UI behavior**--```powershell-git add web/app/pages/threads/[id]/index.vue web/app/components/MessageThread.vue-@'-feat(web): highlight unread message threads--Co-authored-by: Copilot <[email protected]>-Copilot-Session: bf00a0ac-e11f-4015-b295-3cdd9b491229-'@ | git commit -F --```--### Task 7: Add integration coverage--**Files:**--- Create: `tests/read_receipts_test.go`-- Modify: `tests/README.md`--**Interfaces:**--- Consumes: thread index and update HTTP endpoints from Tasks 1-4.-- Consumes: incoming SMS, missed-call, and outbound message flows from Task 3.-- Produces: `TestMessageThreadReadReceipts`.--- [ ] **Step 1: Write the end-to-end read-receipts test**--Create `tests/read_receipts_test.go`:--```go-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 integrationMessageThread struct {- ID string `json:"id"`- Contact string `json:"contact"`- IsRead bool `json:"is_read"`- LastMessageContent *string `json:"last_message_content"`-}--func requestJSON(- ctx context.Context,- t *testing.T,- method string,- path string,- apiKey string,- payload any,- expectedStatus int,- output any,-) {- t.Helper()-- var body io.Reader- if payload != nil {- encoded, err := json.Marshal(payload)- require.NoError(t, err)- body = bytes.NewReader(encoded)- }-- request, err := http.NewRequestWithContext(ctx, method, apiBaseURL+path, body)- require.NoError(t, err)- request.Header.Set("x-api-key", apiKey)- request.Header.Set("Content-Type", "application/json")-- response, err := http.DefaultClient.Do(request)- require.NoError(t, err)- defer response.Body.Close()-- responseBody, err := io.ReadAll(response.Body)- require.NoError(t, err)- require.Equal(t, expectedStatus, response.StatusCode, "response: %s", string(responseBody))-- if output != nil {- require.NoError(t, json.Unmarshal(responseBody, output))- }-}--func fetchMessageThreads(ctx context.Context, t *testing.T, owner string) []integrationMessageThread {- t.Helper()-- var response struct {- Data []integrationMessageThread `json:"data"`- }- path := fmt.Sprintf(- "/v1/message-threads?owner=%s&skip=0&limit=20&is_archived=false",- url.QueryEscape(owner),- )- requestJSON(ctx, t, http.MethodGet, path, userAPIKey, nil, http.StatusOK, &response)- return response.Data-}--func waitForMessageThread(- ctx context.Context,- t *testing.T,- owner string,- contact string,- timeout time.Duration,- matches func(integrationMessageThread) bool,-) integrationMessageThread {- t.Helper()-- deadline := time.Now().Add(timeout)- for time.Now().Before(deadline) {- for _, thread := range fetchMessageThreads(ctx, t, owner) {- if thread.Contact == contact && matches(thread) {- return thread- }- }- time.Sleep(500 * time.Millisecond)- }-- t.Fatalf("thread %s -> %s did not reach the expected state within %v", owner, contact, timeout)- return integrationMessageThread{}-}--func markMessageThreadRead(ctx context.Context, t *testing.T, threadID string) integrationMessageThread {- t.Helper()-- var response struct {- Data integrationMessageThread `json:"data"`- }- requestJSON(- ctx,- t,- http.MethodPut,- "/v1/message-threads/"+threadID,- userAPIKey,- map[string]any{"is_read": true},- http.StatusOK,- &response,- )- return response.Data-}--func TestMessageThreadReadReceipts(t *testing.T) {- ctx := context.Background()- phone := setupPhone(ctx, t, 60)- contact := randomPhoneNumber()-- requestJSON(- ctx,- t,- http.MethodPost,- "/v1/messages/receive",- phone.PhoneAPIKey,- map[string]any{- "from": contact,- "to": phone.PhoneNumber,- "content": "Unread inbound message",- "encrypted": false,- "sim": "SIM1",- "timestamp": time.Now().UTC().Format(time.RFC3339),- },- http.StatusOK,- nil,- )-- thread := waitForMessageThread(ctx, t, phone.PhoneNumber, contact, 20*time.Second, func(thread integrationMessageThread) bool {- return !thread.IsRead- })- assert.False(t, thread.IsRead)-- updated := markMessageThreadRead(ctx, t, thread.ID)- assert.True(t, updated.IsRead)- waitForMessageThread(ctx, t, phone.PhoneNumber, contact, 10*time.Second, func(thread integrationMessageThread) bool {- return thread.IsRead- })-- requestJSON(- ctx,- t,- http.MethodPost,- "/v1/messages/calls/missed",- phone.PhoneAPIKey,- map[string]any{- "from": contact,- "to": phone.PhoneNumber,- "sim": "SIM1",- "timestamp": time.Now().UTC().Format(time.RFC3339),- },- http.StatusOK,- nil,- )-- thread = waitForMessageThread(ctx, t, phone.PhoneNumber, contact, 20*time.Second, func(thread integrationMessageThread) bool {- return !thread.IsRead &&- thread.LastMessageContent != nil &&- *thread.LastMessageContent == "Missed phone call"- })- assert.False(t, thread.IsRead)-- outboundContent := "Outbound activity preserves unread"- client := newAPIClient()- _, response, err := client.Messages.Send(ctx, &httpsms.MessageSendParams{- From: phone.PhoneNumber,- To: contact,- Content: outboundContent,- })- require.NoError(t, err)- require.Equal(t, http.StatusOK, response.HTTPResponse.StatusCode)-- thread = waitForMessageThread(ctx, t, phone.PhoneNumber, contact, 20*time.Second, func(thread integrationMessageThread) bool {- return thread.LastMessageContent != nil &&- *thread.LastMessageContent == outboundContent- })- assert.False(t, thread.IsRead, "outbound activity must not clear unread state")-}-```--- [ ] **Step 2: Run the test before implementation is complete**--With the Docker integration stack running, execute:--```powershell-Set-Location 'C:\Users\achoa\Work\NdoleStudio\httpsms-read-receipts\tests'-go test -v -timeout 120s -run TestMessageThreadReadReceipts ./...-```--Expected before the feature implementation: FAIL because thread responses do not expose/persist `is_read`.--- [ ] **Step 3: Update integration-test documentation**--Add to the Test Coverage checklist in `tests/README.md`:--```markdown-- [x] **Message thread read receipts E2E** — Incoming SMS and missed calls mark a thread unread, the existing thread update endpoint marks it read, and outbound activity preserves unread state-```--- [ ] **Step 4: Run the integration test against the completed stack**--Generate credentials, start the Docker stack, run the focused test, and tear down:--```powershell-Set-Location 'C:\Users\achoa\Work\NdoleStudio\httpsms-read-receipts\tests'-& 'C:\Program Files\Git\bin\bash.exe' generate-firebase-credentials.sh-$env:FIREBASE_CREDENTIALS = (Get-Content firebase-credentials.json -Raw | ConvertFrom-Json | ConvertTo-Json -Compress)-docker compose up -d --build --wait-docker compose wait seed-Start-Sleep -Seconds 2-try {- go test -v -timeout 120s -run TestMessageThreadReadReceipts ./...-} finally {- docker compose down -v-}-```--Expected: PASS.--- [ ] **Step 5: Commit integration coverage**--```powershell-git add tests/read_receipts_test.go tests/README.md-@'-test: cover message thread read receipts--Co-authored-by: Copilot <[email protected]>-Copilot-Session: bf00a0ac-e11f-4015-b295-3cdd9b491229-'@ | git commit -F --```--### Task 8: Verify the complete feature--**Files:**--- Review: all files changed since `origin/main`--**Interfaces:**--- Consumes: all previous tasks.-- Produces: a clean, verified feature branch.--- [ ] **Step 1: Run API formatting and tests**--Run:--```powershell-Set-Location 'C:\Users\achoa\Work\NdoleStudio\httpsms-read-receipts\api'-go-fumpt -w pkg/entities/message_thread.go pkg/entities/message_thread_test.go pkg/repositories/message_thread_repository.go pkg/repositories/gorm_message_thread_repository.go pkg/repositories/gorm_message_thread_repository_test.go pkg/services/message_thread_service.go pkg/services/message_thread_service_test.go pkg/requests/message_thread_update_request.go pkg/requests/message_thread_update_request_test.go pkg/validators/message_thread_handler_validator.go pkg/validators/message_thread_handler_validator_test.go pkg/responses/message_thead_responses.go pkg/handlers/message_thread_handler.go pkg/listeners/message_thread_listener.go pkg/listeners/read_receipts_test_helpers_test.go pkg/listeners/message_thread_listener_test.go pkg/listeners/websocket_listener.go pkg/listeners/websocket_listener_test.go-go test -vet=off ./pkg/entities ./pkg/repositories ./pkg/requests ./pkg/services ./pkg/validators ./pkg/listeners-go test -vet=off ./pkg/handlers -run '^$'-```--Expected: formatting completes and all API tests PASS.--- [ ] **Step 2: Run complete web validation**--Run:--```powershell-Set-Location 'C:\Users\achoa\Work\NdoleStudio\httpsms-read-receipts\web'-pnpm lint-pnpm run generate-```--Expected: PASS.--- [ ] **Step 3: Inspect the final diff**--Run:--```powershell-Set-Location 'C:\Users\achoa\Work\NdoleStudio\httpsms-read-receipts'-git --no-pager diff --check origin/main...HEAD-git --no-pager diff --stat origin/main...HEAD-git --no-pager status --short --branch-```--Expected: no whitespace errors and no uncommitted implementation changes.--- [ ] **Step 4: Perform manual acceptance checks against a migrated local database**--Verify:--1. Existing rows return `"is_read": true`.-2. A closed thread becomes highlighted after an incoming SMS.-3. A closed thread becomes highlighted after a missed call.-4. Opening the thread removes the highlight and refresh keeps it read.-5. Incoming activity while the thread is open does not leave it unread.-6. Sending and delivery-status changes do not clear an unread thread.-7. Archiving and unarchiving preserve read state.--- [ ] **Step 5: Commit any formatting-only corrections**--Skip this step when Step 1 produced no changes. Otherwise:--```powershell-git add api web-@'-style: format read receipts changes--Co-authored-by: Copilot <[email protected]>-Copilot-Session: bf00a0ac-e11f-4015-b295-3cdd9b491229-'@ | git commit -F --```diff --git a/docs/superpowers/plans/2026-07-18-unarchive-thread-on-receive.md b/docs/superpowers/plans/2026-07-18-unarchive-thread-on-receive.mddeleted file mode 100644index 70ec8969..00000000--- a/docs/superpowers/plans/2026-07-18-unarchive-thread-on-receive.md+++ /dev/null@@ -1,848 +0,0 @@-# Unarchive Thread on Receive Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Let an archived message thread automatically move back to the inbox when a new inbound message is received, configurable per phone number.--**Architecture:** Add a per-phone boolean `UnarchiveThread` (default false). It is copied onto the `message.phone.received` event payload when a message is received, carried through the thread listener into `MessageThreadUpdateParams`, and applied by `MessageThreadService.UpdateThread`, which clears `IsArchived` only for inbound (received) messages when the flag is true. A per-phone toggle is exposed in the web settings page.--**Tech Stack:** Go 1.x (Fiber v3, GORM, stacktrace, testify), Nuxt 4 / Vue 3 (Vuetify 4, Pinia), swaggo/swag, swagger-typescript-api.--## Global Constraints--- Field name is exactly `UnarchiveThread` (Go) / `unarchive_thread` (JSON) everywhere.-- Default value is `false` (opt-in). GORM tag: `gorm:"default:false"`.-- Only inbound messages (`entities.MessageStatusReceived`) may unarchive a thread.-- Wrap all Go errors with `github.com/palantir/stacktrace` (never return bare errors).-- Go formatting via `go-fumpt` (pre-commit). Run `go test ./...` from `api/`.-- After changing Swagger annotations run, in `api/`: `swag init --requiredByDefault --parseDependency --parseInternal`.-- After Swagger regen, regenerate web models in `web/`: `pnpm api:models`.-- Web: no semicolons, single quotes, 2-space indent (Prettier/ESLint). Lint via `pnpm lint`.-- The `docs/` directory is gitignored in this repo; this plan and its spec were committed with `git add -f`. Do NOT `-f` add source files — only the plan/spec docs need force-add.--## File Structure--- `api/pkg/entities/phone.go` — add `UnarchiveThread` field to `Phone`.-- `api/pkg/events/message_phone_received_event.go` — add `UnarchiveThread` to `MessagePhoneReceivedPayload`.-- `api/pkg/services/message_service.go` — populate `UnarchiveThread` on the received-event payload from the loaded phone.-- `api/pkg/services/message_thread_service.go` — add `UnarchiveThread` to `MessageThreadUpdateParams`; add pure helper `shouldUnarchive`; apply it in `UpdateThread`.-- `api/pkg/services/message_thread_service_test.go` — NEW unit tests for `shouldUnarchive`.-- `api/pkg/listeners/message_thread_listener.go` — pass `payload.UnarchiveThread` into params in `OnMessagePhoneReceived`.-- `api/pkg/requests/phone_update_request.go` — add `UnarchiveThread *bool` request field + partial-update mapping.-- `api/pkg/services/phone_service.go` — add `UnarchiveThread *bool` to `PhoneUpsertParams`; apply in `update`.-- `web/app/stores/phones.ts` — send `unarchive_thread` in `updatePhone` PUT body.-- `web/app/pages/settings/index.vue` — add a per-phone toggle bound to `activePhone.unarchive_thread`.-- `web/shared/types/api.ts` — regenerated (not hand-edited).-- `tests/unarchive_thread_integration_test.go` — NEW end-to-end integration test (package `tests`, runs against the live Docker stack).-------### Task 1: Add `UnarchiveThread` field to the Phone entity--**Files:**-- Modify: `api/pkg/entities/phone.go`--**Interfaces:**-- Consumes: nothing.-- Produces: `entities.Phone.UnarchiveThread bool` (JSON `unarchive_thread`).--- [ ] **Step 1: Add the field**--In `api/pkg/entities/phone.go`, inside the `Phone` struct, add the field just below `MissedCallAutoReply` (keep the existing blank-line grouping style):--```go- 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"`-```--- [ ] **Step 2: Verify it compiles**--Run (from `api/`): `go build ./...`-Expected: no output, exit code 0.--- [ ] **Step 3: Commit**--```bash-git add api/pkg/entities/phone.go-git commit -m "feat(api): add UnarchiveThread setting to Phone entity"-```-------### Task 2: Add `UnarchiveThread` to the received-message event payload--**Files:**-- Modify: `api/pkg/events/message_phone_received_event.go`--**Interfaces:**-- Consumes: nothing.-- Produces: `events.MessagePhoneReceivedPayload.UnarchiveThread bool` (JSON `unarchive_thread`).--- [ ] **Step 1: Add the field**--In `api/pkg/events/message_phone_received_event.go`, add the field to the `MessagePhoneReceivedPayload` struct (after `Attachments`):--```go-type MessagePhoneReceivedPayload struct {- MessageID uuid.UUID `json:"message_id"`- UserID entities.UserID `json:"user_id"`- Owner string `json:"owner"`- Encrypted bool `json:"encrypted"`- Contact string `json:"contact"`- Timestamp time.Time `json:"timestamp"`- Content string `json:"content"`- SIM entities.SIM `json:"sim"`- Attachments []string `json:"attachments"`- UnarchiveThread bool `json:"unarchive_thread"`-}-```--- [ ] **Step 2: Verify it compiles**--Run (from `api/`): `go build ./...`-Expected: exit code 0.--- [ ] **Step 3: Commit**--```bash-git add api/pkg/events/message_phone_received_event.go-git commit -m "feat(api): add UnarchiveThread to MessagePhoneReceivedPayload"-```-------### Task 3: Populate `UnarchiveThread` on the payload in ReceiveMessage--**Files:**-- Modify: `api/pkg/services/message_service.go` (function `ReceiveMessage`, around lines 333-362)--**Interfaces:**-- Consumes: `entities.Phone.UnarchiveThread` (Task 1); `events.MessagePhoneReceivedPayload.UnarchiveThread` (Task 2); existing `service.phoneService.Load(ctx, userID, ownerE164 string) (*entities.Phone, error)`.-- Produces: received events now carry the phone's `UnarchiveThread` value.--- [ ] **Step 1: Load the phone and set the flag**--In `ReceiveMessage`, the owner E.164 string is `phonenumbers.Format(¶ms.Owner, phonenumbers.E164)`. Replace the `eventPayload := events.MessagePhoneReceivedPayload{...}` block so the owner string is computed once and the phone setting is looked up. Insert BEFORE the `eventPayload :=` assignment:--```go- owner := phonenumbers.Format(¶ms.Owner, phonenumbers.E164)-- unarchiveThread := false- phone, err := service.phoneService.Load(ctx, params.UserID, owner)- if err != nil {- ctxLogger.Warn(stacktrace.Propagate(err, fmt.Sprintf("cannot load phone [%s] for user [%s] to resolve UnarchiveThread; defaulting to false", owner, params.UserID)))- } else {- unarchiveThread = phone.UnarchiveThread- }-```--Then update the payload literal to reuse `owner` and set the flag:--```go- eventPayload := events.MessagePhoneReceivedPayload{- MessageID: messageID,- UserID: params.UserID,- Encrypted: params.Encrypted,- Owner: owner,- Contact: params.Contact,- Timestamp: params.Timestamp,- Content: params.Content,- SIM: params.SIM,- Attachments: attachmentURLs,- UnarchiveThread: unarchiveThread,- }-```--Note: `err` is already declared earlier in `ReceiveMessage` (from the attachments upload), so use `=` not `:=` for the phone load, as shown. Confirm `stacktrace` is already imported in this file (it is).--- [ ] **Step 2: Verify it compiles**--Run (from `api/`): `go build ./...`-Expected: exit code 0. If you get "err redeclared" or "err not used", ensure the phone load uses `phone, err = ...` on its own line (not `:=`) and that `phone` is newly declared with `:=` — since `phone` is new and `err` exists, `phone, err := ...` is correct Go (at least one new var on the left). Prefer `phone, err := service.phoneService.Load(...)`.--Correction to Step 1: use `phone, err := service.phoneService.Load(ctx, params.UserID, owner)` (mixed assignment is valid because `phone` is new). Keep the rest as written.--- [ ] **Step 3: Run existing message service tests**--Run (from `api/`): `go test ./pkg/services/ -run TestMessageService -v`-Expected: PASS (these are pure helper tests unaffected by this change). Also run `go build ./...` again to be safe.--- [ ] **Step 4: Commit**--```bash-git add api/pkg/services/message_service.go-git commit -m "feat(api): populate UnarchiveThread from phone on received event"-```-------### Task 4: Thread unarchive decision helper + wiring (TDD)--**Files:**-- Modify: `api/pkg/services/message_thread_service.go`-- Create: `api/pkg/services/message_thread_service_test.go`--**Interfaces:**-- Consumes: `entities.MessageThread.IsArchived`; `entities.MessageStatusReceived`; `MessageThreadUpdateParams`.-- Produces:- - `MessageThreadUpdateParams.UnarchiveThread bool`- - `func (service *MessageThreadService) shouldUnarchive(thread *entities.MessageThread, params MessageThreadUpdateParams) bool`--- [ ] **Step 1: Write the failing test**--Create `api/pkg/services/message_thread_service_test.go`:--```go-package services--import (- "testing"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/stretchr/testify/assert"-)--func TestShouldUnarchive(t *testing.T) {- service := &MessageThreadService{}-- archived := &entities.MessageThread{IsArchived: true}- notArchived := &entities.MessageThread{IsArchived: false}-- received := MessageThreadUpdateParams{Status: entities.MessageStatusReceived, UnarchiveThread: true}- receivedFlagOff := MessageThreadUpdateParams{Status: entities.MessageStatusReceived, UnarchiveThread: false}- sentFlagOn := MessageThreadUpdateParams{Status: entities.MessageStatusSent, UnarchiveThread: true}-- assert.True(t, service.shouldUnarchive(archived, received), "archived + inbound + flag on -> unarchive")- assert.False(t, service.shouldUnarchive(archived, receivedFlagOff), "flag off -> no unarchive")- assert.False(t, service.shouldUnarchive(archived, sentFlagOn), "outbound status -> no unarchive")- assert.False(t, service.shouldUnarchive(notArchived, received), "already unarchived -> no change")-}-```--Note: confirm `entities.MessageStatusSent` exists (it does — used in listeners). If not, substitute any non-received status constant such as `entities.MessageStatusPending`.--- [ ] **Step 2: Run the test to verify it fails**--Run (from `api/`): `go test ./pkg/services/ -run TestShouldUnarchive -v`-Expected: FAIL — compile error `service.shouldUnarchive undefined` and `params.UnarchiveThread` unknown field.--- [ ] **Step 3: Add the param field and the helper**--In `api/pkg/services/message_thread_service.go`, add the field to `MessageThreadUpdateParams`:--```go-type MessageThreadUpdateParams struct {- Owner string- Status entities.MessageStatus- Contact string- Content string- UserID entities.UserID- MessageID uuid.UUID- Timestamp time.Time- UnarchiveThread bool-}-```--Then add the pure helper (place it directly above `UpdateThread`):--```go-// shouldUnarchive reports whether an archived thread should be moved back to-// the inbox because a new inbound message was received and the phone has the-// UnarchiveThread setting enabled.-func (service *MessageThreadService) shouldUnarchive(thread *entities.MessageThread, params MessageThreadUpdateParams) bool {- return thread.IsArchived && params.UnarchiveThread && params.Status == entities.MessageStatusReceived-}-```--- [ ] **Step 4: Run the test to verify it passes**--Run (from `api/`): `go test ./pkg/services/ -run TestShouldUnarchive -v`-Expected: PASS.--- [ ] **Step 5: Apply the decision inside UpdateThread**--In `UpdateThread`, the thread is updated via `thread.Update(params.Timestamp, params.MessageID, params.Content, params.Status)`. Immediately BEFORE the `if err = service.repository.Update(ctx, thread.Update(...))` call, add:--```go- if service.shouldUnarchive(thread, params) {- thread.UpdateArchive(false)- ctxLogger.Info(fmt.Sprintf("unarchiving thread [%s] after inbound message [%s]", thread.ID, params.MessageID))- }-```--`thread.UpdateArchive(false)` mutates the same `thread` pointer that `thread.Update(...)` mutates and persists, so the single `repository.Update` call saves both the new last message and the cleared archive flag. Do not add a second Update call.--- [ ] **Step 6: Run the full services test package**--Run (from `api/`): `go test ./pkg/services/ -v`-Expected: PASS (including `TestShouldUnarchive` and existing `TestMessageService*`).--- [ ] **Step 7: Commit**--```bash-git add api/pkg/services/message_thread_service.go api/pkg/services/message_thread_service_test.go-git commit -m "feat(api): unarchive thread on inbound message when enabled"-```-------### Task 5: Pass the flag through the received-message listener--**Files:**-- Modify: `api/pkg/listeners/message_thread_listener.go` (function `OnMessagePhoneReceived`)--**Interfaces:**-- Consumes: `events.MessagePhoneReceivedPayload.UnarchiveThread` (Task 2); `MessageThreadUpdateParams.UnarchiveThread` (Task 4).-- Produces: inbound received events now request unarchiving.--- [ ] **Step 1: Set the field on the params**--In `OnMessagePhoneReceived`, update the `updateParams := services.MessageThreadUpdateParams{...}` literal to include the flag:--```go- updateParams := services.MessageThreadUpdateParams{- Owner: payload.Owner,- Contact: payload.Contact,- Timestamp: payload.Timestamp,- UserID: payload.UserID,- Status: entities.MessageStatusReceived,- Content: payload.Content,- MessageID: payload.MessageID,- UnarchiveThread: payload.UnarchiveThread,- }-```--Do NOT set `UnarchiveThread` on any other handler in this file (only inbound received messages unarchive).--- [ ] **Step 2: Verify it compiles and tests pass**--Run (from `api/`): `go build ./...` then `go test ./pkg/services/... ./pkg/listeners/...`-Expected: exit code 0 / PASS.--- [ ] **Step 3: Commit**--```bash-git add api/pkg/listeners/message_thread_listener.go-git commit -m "feat(api): forward UnarchiveThread flag from received event to thread update"-```-------### Task 6: Accept `unarchive_thread` in the phone upsert request/service--**Files:**-- Modify: `api/pkg/requests/phone_update_request.go`-- Modify: `api/pkg/services/phone_service.go` (`PhoneUpsertParams` struct and `update` method)--**Interfaces:**-- Consumes: `entities.Phone.UnarchiveThread` (Task 1).-- Produces: `PhoneUpsertParams.UnarchiveThread *bool`; PUT `/v1/phones` persists the setting.--- [ ] **Step 1: Add the request field**--In `api/pkg/requests/phone_update_request.go`, add to the `PhoneUpsert` struct (after `MissedCallAutoReply`):--```go- 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"`-```--- [ ] **Step 2: Map it as a partial-update field in ToUpsertParams**--Still in `phone_update_request.go`, inside `ToUpsertParams`, after the `maxSendAttempts` block, add the presence-detected mapping (mirrors the existing pattern):--```go- var unarchiveThread *bool- if _, exists := fields["unarchive_thread"]; exists {- unarchiveThread = &input.UnarchiveThread- }-```--Then add `UnarchiveThread: unarchiveThread,` to the returned `&services.PhoneUpsertParams{...}` literal.--- [ ] **Step 3: Add the field to PhoneUpsertParams and apply it**--In `api/pkg/services/phone_service.go`, add to `PhoneUpsertParams`:--```go- UnarchiveThread *bool-```--In the `update` method, before `phone.SIM = params.SIM`, add:--```go- if params.UnarchiveThread != nil {- phone.UnarchiveThread = *params.UnarchiveThread- }-```--- [ ] **Step 4: Verify build and tests**--Run (from `api/`): `go build ./...` then `go test ./pkg/...`-Expected: exit code 0 / PASS.--- [ ] **Step 5: Regenerate Swagger docs**--Run (from `api/`): `swag init --requiredByDefault --parseDependency --parseInternal`-Expected: regenerates `api/docs/*` including the new `unarchive_thread` fields. If `swag` is not installed: `go install github.com/swaggo/swag/cmd/swag@latest` then re-run.--- [ ] **Step 6: Commit**--```bash-git add api/pkg/requests/phone_update_request.go api/pkg/services/phone_service.go api/docs-git commit -m "feat(api): accept unarchive_thread in phone upsert request"-```-------### Task 7: Regenerate web API models--**Files:**-- Modify (generated): `web/shared/types/api.ts`--**Interfaces:**-- Consumes: regenerated Swagger from Task 6.-- Produces: `EntitiesPhone.unarchive_thread?: boolean` available to the web app.--- [ ] **Step 1: Install web deps (if not already installed)**--Run (from `web/`): `pnpm install`-Expected: completes without `ERR_PNPM_IGNORED_BUILDS`.--- [ ] **Step 2: Regenerate models**--Run (from `web/`): `pnpm api:models`-Expected: `web/shared/types/api.ts` now includes `unarchive_thread` on the phone type (search the file for `unarchive_thread`).--- [ ] **Step 3: Verify the field exists**--Run (from `web/`): `Select-String -Path shared/types/api.ts -Pattern unarchive_thread`-Expected: at least one match.--- [ ] **Step 4: Commit**--```bash-git add web/shared/types/api.ts-git commit -m "chore(web): regenerate api models with unarchive_thread"-```-------### Task 8: Send `unarchive_thread` in the phones store update--**Files:**-- Modify: `web/app/stores/phones.ts` (function `updatePhone`, around lines 48-62)--**Interfaces:**-- Consumes: `EntitiesPhone.unarchive_thread` (Task 7).-- Produces: PUT `/v1/phones` body includes `unarchive_thread`.--- [ ] **Step 1: Add the field to the PUT body**--In `updatePhone`, inside the `body` object passed to `apiFetch('/v1/phones', { method: 'PUT', ... })`, add after `message_send_schedule_id`:--```ts- message_send_schedule_id: phone.message_send_schedule_id ?? null,- unarchive_thread: phone.unarchive_thread ?? false,-```--- [ ] **Step 2: Lint**--Run (from `web/`): `pnpm lint`-Expected: no new errors for `web/app/stores/phones.ts`.--- [ ] **Step 3: Commit**--```bash-git add web/app/stores/phones.ts-git commit -m "feat(web): send unarchive_thread in updatePhone"-```-------### Task 9: Add the per-phone toggle to the settings UI--**Files:**-- Modify: `web/app/pages/settings/index.vue` (phone settings card, near the `missed_call_auto_reply` VTextarea around lines 1680-1690)--**Interfaces:**-- Consumes: `activePhone.unarchive_thread` (Task 7); `updatePhone` store action (Task 8).-- Produces: user-visible toggle that persists via the existing "Update Phone" button.--- [ ] **Step 1: Add a VSwitch bound to activePhone.unarchive_thread**--In `web/app/pages/settings/index.vue`, immediately AFTER the closing `/>` of the `missed_call_auto_reply` `<VTextarea>` (line ~1690) and before the `</VCol>`, add:--```html- <VSwitch- v-model="activePhone.unarchive_thread"- class="mt-4"- color="primary"- density="compact"- hide-details- label="Unarchive thread on new message"- hint="When a new message is received, move an archived conversation back to the inbox"- persistent-hint- />-```--Note: match the surrounding indentation exactly (this block sits inside the same `<VCol>` as the textarea). If `activePhone` is typed and `unarchive_thread` is optional, `v-model` still works; the store update coerces with `?? false`.--- [ ] **Step 2: Lint**--Run (from `web/`): `pnpm lint`-Expected: no new errors for `settings/index.vue`. Auto-fix formatting if needed with `pnpm lintfix`.--- [ ] **Step 3: Build the site to confirm the template compiles**--Run (from `web/`): `pnpm run generate`-Expected: build completes without template/compile errors. (If `generate` is heavy, `pnpm dev` briefly and confirm the settings page renders is an acceptable alternative.)--- [ ] **Step 4: Commit**--```bash-git add web/app/pages/settings/index.vue-git commit -m "feat(web): add per-phone unarchive-thread toggle to settings"-```-------### Task 10: Full validation--**Files:** none (verification only).--- [ ] **Step 1: API full test + build**--Run (from `api/`): `go test ./...` then `go build ./...`-Expected: all PASS, exit code 0.--- [ ] **Step 2: Web lint + test**--Run (from `web/`): `pnpm lint` then `pnpm test`-Expected: PASS.--- [ ] **Step 3: Manual smoke (optional, if a local stack is available)**--Start the stack (`docker compose up --build`), open the web settings for a phone, enable "Unarchive thread on new message", save. Archive a thread, then simulate/receive an inbound message for that owner and confirm the thread returns to the inbox. Toggle off and confirm an inbound message leaves the thread archived.--- [ ] **Step 4: Final commit (only if any fixups were needed)**--```bash-git add -A-git commit -m "chore: finalize unarchive-thread-on-receive feature"-```-------### Task 11: End-to-end integration test--**Files:**-- Create: `tests/unarchive_thread_integration_test.go`--**Context:** The `tests/` module is a black-box integration suite (package `tests`)-that runs against the full Docker stack (API on `localhost:8000`, CockroachDB,-Redis, phone emulator). It uses the external `github.com/NdoleStudio/httpsms-go`-client for convenience, but that client does NOT know about the new-`unarchive_thread` field — so this test sets the phone flag with a raw HTTP PUT-to `/v1/phones` and reads threads with raw HTTP GETs. It reuses existing helpers-from `helpers_test.go`: `apiBaseURL`, `userAPIKey`, `newAPIClient`, `setupPhone`,-`randomPhoneNumber`, `randomEncryptionKey`, `pollMessageStatus`.--**Interfaces:**-- Consumes: the running API with all prior tasks deployed; endpoints- `PUT /v1/phones`, `POST /v1/messages/receive`, `GET /v1/message-threads`,- `PUT /v1/message-threads/{id}`.-- Produces: `TestUnarchiveThreadOnReceive_Enabled` and- `TestUnarchiveThreadOnReceive_Disabled`.--- [ ] **Step 1: Write the integration test file**--Create `tests/unarchive_thread_integration_test.go`:--```go-package tests--import (- "bytes"- "context"- "encoding/json"- "fmt"- "io"- "net/http"- "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()-- 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.-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)-- 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)- defer resp.Body.Close()-- respBody, err := io.ReadAll(resp.Body)- require.NoError(t, err)- 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()-- url := fmt.Sprintf("%s/v1/message-threads?owner=%s&is_archived=%t&limit=20", apiBaseURL, owner, archived)- req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, 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")-}-```--- [ ] **Step 2: Build the test module (compile check without a running stack)**--Run (from `tests/`): `go vet ./...`-Expected: exit code 0 (compiles). If `httpsms.MessageResponse` field access differs, adjust to match the version pinned in `tests/go.mod` (the existing `integration_test.go` already uses `httpsms.MessageResponse` and `result.Data.ID`).--- [ ] **Step 3: Run the full integration suite against the Docker stack**--Run (from `tests/`), following the README one-liner:--```bash-bash generate-firebase-credentials.sh-export FIREBASE_CREDENTIALS=$(jq -c . firebase-credentials.json)-docker compose up -d --build --wait-docker compose wait seed-sleep 2-go test -v -timeout 180s -run TestUnarchiveThreadOnReceive ./...-docker compose down -v-```--On Windows without bash/jq available, run the integration suite via the CI-workflow (`.github/workflows/integration-test.yml`) or a Linux/WSL shell; the-Step 2 `go vet` compile check is the local gate.--Expected: both `TestUnarchiveThreadOnReceive_Enabled` and-`TestUnarchiveThreadOnReceive_Disabled` PASS.--- [ ] **Step 4: Update the test coverage checklist in the README**--In `tests/README.md`, under "## Test Coverage", add:--```markdown-- [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-```--- [ ] **Step 5: Commit**--```bash-git add tests/unarchive_thread_integration_test.go tests/README.md-git commit -m "test(integration): verify unarchive thread on receive"-```-------## Self-Review--**Spec coverage:**-- Data model field -> Task 1. ✓-- Event payload field -> Task 2. ✓-- Populate flag in ReceiveMessage via phoneService.Load -> Task 3 (with fallback to false on load error). ✓-- Thread trigger (inbound-only, archived-only, same Update call) -> Task 4. ✓-- Listener wiring, inbound-only -> Task 5. ✓-- Phone upsert request + params partial update -> Task 6. ✓-- Swagger regen -> Task 6 Step 5. ✓-- Web: store PUT body -> Task 8; settings toggle -> Task 9; model regen -> Task 7. ✓-- Testing (pure helper unit test, go test, web lint/test) -> Tasks 4 & 10. ✓-- Integration test (live-stack E2E, enabled + disabled) -> Task 11. ✓-- Out of scope (Android, global/per-thread config, auto-archive) -> not implemented. ✓--**Placeholder scan:** No TBD/TODO; all code steps include concrete code and exact commands.--**Type consistency:** `UnarchiveThread` (Go) / `unarchive_thread` (JSON) used identically across entity, event, params, request, store, and template. Helper `shouldUnarchive(thread, params)` signature matches its test and its call site. `phoneService.Load(ctx, userID, ownerE164)` matches existing usage in `RespondToMissedCall`.diff --git a/docs/superpowers/plans/2026-07-18-webhook-email-payload-formatting.md b/docs/superpowers/plans/2026-07-18-webhook-email-payload-formatting.mddeleted file mode 100644index c5c9b3e2..00000000--- a/docs/superpowers/plans/2026-07-18-webhook-email-payload-formatting.md+++ /dev/null@@ -1,593 +0,0 @@-# Webhook Email Payload Formatting Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Render the webhook failure email's Event Payload as readable indented JSON with safe lightweight syntax colors in HTML and readable indentation in plain text.--**Architecture:** Add a focused formatter in `api/pkg/emails` that produces a plain string and a safely constructed `template.HTML` code block. Teach the custom Hermes HTML dictionary template to use `hermes.Entry.UnsafeValue` when explicitly supplied, then wire only the webhook email's Event Payload entry to that path.--**Tech Stack:** Go 1.25.8 module, Go standard library (`bytes`, `encoding/json`, `html`, `html/template`, `strings`), go-hermes v2.6.2, testify v1.11.1.--## Global Constraints--- Format only the webhook email's **Event Payload** value.-- Leave SMS content, failure reasons, HTTP responses, and every other email field unchanged.-- Pretty-print valid JSON with indentation.-- Render valid JSON in HTML with lightweight colors for keys, strings, numbers, booleans, and `null`.-- Render invalid JSON in the same monospace block with original whitespace and no syntax colors.-- Add no third-party dependency.-- HTML-escape every payload token before converting the completed markup to `template.HTML`.-- Invalid JSON must not prevent email generation or delivery.-- Preserve the existing plain-text email behavior except for readable payload indentation.-- Use `stacktrace.Propagate` for existing Hermes generation errors; this feature introduces no new returned error.-------## File Structure--- Create `api/pkg/emails/event_payload_formatter.go`: JSON indentation, token highlighting, HTML escaping, and code-block construction.-- Create `api/pkg/emails/event_payload_formatter_test.go`: focused tests for valid JSON tokens, escaping, and invalid JSON fallback.-- Create `api/pkg/emails/hermes_theme_test.go`: verifies safe opt-in HTML dictionary rendering and unchanged plain-text rendering.-- Modify `api/pkg/emails/hermes_theme.go:325-334`: render `Entry.UnsafeValue` only when present.-- Create `api/pkg/emails/hermes_notification_email_factory_test.go`: end-to-end factory coverage for the webhook notification email.-- Modify `api/pkg/emails/hermes_notification_email_factory.go:78-122`: format and attach only the Event Payload dictionary entry.--### Task 1: Build the event payload formatter--**Files:**-- Create: `api/pkg/emails/event_payload_formatter.go`-- Create: `api/pkg/emails/event_payload_formatter_test.go`--**Interfaces:**-- Consumes: a raw webhook event payload `string`.-- Produces: `formatEventPayload(payload string) (string, template.HTML)`.-- Produces: plain indented JSON for `hermes.Entry.Value` and an escaped styled code block for `hermes.Entry.UnsafeValue`.--- [ ] **Step 1: Write the failing formatter tests**--Create `api/pkg/emails/event_payload_formatter_test.go`:--```go-package emails--import (- "strings"- "testing"-- "github.com/stretchr/testify/assert"-)--func TestFormatEventPayloadIndentsAndHighlightsJSON(t *testing.T) {- payload := `{"message":"hello","count":2,"ratio":1.5,"enabled":true,"disabled":false,"missing":null,"nested":{"value":"ok"}}`-- plain, rich := formatEventPayload(payload)- html := string(rich)-- assert.Equal(t, `{- "message": "hello",- "count": 2,- "ratio": 1.5,- "enabled": true,- "disabled": false,- "missing": null,- "nested": {- "value": "ok"- }-}`, plain)- assert.Contains(t, html, `<span style="color:#0550AE;font-weight:600;">"message"</span>`)- assert.Contains(t, html, `<span style="color:#0A3069;">"hello"</span>`)- assert.Contains(t, html, `<span style="color:#953800;">2</span>`)- assert.Contains(t, html, `<span style="color:#953800;">1.5</span>`)- assert.Contains(t, html, `<span style="color:#8250DF;">true</span>`)- assert.Contains(t, html, `<span style="color:#8250DF;">false</span>`)- assert.Contains(t, html, `<span style="color:#8250DF;">null</span>`)- assert.Contains(t, html, `white-space:pre-wrap`)-}--func TestFormatEventPayloadEscapesPayloadHTML(t *testing.T) {- plain, rich := formatEventPayload(`{"message":"<script>alert(\"x\")</script>&"}`)- html := string(rich)-- assert.Contains(t, plain, `<script>alert`)- assert.NotContains(t, html, `<script>`)- assert.Contains(t, html, `<script>`)- assert.Contains(t, html, `&`)-}--func TestFormatEventPayloadPreservesInvalidJSONWithoutHighlighting(t *testing.T) {- payload := "line one\n <strong>line two</strong>"-- plain, rich := formatEventPayload(payload)- html := string(rich)-- assert.Equal(t, payload, plain)- assert.Contains(t, html, "line one\n <strong>line two</strong>")- assert.NotContains(t, html, `<strong>`)- assert.NotContains(t, html, `<span style="color:`)- assert.Equal(t, 1, strings.Count(html, `<pre style=`))-}-```--- [ ] **Step 2: Run the formatter tests to verify they fail**--Run:--```powershell-Set-Location api-go test ./pkg/emails -run '^TestFormatEventPayload' -count=1-```--Expected: build failure with `undefined: formatEventPayload`.--- [ ] **Step 3: Implement the formatter**--Create `api/pkg/emails/event_payload_formatter.go`:--```go-package emails--import (- "bytes"- "encoding/json"- "html"- "html/template"- "strings"-)--const (- eventPayloadCodeBlockStyle = "margin:0;padding:12px;border:1px solid #D0D7DE;border-radius:6px;background:#F6F8FA;color:#24292F;font-family:Consolas,Monaco,'Courier New',monospace;font-size:13px;line-height:1.5;white-space:pre-wrap;word-break:break-word;overflow-wrap:anywhere;"- jsonKeyStyle = "color:#0550AE;font-weight:600;"- jsonStringStyle = "color:#0A3069;"- jsonNumberStyle = "color:#953800;"- jsonLiteralStyle = "color:#8250DF;"-)--func formatEventPayload(payload string) (string, template.HTML) {- formattedPayload, isJSON := indentEventPayloadJSON(payload)- content := html.EscapeString(formattedPayload)- if isJSON {- content = highlightEventPayloadJSON(formattedPayload)- }-- // Every payload token is escaped before this trusted wrapper is constructed.- richPayload := template.HTML(`<pre style="` + eventPayloadCodeBlockStyle + `">` + content + `</pre>`)- return formattedPayload, richPayload-}--func indentEventPayloadJSON(payload string) (string, bool) {- var formatted bytes.Buffer- if err := json.Indent(&formatted, []byte(payload), "", " "); err != nil {- return payload, false- }-- return formatted.String(), true-}--func highlightEventPayloadJSON(payload string) string {- var highlighted strings.Builder- highlighted.Grow(len(payload))-- for index := 0; index < len(payload); {- switch {- case payload[index] == '"':- end := eventPayloadJSONStringEnd(payload, index)- style := jsonStringStyle- if eventPayloadNextNonSpace(payload, end) == ':' {- style = jsonKeyStyle- }- writeEventPayloadToken(&highlighted, style, payload[index:end])- index = end- case payload[index] == '-' || isEventPayloadDigit(payload[index]):- end := index + 1- for end < len(payload) && isEventPayloadNumberCharacter(payload[end]) {- end++- }- writeEventPayloadToken(&highlighted, jsonNumberStyle, payload[index:end])- index = end- case strings.HasPrefix(payload[index:], "true"):- writeEventPayloadToken(&highlighted, jsonLiteralStyle, "true")- index += len("true")- case strings.HasPrefix(payload[index:], "false"):- writeEventPayloadToken(&highlighted, jsonLiteralStyle, "false")- index += len("false")- case strings.HasPrefix(payload[index:], "null"):- writeEventPayloadToken(&highlighted, jsonLiteralStyle, "null")- index += len("null")- default:- highlighted.WriteString(html.EscapeString(payload[index : index+1]))- index++- }- }-- return highlighted.String()-}--func eventPayloadJSONStringEnd(payload string, start int) int {- escaped := false- for index := start + 1; index < len(payload); index++ {- switch {- case escaped:- escaped = false- case payload[index] == '\\':- escaped = true- case payload[index] == '"':- return index + 1- }- }-- return len(payload)-}--func eventPayloadNextNonSpace(payload string, start int) byte {- for index := start; index < len(payload); index++ {- switch payload[index] {- case ' ', '\n', '\r', '\t':- continue- default:- return payload[index]- }- }-- return 0-}--func isEventPayloadDigit(value byte) bool {- return value >= '0' && value <= '9'-}--func isEventPayloadNumberCharacter(value byte) bool {- return isEventPayloadDigit(value) ||- value == '-' ||- value == '+' ||- value == '.' ||- value == 'e' ||- value == 'E'-}--func writeEventPayloadToken(builder *strings.Builder, style string, token string) {- builder.WriteString(`<span style="`)- builder.WriteString(style)- builder.WriteString(`">`)- builder.WriteString(html.EscapeString(token))- builder.WriteString(`</span>`)-}-```--- [ ] **Step 4: Format and run the formatter tests**--Run:--```powershell-pre-commit run go-fumpt --files api/pkg/emails/event_payload_formatter.go api/pkg/emails/event_payload_formatter_test.go-Set-Location api-go test ./pkg/emails -run '^TestFormatEventPayload' -count=1-```--Expected: `go-fumpt` passes (rerun it once if it initially reformats the files),-then all three formatter tests pass.--- [ ] **Step 5: Commit the formatter**--Run from the repository root:--```powershell-git add -- api\pkg\emails\event_payload_formatter.go api\pkg\emails\event_payload_formatter_test.go-git commit -m "feat(api): format webhook email payload" -m "Co-authored-by: Copilot <[email protected]>" -m "Copilot-Session: 48f6d946-ae22-4440-b7a1-44e939419b11"-```--Expected: one commit containing only the formatter and its tests.--### Task 2: Add opt-in rich dictionary rendering to the Hermes theme--**Files:**-- Create: `api/pkg/emails/hermes_theme_test.go`-- Modify: `api/pkg/emails/hermes_theme.go:325-334`--**Interfaces:**-- Consumes: `hermes.Entry{Value: plain, UnsafeValue: rich}`.-- Produces: HTML rendering that uses `UnsafeValue` only when non-empty.-- Preserves: plain-text rendering always uses `Value`.--- [ ] **Step 1: Write the failing Hermes theme test**--Create `api/pkg/emails/hermes_theme_test.go`:--```go-package emails--import (- "html/template"- "testing"-- "github.com/go-hermes/hermes/v2"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--func TestHermesThemeRendersUnsafeDictionaryValueOnlyWhenProvided(t *testing.T) {- generator := (&HermesGeneratorConfig{- AppURL: "https://httpsms.com",- AppName: "httpSMS",- AppLogoURL: "https://httpsms.com/logo.png",- }).Generator()- email := hermes.Email{- Body: hermes.Body{- Title: "Hello",- Dictionary: []hermes.Entry{- {Key: "Normal", Value: "<b>escaped</b>"},- {- Key: "Payload",- Value: "plain payload",- UnsafeValue: template.HTML(`<pre style="white-space:pre-wrap">rich payload</pre>`),- },- },- },- }-- htmlEmail, err := generator.GenerateHTML(email)- require.NoError(t, err)- textEmail, err := generator.GeneratePlainText(email)- require.NoError(t, err)-- assert.Contains(t, htmlEmail, `<b>escaped</b>`)- assert.NotContains(t, htmlEmail, `<b>escaped</b>`)- assert.Contains(t, htmlEmail, `<pre style="white-space:pre-wrap">rich payload</pre>`)- assert.NotContains(t, htmlEmail, `<dd>plain payload</dd>`)- assert.Contains(t, textEmail, "Normal: <b>escaped</b>")- assert.Contains(t, textEmail, "Payload: plain payload")- assert.NotContains(t, textEmail, "<pre")-}-```--- [ ] **Step 2: Run the theme test to verify it fails**--Run:--```powershell-Set-Location api-go test ./pkg/emails -run '^TestHermesThemeRendersUnsafeDictionaryValueOnlyWhenProvided$' -count=1-```--Expected: failure because the generated HTML contains `plain payload` instead-of the `<pre>` block.--- [ ] **Step 3: Update the HTML dictionary template**--In `api/pkg/emails/hermes_theme.go`, replace:--```gotemplate-<dd>{{ $entry.Value }}</dd>-```--with:--```gotemplate-<dd>{{ if $entry.UnsafeValue }}{{ $entry.UnsafeValue }}{{ else }}{{ $entry.Value }}{{ end }}</dd>-```--Do not change the plain-text template at `api/pkg/emails/hermes_theme.go:523-528`;-it must continue to render:--```gotemplate-<li>{{ $entry.Key }}: {{ $entry.Value }}</li>-```--- [ ] **Step 4: Format and run the theme and formatter tests**--Run:--```powershell-pre-commit run go-fumpt --files api/pkg/emails/hermes_theme.go api/pkg/emails/hermes_theme_test.go-Set-Location api-go test ./pkg/emails -run '^(TestHermesTheme|TestFormatEventPayload)' -count=1-```--Expected: `go-fumpt` passes (rerun it once if it initially reformats the files),-then the theme test and all formatter tests pass.--- [ ] **Step 5: Commit the theme support**--Run from the repository root:--```powershell-git add -- api\pkg\emails\hermes_theme.go api\pkg\emails\hermes_theme_test.go-git commit -m "feat(api): render rich email dictionary values" -m "Co-authored-by: Copilot <[email protected]>" -m "Copilot-Session: 48f6d946-ae22-4440-b7a1-44e939419b11"-```--Expected: one commit containing only the Hermes template opt-in and its test.--### Task 3: Wire formatting into the webhook failure email--**Files:**-- Create: `api/pkg/emails/hermes_notification_email_factory_test.go`-- Modify: `api/pkg/emails/hermes_notification_email_factory.go:78-122`--**Interfaces:**-- Consumes: `formatEventPayload(payload string) (string, template.HTML)` from Task 1.-- Produces: the existing `NotificationEmailFactory.WebhookSendFailed` email with only its Event Payload entry using `UnsafeValue`.-- Preserves: factory interface, subjects, recipients, other dictionary entries, actions, and error propagation.--- [ ] **Step 1: Write the failing webhook factory tests**--Create `api/pkg/emails/hermes_notification_email_factory_test.go`:--```go-package emails--import (- "strings"- "testing"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/events"- "github.com/google/uuid"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--func testNotificationEmailFactory() NotificationEmailFactory {- return NewHermesNotificationEmailFactory(&HermesGeneratorConfig{- AppURL: "https://httpsms.com",- AppName: "httpSMS",- AppLogoURL: "https://httpsms.com/logo.png",- })-}--func TestWebhookSendFailedFormatsOnlyEventPayload(t *testing.T) {- statusCode := 500- factory := testNotificationEmailFactory()- user := &entities.User{- Email: "[email protected]",- Timezone: "UTC",- }- payload := &events.WebhookSendFailedPayload{- WebhookID: uuid.New(),- WebhookURL: "https://example.com/webhooks",- Owner: "+237612345678",- EventID: "event-id",- EventType: "message.phone.received",- EventPayload: `{"message":"hello","retry":false}`,- HTTPResponseStatusCode: &statusCode,- ErrorMessage: "plain failure response",- }-- email, err := factory.WebhookSendFailed(user, payload)- require.NoError(t, err)-- assert.Equal(t, "[email protected]", email.ToEmail)- assert.Equal(t, "📢 We could not forward a webhook event to your server", email.Subject)- assert.Contains(t, email.HTML, `<pre style=`)- assert.Equal(t, 1, strings.Count(email.HTML, `<pre style=`))- assert.Contains(t, email.HTML, `"message"`)- assert.Contains(t, email.HTML, `plain failure response`)- assert.Contains(t, email.Text, `"message": "hello"`)- assert.Contains(t, email.Text, `"retry": false`)- assert.NotContains(t, email.Text, "<pre")-}--func TestWebhookSendFailedPreservesNonJSONEventPayload(t *testing.T) {- factory := testNotificationEmailFactory()- user := &entities.User{- Email: "[email protected]",- Timezone: "UTC",- }- payload := &events.WebhookSendFailedPayload{- WebhookID: uuid.New(),- WebhookURL: "https://example.com/webhooks",- Owner: "+237612345678",- EventID: "event-id",- EventType: "message.phone.received",- EventPayload: "line one\n line two",- ErrorMessage: "plain failure response",- }-- email, err := factory.WebhookSendFailed(user, payload)- require.NoError(t, err)-- assert.Contains(t, email.HTML, "line one\n line two")- assert.NotContains(t, email.HTML, `<span style="color:`)- assert.Contains(t, email.Text, "line one\n line two")-}-```--- [ ] **Step 2: Run the webhook factory tests to verify they fail**--Run:--```powershell-Set-Location api-go test ./pkg/emails -run '^TestWebhookSendFailed' -count=1-```--Expected: failure because Event Payload still renders as an ordinary dictionary-value and no `<pre>` block is present.--- [ ] **Step 3: Format Event Payload in the webhook factory**--At the start of-`hermesNotificationEmailFactory.WebhookSendFailed` in-`api/pkg/emails/hermes_notification_email_factory.go`, add:--```go-formattedPayload, formattedPayloadHTML := formatEventPayload(payload.EventPayload)-```--Replace the existing Event Payload dictionary entry:--```go-{Key: "Event Payload", Value: payload.EventPayload},-```--with:--```go-{- Key: "Event Payload",- Value: formattedPayload,- UnsafeValue: formattedPayloadHTML,-},-```--Do not change the Error Message / HTTP Response entry or any SMS email method.--- [ ] **Step 4: Format and run all email package tests**--Run:--```powershell-pre-commit run go-fumpt --files api/pkg/emails/hermes_notification_email_factory.go api/pkg/emails/hermes_notification_email_factory_test.go-Set-Location api-go test ./pkg/emails -count=1-```--Expected: `go-fumpt` passes (rerun it once if it initially reformats the files),-then all `pkg/emails` tests pass.--- [ ] **Step 5: Run the stable API package regression suite**--Run:--```powershell-Set-Location api-$env:GOTOOLCHAIN = 'go1.25.8'-$packages = go list ./... | Where-Object { $_ -ne 'github.com/NdoleStudio/httpsms/pkg/handlers' }-go test -vet=off $packages-```--Expected: all selected API packages pass without adding or changing-dependencies.--The clean baseline cannot use plain `go test ./...`: existing stacktrace calls-fail Go vet's non-constant-format check, and-`pkg/handlers.TestPhoneAPIKeyHandler_store` requires an API server at-`localhost:8000`. Do not change those unrelated packages as part of this-feature.--- [ ] **Step 6: Review the final diff**--Run from the repository root:--```powershell-git --no-pager diff --check-git --no-pager diff -- api\pkg\emails-```--Expected:--- no whitespace errors;-- only the formatter, Hermes dictionary opt-in, webhook Event Payload wiring,- and their tests are present;-- SMS content, error responses, and failure reasons are unchanged; and-- `api\go.mod` and `api\go.sum` are unchanged.--- [ ] **Step 7: Commit the webhook factory integration**--Run from the repository root:--```powershell-git add -- api\pkg\emails\hermes_notification_email_factory.go api\pkg\emails\hermes_notification_email_factory_test.go-git commit -m "feat(api): highlight webhook email payload" -m "Co-authored-by: Copilot <[email protected]>" -m "Copilot-Session: 48f6d946-ae22-4440-b7a1-44e939419b11"-```--Expected: one commit containing only the webhook factory integration and its-tests.diff --git a/docs/superpowers/plans/2026-07-19-contacts-feature.md b/docs/superpowers/plans/2026-07-19-contacts-feature.mddeleted file mode 100644index 8a72fe40..00000000--- a/docs/superpowers/plans/2026-07-19-contacts-feature.md+++ /dev/null@@ -1,3025 +0,0 @@-# Contacts Feature Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Add a Contacts feature (name, emails, phone numbers, free-form properties) with full CRUD + CSV import, and display the resolved contact name instead of the raw phone number on the threads page, using as few DB queries as possible.--**Architecture:** New `Contact` entity + layered backend (handler → service → repository → validator → requests/responses) mirroring existing patterns. Thread-name resolution is opt-in per request and served from a per-user `phone_number → *Contact` map cached in `cache.Cache`, so the common path adds zero DB queries and a name change is a single-row `UPDATE` + cache invalidation. Frontend adds a Pinia store and a Plunk-style Contacts page (Nuxt 4 SPA).--**Tech Stack:** Go (Fiber v3, GORM v1.31.2, lib/pq, nyaruka/phonenumbers, jszwec/csvutil), Nuxt 4 + Pinia + Vuetify 4, Swagger (`swag`), swagger-typescript-api.--## Global Constraints--- Source of truth: `docs/superpowers/specs/2026-07-19-contacts-feature-design.md`. Follow it exactly.-- Run Go tests with `go test -vet=off ./...` from `api/` (Go 1.26 vet rejects the repo's `stacktrace.Propagate(err, fmt.Sprintf(...))` pattern).-- Wrap all Go errors with `github.com/NdoleStudio/stacktrace` (`Propagatef` / `PropagateWithCodef`) — never return bare errors.-- All GORM queries use `repository.db.WithContext(ctx)`. No raw SQL.-- Register Fiber routes via the `h.register(router, fiber.MethodX, path, middlewares, route)` helper (Fiber v3), not `Get`/`Post` directly.-- Contacts are global to the user account. **No** uniqueness constraint on phone numbers; **no** `contact_phone_numbers` lookup table.-- On phone-number collision across contacts, the **most recently updated** contact wins for display.-- Thread-name resolution is **opt-in** via `?contacts=true` (default off).-- Create endpoint accepts one or many; batch capped at **≤ 1000** contacts; cache invalidated **once** after the batch commits.-- CSV import is **CSV only** — Excel/XLSX is not supported for contacts. Max 500 KB, ≤ 1000 rows.-- `pq.StringArray` with `gorm:"type:text[]" swaggertype:"array,string"` for array fields (convention from `phone_api_key.go`/`webhook.go`).-- Web conventions: every `VDialog` has `opacity="0.9"` and a Close button with `color="warning"`; hyperlinks get `text-decoration-none hover:text-decoration-underline`; destructure filters from `useFilters()` in `<script setup>` and use directly in the template; no glowing gradient text off the homepage; Vuetify 4 typography classes (`text-headline-large`, `text-title-large`, `text-display-large`, etc.); in `useApi` `onRequest`, `options.headers` is a `Headers` instance — use `.set()`.-- Regenerate Swagger after API annotation changes: `cd api && swag init --requiredByDefault --parseDependency --parseInternal`.-- Regenerate web API models after Swagger changes: `cd web && pnpm api:models`.-------## File Structure--Backend (`api/`):-- `pkg/entities/contact.go` — `Contact` entity + `ContactProperties` custom jsonb type (Valuer/Scanner).-- `pkg/entities/contact_test.go` — round-trip tests for `ContactProperties`.-- `pkg/entities/message_thread.go` — add non-persisted `ContactDetails *Contact` field.-- `pkg/repositories/contact_repository.go` — `ContactRepository` interface + param structs.-- `pkg/repositories/gorm_contact_repository.go` — GORM implementation.-- `pkg/repositories/gorm_contact_repository_test.go` — repository tests.-- `pkg/requests/contact_store.go` — create-many request + per-item `ContactItem`.-- `pkg/requests/contact_update.go` — update request.-- `pkg/requests/contact_index.go` — list/search request.-- `pkg/responses/*` — reuse existing generic OK/Created responses (no new file needed).-- `pkg/validators/contact_handler_validator.go` — validates store/update/index + CSV parse.-- `pkg/services/contact_service.go` — CRUD + contact-map build + cache invalidation.-- `pkg/services/contact_service_test.go` — service tests.-- `pkg/handlers/contact_handler.go` — HTTP handlers + `RegisterRoutes`.-- `pkg/services/message_thread_service.go` — extend `GetThreads` to attach `ContactDetails`.-- `pkg/requests/message_thread_index_request.go` — add `Contacts` query param.-- `pkg/di/container.go` — wire repo/service/validator/handler, AutoMigrate, register routes.--Frontend (`web/`):-- `app/stores/contacts.ts` — Pinia store.-- `app/pages/contacts/index.vue` — Plunk-style Contacts page + dialogs.-- `app/stores/threads.ts` — pass `contacts: true`.-- `app/components/MessageThread.vue`, `app/components/MessageThreadHeader.vue` — render resolved name.-- default layout — add Contacts nav link.-- `shared/types/api` — regenerated from Swagger.-- `public/templates/httpsms-contacts.csv` — CSV template.-------### Task 1: Contact entity + ContactProperties custom type--**Files:**-- Create: `api/pkg/entities/contact.go`-- Create: `api/pkg/entities/contact_test.go`--**Interfaces:**-- Produces: `entities.Contact` struct; `entities.ContactProperties` (`map[string]string`) implementing `driver.Valuer` and `sql.Scanner`.--- [ ] **Step 1: Write the failing test**--Create `api/pkg/entities/contact_test.go`:--```go-package entities--import (- "testing"-- "github.com/stretchr/testify/assert"-)--func TestContactProperties_ValueScanRoundTrip(t *testing.T) {- cases := []ContactProperties{- nil,- {},- {"company": "Acme", "role": "CTO"},- }-- for _, original := range cases {- value, err := original.Value()- assert.Nil(t, err)-- var scanned ContactProperties- assert.Nil(t, scanned.Scan(value))-- if len(original) == 0 {- assert.Equal(t, 0, len(scanned))- continue- }- assert.Equal(t, original, scanned)- }-}--func TestContactProperties_ScanFromString(t *testing.T) {- var scanned ContactProperties- assert.Nil(t, scanned.Scan(`{"k":"v"}`))- assert.Equal(t, ContactProperties{"k": "v"}, scanned)-}--func TestContactProperties_ScanNil(t *testing.T) {- var scanned ContactProperties- assert.Nil(t, scanned.Scan(nil))- assert.Equal(t, 0, len(scanned))-}-```--- [ ] **Step 2: Run test to verify it fails**--Run: `cd api && go test -vet=off ./pkg/entities/ -run TestContactProperties`-Expected: FAIL / build error — `Contact`/`ContactProperties` undefined.--- [ ] **Step 3: Write minimal implementation**--Create `api/pkg/entities/contact.go`:--```go-package entities--import (- "database/sql/driver"- "encoding/json"- "fmt"- "time"-- "github.com/google/uuid"- "github.com/lib/pq"-)--// ContactProperties is a free-form key/value map persisted as a jsonb column.-type ContactProperties map[string]string--// Value implements driver.Valuer, serializing the map to JSON bytes.-func (p ContactProperties) Value() (driver.Value, error) {- if p == nil {- return []byte("{}"), nil- }- data, err := json.Marshal(p)- if err != nil {- return nil, err- }- return data, nil-}--// Scan implements sql.Scanner, deserializing jsonb bytes/string into the map.-func (p *ContactProperties) Scan(src any) error {- if src == nil {- *p = ContactProperties{}- return nil- }-- var data []byte- switch value := src.(type) {- case []byte:- data = value- case string:- data = []byte(value)- default:- return fmt.Errorf("unsupported type [%T] for ContactProperties", src)- }-- if len(data) == 0 {- *p = ContactProperties{}- return nil- }-- result := ContactProperties{}- if err := json.Unmarshal(data, &result); err != nil {- return err- }- *p = result- return nil-}--// Contact represents a saved contact belonging to a user.-type Contact struct {- ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`- UserID UserID `json:"user_id" gorm:"index" example:"WB7DRDWrJZRGbYrv2CKGkqbzvqdC"`- Name string `json:"name" example:"Alice Smith"`- Emails pq.StringArray `json:"emails" gorm:"type:text[]" swaggertype:"array,string" example:"[email protected]"`- PhoneNumbers pq.StringArray `json:"phone_numbers" gorm:"type:text[]" swaggertype:"array,string" example:"+18005550199,+18005550100"`- Properties ContactProperties `json:"properties" gorm:"type:jsonb" swaggertype:"object,string"`- 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:02.302718+03:00"`-}--// TableName overrides the table name used by Contact.-func (Contact) TableName() string {- return "contacts"-}-```--- [ ] **Step 4: Run test to verify it passes**--Run: `cd api && go test -vet=off ./pkg/entities/ -run TestContactProperties`-Expected: PASS--- [ ] **Step 5: Commit**--```bash-git add api/pkg/entities/contact.go api/pkg/entities/contact_test.go-git commit -m "feat(api): add Contact entity and ContactProperties jsonb type"-```-------### Task 2: MessageThread ContactDetails field + AutoMigrate--**Files:**-- Modify: `api/pkg/entities/message_thread.go`-- Modify: `api/pkg/di/container.go` (AutoMigrate block ~L413)--**Interfaces:**-- Produces: `entities.MessageThread.ContactDetails *Contact` (JSON `contact_details`, `gorm:"-"`), `contacts` table auto-migrated.--- [ ] **Step 1: Add the non-persisted field**--In `api/pkg/entities/message_thread.go`, add after the `OrderTimestamp` field inside the `MessageThread` struct:--```go- // ContactDetails is resolved at read time and never persisted.- ContactDetails *Contact `json:"contact_details,omitempty" gorm:"-"`-```--- [ ] **Step 2: Register AutoMigrate**--In `api/pkg/di/container.go`, immediately after the `&entities.PhoneAPIKey{}` AutoMigrate block (~L413-415), add:--```go- if err = db.AutoMigrate(&entities.Contact{}); err != nil {- container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.Contact{}))- }-```--- [ ] **Step 3: Build to verify it compiles**--Run: `cd api && go build ./...`-Expected: builds with no errors.--- [ ] **Step 4: Commit**--```bash-git add api/pkg/entities/message_thread.go api/pkg/di/container.go-git commit -m "feat(api): add non-persisted ContactDetails on MessageThread and migrate contacts table"-```-------### Task 3: ContactRepository interface + GORM implementation--**Files:**-- Create: `api/pkg/repositories/contact_repository.go`-- Create: `api/pkg/repositories/gorm_contact_repository.go`-- Create: `api/pkg/repositories/gorm_contact_repository_test.go`--**Interfaces:**-- Consumes: `entities.Contact`, `repositories.IndexParams`, `repositories.ErrCodeNotFound`.-- Produces: `repositories.ContactRepository` with methods:- - `Store(ctx context.Context, contacts []*entities.Contact) error`- - `Update(ctx context.Context, contact *entities.Contact) error`- - `Load(ctx context.Context, userID entities.UserID, contactID uuid.UUID) (*entities.Contact, error)`- - `Index(ctx context.Context, userID entities.UserID, params IndexParams) (*[]entities.Contact, error)`- - `FetchAll(ctx context.Context, userID entities.UserID) (*[]entities.Contact, error)` (ordered `updated_at ASC` for tie-break)- - `Delete(ctx context.Context, userID entities.UserID, contactID uuid.UUID) error`- - `DeleteAllForUser(ctx context.Context, userID entities.UserID) error`- - Constructor: `NewGormContactRepository(logger, tracer, db) ContactRepository`--- [ ] **Step 1: Write the interface**--Create `api/pkg/repositories/contact_repository.go`:--```go-package repositories--import (- "context"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/google/uuid"-)--// ContactRepository loads and persists an entities.Contact-type ContactRepository interface {- // Store one or many new entities.Contact- Store(ctx context.Context, contacts []*entities.Contact) error-- // Update an existing entities.Contact- Update(ctx context.Context, contact *entities.Contact) error-- // Load a contact by ID for a user- Load(ctx context.Context, userID entities.UserID, contactID uuid.UUID) (*entities.Contact, error)-- // Index contacts for a user with optional search- Index(ctx context.Context, userID entities.UserID, params IndexParams) (*[]entities.Contact, error)-- // FetchAll returns every contact for a user ordered by updated_at ascending- FetchAll(ctx context.Context, userID entities.UserID) (*[]entities.Contact, error)-- // Delete a contact by ID for a user- Delete(ctx context.Context, userID entities.UserID, contactID uuid.UUID) error-- // DeleteAllForUser deletes all contacts for a user- DeleteAllForUser(ctx context.Context, userID entities.UserID) error-}-```--- [ ] **Step 2: Write the failing test**--Create `api/pkg/repositories/gorm_contact_repository_test.go`. Reuse the SQL-capturing conn-pool mock pattern already defined in `api/pkg/repositories/gorm_message_thread_repository_test.go` (the `messageThreadTestConnPool`, `messageThreadTestLogger`, and the `postgres.New(postgres.Config{Conn: ...})` DryRun setup). Add these focused tests:--```go-package repositories--import (- "context"- "testing"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/google/uuid"- "github.com/lib/pq"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"- "gorm.io/driver/postgres"- "gorm.io/gorm"-)--func newContactTestRepo(t *testing.T) (ContactRepository, *messageThreadTestConnPool) {- pool := &messageThreadTestConnPool{}- db, err := gorm.Open(- postgres.New(postgres.Config{Conn: pool, WithoutReturning: true}),- &gorm.Config{DisableAutomaticPing: true},- )- require.NoError(t, err)- logger := &messageThreadTestLogger{}- return NewGormContactRepository(logger, telemetry.NewOtelLogger("test", logger), db), pool-}--func TestGormContactRepository_Index_FiltersByUserAndQuery(t *testing.T) {- repo, _ := newContactTestRepo(t)-- _, err := repo.Index(context.Background(), entities.UserID("user-1"), IndexParams{Query: "alice", Limit: 20, Skip: 0})- assert.Nil(t, err)-}--func TestGormContactRepository_FetchAll_OrdersByUpdatedAtAsc(t *testing.T) {- repo, _ := newContactTestRepo(t)-- _, err := repo.FetchAll(context.Background(), entities.UserID("user-1"))- assert.Nil(t, err)-}--func TestGormContactRepository_Store_BuildsContact(t *testing.T) {- repo, _ := newContactTestRepo(t)-- err := repo.Store(context.Background(), []*entities.Contact{{- ID: uuid.New(),- UserID: entities.UserID("user-1"),- Name: "Alice",- Emails: pq.StringArray{"[email protected]"},- PhoneNumbers: pq.StringArray{"+18005550199"},- }})- assert.Nil(t, err)-}-```--(The `messageThreadTestConnPool` and `messageThreadTestLogger` types are already defined in `gorm_message_thread_repository_test.go` in the same package, so they are reused directly here.)--- [ ] **Step 3: Run test to verify it fails**--Run: `cd api && go test -vet=off ./pkg/repositories/ -run TestGormContactRepository`-Expected: FAIL / build error — `NewGormContactRepository` undefined.--- [ ] **Step 4: Write the implementation**--Create `api/pkg/repositories/gorm_contact_repository.go`:--```go-package repositories--import (- "context"- "errors"- "fmt"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/NdoleStudio/stacktrace"- "github.com/google/uuid"- "gorm.io/gorm"-)--// gormContactRepository is responsible for persisting entities.Contact-type gormContactRepository struct {- logger telemetry.Logger- tracer telemetry.Tracer- db *gorm.DB-}--// NewGormContactRepository creates the GORM version of the ContactRepository-func NewGormContactRepository(- logger telemetry.Logger,- tracer telemetry.Tracer,- db *gorm.DB,-) ContactRepository {- return &gormContactRepository{- logger: logger.WithService(fmt.Sprintf("%T", &gormContactRepository{})),- tracer: tracer,- db: db,- }-}--func (repository *gormContactRepository) Store(ctx context.Context, contacts []*entities.Contact) error {- ctx, span := repository.tracer.Start(ctx)- defer span.End()-- if len(contacts) == 0 {- return nil- }-- if err := repository.db.WithContext(ctx).Create(&contacts).Error; err != nil {- return repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot store [%d] contacts", len(contacts)))- }- return nil-}--func (repository *gormContactRepository) Update(ctx context.Context, contact *entities.Contact) error {- ctx, span := repository.tracer.Start(ctx)- defer span.End()-- if err := repository.db.WithContext(ctx).Save(contact).Error; err != nil {- return repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot update contact with ID [%s]", contact.ID))- }- return nil-}--func (repository *gormContactRepository) Load(ctx context.Context, userID entities.UserID, contactID uuid.UUID) (*entities.Contact, error) {- ctx, span := repository.tracer.Start(ctx)- defer span.End()-- contact := new(entities.Contact)- err := repository.db.WithContext(ctx).- Where("user_id = ?", userID).- Where("id = ?", contactID).- First(contact).Error- if errors.Is(err, gorm.ErrRecordNotFound) {- return nil, repository.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(err, ErrCodeNotFound, "contact with id [%s] not found for user [%s]", contactID, userID))- }- if err != nil {- return nil, repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot load contact with id [%s]", contactID))- }- return contact, nil-}--func (repository *gormContactRepository) Index(ctx context.Context, userID entities.UserID, params IndexParams) (*[]entities.Contact, error) {- ctx, span := repository.tracer.Start(ctx)- defer span.End()-- query := repository.db.WithContext(ctx).Where("user_id = ?", userID)-- if len(params.Query) > 0 {- queryPattern := "%" + params.Query + "%"- query = query.Where(- repository.db.Where("name ILIKE ?", queryPattern).- Or("array_to_string(emails, ',') ILIKE ?", queryPattern).- Or("array_to_string(phone_numbers, ',') ILIKE ?", queryPattern),- )- }-- contacts := new([]entities.Contact)- if err := query.Order("updated_at DESC").Limit(params.Limit).Offset(params.Skip).Find(contacts).Error; err != nil {- return nil, repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot index contacts for user [%s]", userID))- }- return contacts, nil-}--func (repository *gormContactRepository) FetchAll(ctx context.Context, userID entities.UserID) (*[]entities.Contact, error) {- ctx, span := repository.tracer.Start(ctx)- defer span.End()-- contacts := new([]entities.Contact)- if err := repository.db.WithContext(ctx).- Where("user_id = ?", userID).- Order("updated_at ASC").- Find(contacts).Error; err != nil {- return nil, repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot fetch all contacts for user [%s]", userID))- }- return contacts, nil-}--func (repository *gormContactRepository) Delete(ctx context.Context, userID entities.UserID, contactID uuid.UUID) error {- ctx, span := repository.tracer.Start(ctx)- defer span.End()-- if err := repository.db.WithContext(ctx).- Where("user_id = ?", userID).- Where("id = ?", contactID).- Delete(&entities.Contact{}).Error; err != nil {- return repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot delete contact with id [%s] for user [%s]", contactID, userID))- }- return nil-}--func (repository *gormContactRepository) DeleteAllForUser(ctx context.Context, userID entities.UserID) error {- ctx, span := repository.tracer.Start(ctx)- defer span.End()-- if err := repository.db.WithContext(ctx).- Where("user_id = ?", userID).- Delete(&entities.Contact{}).Error; err != nil {- return repository.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot delete all contacts for user [%s]", userID))- }- return nil-}-```--- [ ] **Step 5: Run test to verify it passes**--Run: `cd api && go test -vet=off ./pkg/repositories/ -run TestGormContactRepository`-Expected: PASS--- [ ] **Step 6: Commit**--```bash-git add api/pkg/repositories/contact_repository.go api/pkg/repositories/gorm_contact_repository.go api/pkg/repositories/gorm_contact_repository_test.go-git commit -m "feat(api): add ContactRepository with GORM implementation"-```-------### Task 4: Contact requests (store / update / index)--**Files:**-- Create: `api/pkg/requests/contact_store.go`-- Create: `api/pkg/requests/contact_update.go`-- Create: `api/pkg/requests/contact_index.go`-- Create: `api/pkg/requests/contact_store_test.go`--**Interfaces:**-- Produces:- - `requests.ContactItem{ Name string; Emails []string; PhoneNumbers []string; Properties map[string]string }`- - `requests.ContactStoreRequest{ Contacts []ContactItem }` with `UnmarshalJSON` accepting a JSON array or `{"contacts":[...]}`; methods `Sanitize()` and `ToContacts(userID entities.UserID) []*entities.Contact`.- - `requests.ContactUpdateRequest{ Name string; Emails []string; PhoneNumbers []string; Properties map[string]string }` with `Sanitize()` and `ApplyTo(contact *entities.Contact)`.- - `requests.ContactIndex{ Skip, Query, Limit string }` with `Sanitize()` and `ToIndexParams() repositories.IndexParams`.--- [ ] **Step 1: Write the failing test**--Create `api/pkg/requests/contact_store_test.go`:--```go-package requests--import (- "encoding/json"- "testing"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--func TestContactStoreRequest_UnmarshalArrayForm(t *testing.T) {- var request ContactStoreRequest- require.NoError(t, json.Unmarshal([]byte(`[{"name":"Alice","phone_numbers":["+18005550199"]}]`), &request))- assert.Equal(t, 1, len(request.Contacts))- assert.Equal(t, "Alice", request.Contacts[0].Name)-}--func TestContactStoreRequest_UnmarshalObjectForm(t *testing.T) {- var request ContactStoreRequest- require.NoError(t, json.Unmarshal([]byte(`{"contacts":[{"name":"Bob","phone_numbers":["+18005550100"]}]}`), &request))- assert.Equal(t, 1, len(request.Contacts))- assert.Equal(t, "Bob", request.Contacts[0].Name)-}--func TestContactStoreRequest_SanitizeNormalizesNumbers(t *testing.T) {- request := ContactStoreRequest{Contacts: []ContactItem{{- Name: " Alice ",- PhoneNumbers: []string{"18005550199"},- Emails: []string{" [email protected] "},- }}}- request = request.Sanitize()- assert.Equal(t, "Alice", request.Contacts[0].Name)- assert.Equal(t, "+18005550199", request.Contacts[0].PhoneNumbers[0])- assert.Equal(t, "[email protected]", request.Contacts[0].Emails[0])-}--func TestContactStoreRequest_ToContacts(t *testing.T) {- request := ContactStoreRequest{Contacts: []ContactItem{{- Name: "Alice",- PhoneNumbers: []string{"+18005550199"},- }}}- contacts := request.ToContacts(entities.UserID("user-1"))- require.Equal(t, 1, len(contacts))- assert.Equal(t, "Alice", contacts[0].Name)- assert.Equal(t, entities.UserID("user-1"), contacts[0].UserID)- assert.NotEqual(t, "", contacts[0].ID.String())-}-```--- [ ] **Step 2: Run test to verify it fails**--Run: `cd api && go test -vet=off ./pkg/requests/ -run TestContactStoreRequest`-Expected: FAIL / build error — types undefined.--- [ ] **Step 3: Write the implementations**--Create `api/pkg/requests/contact_store.go`:--```go-package requests--import (- "encoding/json"- "strings"- "time"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/google/uuid"- "github.com/lib/pq"-)--// ContactItem is a single contact in a create request.-type ContactItem struct {- Name string `json:"name" example:"Alice Smith"`- Emails []string `json:"emails"`- PhoneNumbers []string `json:"phone_numbers"`- Properties map[string]string `json:"properties"`-}--// ContactStoreRequest creates one or many contacts.-type ContactStoreRequest struct {- request- Contacts []ContactItem `json:"contacts"`-}--// UnmarshalJSON accepts either a JSON array of contacts or {"contacts":[...]}.-func (input *ContactStoreRequest) UnmarshalJSON(data []byte) error {- trimmed := strings.TrimSpace(string(data))- if strings.HasPrefix(trimmed, "[") {- var items []ContactItem- if err := json.Unmarshal(data, &items); err != nil {- return err- }- input.Contacts = items- return nil- }-- type alias ContactStoreRequest- var wrapper alias- if err := json.Unmarshal(data, &wrapper); err != nil {- return err- }- input.Contacts = wrapper.Contacts- return nil-}--// Sanitize trims and normalizes each contact item.-func (input ContactStoreRequest) Sanitize() ContactStoreRequest {- for index := range input.Contacts {- input.Contacts[index] = input.sanitizeItem(input.Contacts[index])- }- return input-}--func (input *ContactStoreRequest) sanitizeItem(item ContactItem) ContactItem {- item.Name = strings.TrimSpace(item.Name)-- numbers := input.removeStringDuplicates(input.removeEmptyStrings(item.PhoneNumbers))- item.PhoneNumbers = input.sanitizeAddresses(numbers)-- emails := input.removeEmptyStrings(item.Emails)- for i := range emails {- emails[i] = strings.ToLower(strings.TrimSpace(emails[i]))- }- item.Emails = input.removeStringDuplicates(emails)-- if item.Properties == nil {- item.Properties = map[string]string{}- }- return item-}--// ToContacts converts the request into persistable entities.Contact records.-func (input *ContactStoreRequest) ToContacts(userID entities.UserID) []*entities.Contact {- now := time.Now().UTC()- contacts := make([]*entities.Contact, 0, len(input.Contacts))- for _, item := range input.Contacts {- contacts = append(contacts, &entities.Contact{- ID: uuid.New(),- UserID: userID,- Name: item.Name,- Emails: pq.StringArray(item.Emails),- PhoneNumbers: pq.StringArray(item.PhoneNumbers),- Properties: entities.ContactProperties(item.Properties),- CreatedAt: now,- UpdatedAt: now,- })- }- return contacts-}-```--Create `api/pkg/requests/contact_update.go`:--```go-package requests--import (- "strings"- "time"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/lib/pq"-)--// ContactUpdateRequest updates an existing contact.-type ContactUpdateRequest struct {- request- Name string `json:"name" example:"Alice Smith"`- Emails []string `json:"emails"`- PhoneNumbers []string `json:"phone_numbers"`- Properties map[string]string `json:"properties"`-}--// Sanitize trims and normalizes the update request.-func (input ContactUpdateRequest) Sanitize() ContactUpdateRequest {- input.Name = strings.TrimSpace(input.Name)-- numbers := input.removeStringDuplicates(input.removeEmptyStrings(input.PhoneNumbers))- input.PhoneNumbers = input.sanitizeAddresses(numbers)-- emails := input.removeEmptyStrings(input.Emails)- for i := range emails {- emails[i] = strings.ToLower(strings.TrimSpace(emails[i]))- }- input.Emails = input.removeStringDuplicates(emails)-- if input.Properties == nil {- input.Properties = map[string]string{}- }- return input-}--// ApplyTo mutates an existing contact with the update values.-func (input *ContactUpdateRequest) ApplyTo(contact *entities.Contact) {- contact.Name = input.Name- contact.Emails = pq.StringArray(input.Emails)- contact.PhoneNumbers = pq.StringArray(input.PhoneNumbers)- contact.Properties = entities.ContactProperties(input.Properties)- contact.UpdatedAt = time.Now().UTC()-}-```--Create `api/pkg/requests/contact_index.go`:--```go-package requests--import (- "strings"-- "github.com/NdoleStudio/httpsms/pkg/repositories"-)--// ContactIndex lists contacts for a user.-type ContactIndex struct {- request- Skip string `json:"skip" query:"skip"`- Query string `json:"query" query:"query"`- Limit string `json:"limit" query:"limit"`-}--// Sanitize sets defaults for the list request.-func (input *ContactIndex) Sanitize() ContactIndex {- if strings.TrimSpace(input.Limit) == "" {- input.Limit = "20"- }- input.Query = strings.TrimSpace(input.Query)- input.Skip = strings.TrimSpace(input.Skip)- if input.Skip == "" {- input.Skip = "0"- }- return *input-}--// ToIndexParams converts the request into repositories.IndexParams.-func (input *ContactIndex) ToIndexParams() repositories.IndexParams {- return repositories.IndexParams{- Skip: input.getInt(input.Skip),- Query: input.Query,- Limit: input.getInt(input.Limit),- }-}-```--- [ ] **Step 4: Run test to verify it passes**--Run: `cd api && go test -vet=off ./pkg/requests/ -run TestContactStoreRequest`-Expected: PASS--- [ ] **Step 5: Commit**--```bash-git add api/pkg/requests/contact_store.go api/pkg/requests/contact_update.go api/pkg/requests/contact_index.go api/pkg/requests/contact_store_test.go-git commit -m "feat(api): add contact store/update/index requests"-```-------### Task 5: ContactHandlerValidator (store / update / index / CSV upload)--**Files:**-- Create: `api/pkg/validators/contact_handler_validator.go`-- Create: `api/pkg/validators/contact_handler_validator_test.go`--**Interfaces:**-- Consumes: `requests.ContactStoreRequest`, `requests.ContactUpdateRequest`, `requests.ContactIndex`, `requests.ContactItem`.-- Produces: `validators.ContactHandlerValidator` with:- - `NewContactHandlerValidator(logger, tracer) *ContactHandlerValidator`- - `ValidateStore(ctx, request requests.ContactStoreRequest) url.Values`- - `ValidateUpdate(ctx, request requests.ContactUpdateRequest) url.Values`- - `ValidateIndex(ctx, request requests.ContactIndex) url.Values`- - `ValidateUpload(ctx, userID entities.UserID, header *multipart.FileHeader) ([]requests.ContactItem, url.Values)`--- [ ] **Step 1: Write the failing test**--Create `api/pkg/validators/contact_handler_validator_test.go`:--```go-package validators--import (- "context"- "testing"-- "github.com/NdoleStudio/httpsms/pkg/requests"- "github.com/stretchr/testify/assert"-)--func newContactValidator() *ContactHandlerValidator {- return &ContactHandlerValidator{}-}--func TestContactValidator_ValidateStore_Valid(t *testing.T) {- v := newContactValidator()- errs := v.ValidateStore(context.Background(), requests.ContactStoreRequest{Contacts: []requests.ContactItem{{- Name: "Alice",- PhoneNumbers: []string{"+18005550199"},- Emails: []string{"[email protected]"},- }}})- assert.Equal(t, 0, len(errs))-}--func TestContactValidator_ValidateStore_MissingName(t *testing.T) {- v := newContactValidator()- errs := v.ValidateStore(context.Background(), requests.ContactStoreRequest{Contacts: []requests.ContactItem{{- PhoneNumbers: []string{"+18005550199"},- }}})- assert.NotEqual(t, 0, len(errs))-}--func TestContactValidator_ValidateStore_InvalidNumber(t *testing.T) {- v := newContactValidator()- errs := v.ValidateStore(context.Background(), requests.ContactStoreRequest{Contacts: []requests.ContactItem{{- Name: "Alice",- PhoneNumbers: []string{"not-a-number"},- }}})- assert.NotEqual(t, 0, len(errs))-}--func TestContactValidator_ValidateStore_EmptyBatch(t *testing.T) {- v := newContactValidator()- errs := v.ValidateStore(context.Background(), requests.ContactStoreRequest{Contacts: nil})- assert.NotEqual(t, 0, len(errs))-}--func TestContactValidator_ValidateStore_InvalidEmail(t *testing.T) {- v := newContactValidator()- errs := v.ValidateStore(context.Background(), requests.ContactStoreRequest{Contacts: []requests.ContactItem{{- Name: "Alice",- PhoneNumbers: []string{"+18005550199"},- Emails: []string{"not-an-email"},- }}})- assert.NotEqual(t, 0, len(errs))-}-```--(If `telemetry.NewOtelLogger` for the tracer differs in your package, `ValidateUpload` is the only method needing a real logger/tracer; the store/update/index tests use a zero-value validator.)--- [ ] **Step 2: Run test to verify it fails**--Run: `cd api && go test -vet=off ./pkg/validators/ -run TestContactValidator`-Expected: FAIL / build error — `NewContactHandlerValidator` undefined.--- [ ] **Step 3: Write the implementation**--Create `api/pkg/validators/contact_handler_validator.go`:--```go-package validators--import (- "bytes"- "context"- "fmt"- "io"- "mime/multipart"- "net/mail"- "net/url"- "strings"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/requests"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/NdoleStudio/stacktrace"- "github.com/jszwec/csvutil"- "github.com/nyaruka/phonenumbers"- "github.com/thedevsaddam/govalidator"-)--// ContactHandlerValidator validates models used in handlers.ContactHandler-type ContactHandlerValidator struct {- validator- logger telemetry.Logger- tracer telemetry.Tracer-}--// NewContactHandlerValidator creates a new handlers.ContactHandler validator-func NewContactHandlerValidator(- logger telemetry.Logger,- tracer telemetry.Tracer,-) *ContactHandlerValidator {- return &ContactHandlerValidator{- logger: logger.WithService(fmt.Sprintf("%T", &ContactHandlerValidator{})),- tracer: tracer,- }-}--const maxContactBatch = 1000--// ValidateStore validates a create request of one or many contacts.-func (v *ContactHandlerValidator) ValidateStore(_ context.Context, request requests.ContactStoreRequest) url.Values {- result := url.Values{}- if len(request.Contacts) == 0 {- result.Add("contacts", "You must provide at least one contact.")- return result- }- if len(request.Contacts) > maxContactBatch {- result.Add("contacts", fmt.Sprintf("You cannot create more than %d contacts in one request.", maxContactBatch))- return result- }- for index, item := range request.Contacts {- v.validateItem(result, index, item)- }- return result-}--// ValidateUpdate validates a single contact update.-func (v *ContactHandlerValidator) ValidateUpdate(_ context.Context, request requests.ContactUpdateRequest) url.Values {- result := url.Values{}- v.validateItem(result, 0, requests.ContactItem{- Name: request.Name,- Emails: request.Emails,- PhoneNumbers: request.PhoneNumbers,- Properties: request.Properties,- })- return result-}--func (v *ContactHandlerValidator) validateItem(result url.Values, index int, item requests.ContactItem) {- row := index + 1- if strings.TrimSpace(item.Name) == "" {- result.Add("contacts", fmt.Sprintf("Contact [%d]: The name is required.", row))- }- if len(item.PhoneNumbers) == 0 {- result.Add("contacts", fmt.Sprintf("Contact [%d]: At least one phone number is required.", row))- }- for _, number := range item.PhoneNumbers {- if _, err := phonenumbers.Parse(number, phonenumbers.UNKNOWN_REGION); err != nil {- result.Add("contacts", fmt.Sprintf("Contact [%d]: The phone number [%s] is not a valid E.164 phone number.", row, number))- }- }- for _, email := range item.Emails {- if _, err := mail.ParseAddress(email); err != nil {- result.Add("contacts", fmt.Sprintf("Contact [%d]: The email [%s] is not a valid email address.", row, email))- }- }-}--// ValidateIndex validates the list request.-func (v *ContactHandlerValidator) ValidateIndex(_ context.Context, request requests.ContactIndex) url.Values {- value := govalidator.New(govalidator.Options{- Data: &request,- Rules: govalidator.MapData{- "limit": []string{"required", "numeric", "min:1", "max:100"},- "skip": []string{"required", "numeric", "min:0"},- "query": []string{"max:100"},- },- })- return value.ValidateStruct()-}--type contactCSVRow struct {- Name string `csv:"Name"`- Emails string `csv:"Emails"`- PhoneNumbers string `csv:"PhoneNumbers"`-}--// ValidateUpload parses and validates a CSV upload (CSV only).-func (v *ContactHandlerValidator) ValidateUpload(ctx context.Context, userID entities.UserID, header *multipart.FileHeader) ([]requests.ContactItem, url.Values) {- ctx, span, ctxLogger := v.tracer.StartWithLogger(ctx, v.logger)- defer span.End()- _ = ctx-- result := url.Values{}-- if header.Header.Get("Content-Type") != "text/csv" && !strings.HasSuffix(strings.ToLower(header.Filename), ".csv") {- result.Add("document", fmt.Sprintf("The file [%s] is not a valid CSV file. Only CSV files are supported.", header.Filename))- return nil, result- }-- if header.Size >= 500000 {- result.Add("document", "The CSV file must be less than 500 KB.")- return nil, result- }-- file, err := header.Open()- if err != nil {- ctxLogger.Error(stacktrace.Propagatef(err, "cannot open file [%s] for user [%s]", header.Filename, userID))- result.Add("document", fmt.Sprintf("Cannot open the uploaded file [%s].", header.Filename))- return nil, result- }- defer func() { _ = file.Close() }()-- buffer := new(bytes.Buffer)- if _, err = io.Copy(buffer, file); err != nil {- ctxLogger.Error(stacktrace.Propagatef(err, "cannot read file [%s] for user [%s]", header.Filename, userID))- result.Add("document", fmt.Sprintf("Cannot read the uploaded file [%s].", header.Filename))- return nil, result- }-- var rows []contactCSVRow- if err = csvutil.Unmarshal(buffer.Bytes(), &rows); err != nil {- ctxLogger.Error(stacktrace.Propagatef(err, "cannot parse CSV file [%s] for user [%s]", header.Filename, userID))- result.Add("document", fmt.Sprintf("Cannot parse the uploaded CSV file [%s]. Use the official httpSMS contacts template.", header.Filename))- return nil, result- }-- if len(rows) > maxContactBatch {- result.Add("document", fmt.Sprintf("The uploaded file must contain less than %d records.", maxContactBatch))- return nil, result- }-- items := make([]requests.ContactItem, 0, len(rows))- for _, row := range rows {- if strings.TrimSpace(row.Name) == "" && strings.TrimSpace(row.PhoneNumbers) == "" {- continue- }- items = append(items, requests.ContactItem{- Name: strings.TrimSpace(row.Name),- Emails: splitMultiValue(row.Emails),- PhoneNumbers: splitMultiValue(row.PhoneNumbers),- })- }-- if len(items) == 0 {- result.Add("document", "The uploaded file doesn't contain any valid records.")- }- return items, result-}--func splitMultiValue(value string) []string {- if strings.TrimSpace(value) == "" {- return nil- }- fields := strings.FieldsFunc(value, func(r rune) bool { return r == ';' || r == ',' })- var result []string- for _, field := range fields {- field = strings.TrimSpace(field)- if field != "" {- result = append(result, field)- }- }- return result-}-```--- [ ] **Step 4: Run test to verify it passes**--Run: `cd api && go test -vet=off ./pkg/validators/ -run TestContactValidator`-Expected: PASS--- [ ] **Step 5: Commit**--```bash-git add api/pkg/validators/contact_handler_validator.go api/pkg/validators/contact_handler_validator_test.go-git commit -m "feat(api): add ContactHandlerValidator with CSV-only upload parsing"-```-------### Task 6: ContactService (CRUD + contact-map cache + invalidation)--**Files:**-- Create: `api/pkg/services/contact_service.go`-- Create: `api/pkg/services/contact_service_test.go`--**Interfaces:**-- Consumes: `repositories.ContactRepository`, `cache.Cache`, `entities.Contact`, `repositories.IndexParams`.-- Produces: `services.ContactService` with:- - `NewContactService(logger, tracer, repository repositories.ContactRepository, appCache cache.Cache) *ContactService`- - `CreateMany(ctx, userID entities.UserID, contacts []*entities.Contact) error`- - `Get(ctx, userID entities.UserID, contactID uuid.UUID) (*entities.Contact, error)`- - `Index(ctx, userID entities.UserID, params repositories.IndexParams) (*[]entities.Contact, error)`- - `Update(ctx, contact *entities.Contact) error`- - `Delete(ctx, userID entities.UserID, contactID uuid.UUID) error`- - `GetContactMap(ctx, userID entities.UserID) (map[string]*entities.Contact, error)` (cache-backed; most-recently-updated wins)--- [ ] **Step 1: Write the failing test**--Create `api/pkg/services/contact_service_test.go`:--```go-package services--import (- "context"- "testing"- "time"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/repositories"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/NdoleStudio/stacktrace"- "github.com/google/uuid"- "github.com/lib/pq"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--type fakeCache struct {- store map[string]string-}--func newFakeCache() *fakeCache { return &fakeCache{store: map[string]string{}} }--func (c *fakeCache) Get(_ context.Context, key string) (string, error) {- value, ok := c.store[key]- if !ok {- return "", assertMiss{}- }- return value, nil-}--func (c *fakeCache) Set(_ context.Context, key, value string, _ time.Duration) error {- c.store[key] = value- return nil-}--type assertMiss struct{}--func (assertMiss) Error() string { return "miss" }--type fakeContactRepo struct {- contacts []*entities.Contact- fetchAll int-}--func (r *fakeContactRepo) Store(_ context.Context, contacts []*entities.Contact) error {- r.contacts = append(r.contacts, contacts...)- return nil-}-func (r *fakeContactRepo) Update(_ context.Context, contact *entities.Contact) error { return nil }-func (r *fakeContactRepo) Load(_ context.Context, _ entities.UserID, id uuid.UUID) (*entities.Contact, error) {- for _, c := range r.contacts {- if c.ID == id {- return c, nil- }- }- return nil, stacktrace.NewErrorWithCodef(repositories.ErrCodeNotFound, "contact [%s] not found", id)-}-func (r *fakeContactRepo) Index(_ context.Context, _ entities.UserID, _ repositories.IndexParams) (*[]entities.Contact, error) {- out := []entities.Contact{}- return &out, nil-}-func (r *fakeContactRepo) FetchAll(_ context.Context, _ entities.UserID) (*[]entities.Contact, error) {- r.fetchAll++- out := make([]entities.Contact, 0, len(r.contacts))- for _, c := range r.contacts {- out = append(out, *c)- }- return &out, nil-}-func (r *fakeContactRepo) Delete(_ context.Context, _ entities.UserID, _ uuid.UUID) error { return nil }-func (r *fakeContactRepo) DeleteAllForUser(_ context.Context, _ entities.UserID) error { return nil }--func newContactService(repo repositories.ContactRepository, appCache *fakeCache) *ContactService {- logger := telemetry.NewZerologLogger("test", nil, nil, nil)- return NewContactService(logger, telemetry.NewOtelLogger("test", logger), repo, appCache)-}--func TestContactService_GetContactMap_TieBreakMostRecentlyUpdated(t *testing.T) {- older := &entities.Contact{ID: uuid.New(), UserID: "u1", Name: "Old", PhoneNumbers: pq.StringArray{"+18005550199"}, UpdatedAt: time.Now().Add(-time.Hour)}- newer := &entities.Contact{ID: uuid.New(), UserID: "u1", Name: "New", PhoneNumbers: pq.StringArray{"+18005550199"}, UpdatedAt: time.Now()}- // FetchAll returns ASC by updated_at, so older first then newer.- repo := &fakeContactRepo{contacts: []*entities.Contact{older, newer}}- service := newContactService(repo, newFakeCache())-- result, err := service.GetContactMap(context.Background(), entities.UserID("u1"))- require.NoError(t, err)- require.NotNil(t, result["+18005550199"])- assert.Equal(t, "New", result["+18005550199"].Name)-}--func TestContactService_GetContactMap_UsesCacheOnSecondCall(t *testing.T) {- repo := &fakeContactRepo{contacts: []*entities.Contact{{ID: uuid.New(), UserID: "u1", Name: "Alice", PhoneNumbers: pq.StringArray{"+18005550199"}}}}- service := newContactService(repo, newFakeCache())-- _, err := service.GetContactMap(context.Background(), entities.UserID("u1"))- require.NoError(t, err)- _, err = service.GetContactMap(context.Background(), entities.UserID("u1"))- require.NoError(t, err)-- assert.Equal(t, 1, repo.fetchAll)-}--func TestContactService_CreateMany_InvalidatesCache(t *testing.T) {- repo := &fakeContactRepo{contacts: []*entities.Contact{{ID: uuid.New(), UserID: "u1", Name: "Alice", PhoneNumbers: pq.StringArray{"+18005550199"}}}}- appCache := newFakeCache()- service := newContactService(repo, appCache)-- _, err := service.GetContactMap(context.Background(), entities.UserID("u1"))- require.NoError(t, err)- require.Equal(t, 1, repo.fetchAll)-- require.NoError(t, service.CreateMany(context.Background(), entities.UserID("u1"), []*entities.Contact{{ID: uuid.New(), UserID: "u1", Name: "Bob", PhoneNumbers: pq.StringArray{"+18005550100"}}}))-- _, err = service.GetContactMap(context.Background(), entities.UserID("u1"))- require.NoError(t, err)- assert.Equal(t, 2, repo.fetchAll)-}-```--- [ ] **Step 2: Run test to verify it fails**--Run: `cd api && go test -vet=off ./pkg/services/ -run TestContactService`-Expected: FAIL / build error — `NewContactService` undefined.--- [ ] **Step 3: Write the implementation**--Create `api/pkg/services/contact_service.go`:--```go-package services--import (- "context"- "encoding/json"- "fmt"- "time"-- "github.com/NdoleStudio/httpsms/pkg/cache"- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/repositories"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/NdoleStudio/stacktrace"- "github.com/google/uuid"-)--const contactMapCacheTTL = 24 * time.Hour--// ContactService handles contact business logic.-type ContactService struct {- service- logger telemetry.Logger- tracer telemetry.Tracer- repository repositories.ContactRepository- cache cache.Cache-}--// NewContactService creates a new ContactService.-func NewContactService(- logger telemetry.Logger,- tracer telemetry.Tracer,- repository repositories.ContactRepository,- appCache cache.Cache,-) (s *ContactService) {- return &ContactService{- logger: logger.WithService(fmt.Sprintf("%T", s)),- tracer: tracer,- repository: repository,- cache: appCache,- }-}--func (service *ContactService) cacheKey(userID entities.UserID) string {- return fmt.Sprintf("contacts.map.%s", userID)-}--// CreateMany persists one or many contacts then invalidates the cache.-func (service *ContactService) CreateMany(ctx context.Context, userID entities.UserID, contacts []*entities.Contact) error {- ctx, span := service.tracer.Start(ctx)- defer span.End()-- if err := service.repository.Store(ctx, contacts); err != nil {- return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot store [%d] contacts for user [%s]", len(contacts), userID))- }- service.invalidate(ctx, userID)- return nil-}--// Get returns a contact by ID.-func (service *ContactService) Get(ctx context.Context, userID entities.UserID, contactID uuid.UUID) (*entities.Contact, error) {- ctx, span := service.tracer.Start(ctx)- defer span.End()-- contact, err := service.repository.Load(ctx, userID, contactID)- if err != nil {- return nil, service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCodef(err, stacktrace.GetCode(err), "cannot load contact [%s] for user [%s]", contactID, userID))- }- return contact, nil-}--// Index lists contacts for a user.-func (service *ContactService) Index(ctx context.Context, userID entities.UserID, params repositories.IndexParams) (*[]entities.Contact, error) {- ctx, span := service.tracer.Start(ctx)- defer span.End()-- contacts, err := service.repository.Index(ctx, userID, params)- if err != nil {- return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot index contacts for user [%s]", userID))- }- return contacts, nil-}--// Update saves a contact and invalidates the cache.-func (service *ContactService) Update(ctx context.Context, contact *entities.Contact) error {- ctx, span := service.tracer.Start(ctx)- defer span.End()-- if err := service.repository.Update(ctx, contact); err != nil {- return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot update contact [%s]", contact.ID))- }- service.invalidate(ctx, contact.UserID)- return nil-}--// Delete removes a contact and invalidates the cache.-func (service *ContactService) Delete(ctx context.Context, userID entities.UserID, contactID uuid.UUID) error {- ctx, span := service.tracer.Start(ctx)- defer span.End()-- if err := service.repository.Delete(ctx, userID, contactID); err != nil {- return service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot delete contact [%s] for user [%s]", contactID, userID))- }- service.invalidate(ctx, userID)- return nil-}--// GetContactMap returns the cached phone_number -> *Contact map for a user.-func (service *ContactService) GetContactMap(ctx context.Context, userID entities.UserID) (map[string]*entities.Contact, error) {- ctx, span := service.tracer.Start(ctx)- defer span.End()-- if raw, err := service.cache.Get(ctx, service.cacheKey(userID)); err == nil && raw != "" {- result := map[string]*entities.Contact{}- if jsonErr := json.Unmarshal([]byte(raw), &result); jsonErr == nil {- return result, nil- }- }-- contacts, err := service.repository.FetchAll(ctx, userID)- if err != nil {- return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "cannot fetch contacts to build map for user [%s]", userID))- }-- // FetchAll returns updated_at ASC, so later (more recently updated) contacts overwrite earlier ones.- result := map[string]*entities.Contact{}- for index := range *contacts {- contact := (*contacts)[index]- for _, number := range contact.PhoneNumbers {- copied := contact- result[number] = &copied- }- }-- if encoded, encodeErr := json.Marshal(result); encodeErr == nil {- _ = service.cache.Set(ctx, service.cacheKey(userID), string(encoded), contactMapCacheTTL)- }-- return result, nil-}--// invalidate overwrites the cache key with an empty marker (Cache has no Delete).-func (service *ContactService) invalidate(ctx context.Context, userID entities.UserID) {- if err := service.cache.Set(ctx, service.cacheKey(userID), "", contactMapCacheTTL); err != nil {- service.logger.Error(stacktrace.Propagatef(err, "cannot invalidate contact map cache for user [%s]", userID))- }-}-```--- [ ] **Step 4: Run test to verify it passes**--Run: `cd api && go test -vet=off ./pkg/services/ -run TestContactService`-Expected: PASS--- [ ] **Step 5: Commit**--```bash-git add api/pkg/services/contact_service.go api/pkg/services/contact_service_test.go-git commit -m "feat(api): add ContactService with cached contact-map resolution"-```-------### Task 7: Opt-in contact resolution in GetThreads--**Files:**-- Modify: `api/pkg/services/message_thread_service.go` (struct, constructor, `MessageThreadGetParams`, `GetThreads`)-- Modify: `api/pkg/requests/message_thread_index_request.go` (`Contacts` param + `ToGetParams`)-- Modify: `api/pkg/handlers/message_thread_handler_test.go` (add 6th constructor arg)-- Create: `api/pkg/services/message_thread_service_contacts_test.go`-- Create: `api/pkg/requests/message_thread_index_request_test.go`--**Interfaces:**-- Consumes: `ContactService.GetContactMap(ctx, userID) (map[string]*entities.Contact, error)` (Task 6); `entities.MessageThread.ContactDetails` (Task 2).-- Produces: `MessageThreadGetParams.WithContacts bool`; `MessageThreadService` gains a `contactService contactMapProvider` field where `contactMapProvider` is:- ```go- type contactMapProvider interface {- GetContactMap(ctx context.Context, userID entities.UserID) (map[string]*entities.Contact, error)- }- ```- `*ContactService` satisfies `contactMapProvider`. New constructor signature:- `NewMessageThreadService(logger, tracer, repository, phoneRepository, eventDispatcher, contactService contactMapProvider) *MessageThreadService`--- [ ] **Step 1: Write the failing tests**--Create `api/pkg/requests/message_thread_index_request_test.go`:--```go-package requests--import (- "testing"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/stretchr/testify/assert"-)--func TestMessageThreadIndex_ToGetParams_WithContacts(t *testing.T) {- input := (&MessageThreadIndex{Owner: "+18005550199", Contacts: "true"}).Sanitize()- params := input.ToGetParams(entities.UserID("u1"))- assert.True(t, params.WithContacts)-}--func TestMessageThreadIndex_ToGetParams_WithoutContacts(t *testing.T) {- input := (&MessageThreadIndex{Owner: "+18005550199"}).Sanitize()- params := input.ToGetParams(entities.UserID("u1"))- assert.False(t, params.WithContacts)-}-```--Create `api/pkg/services/message_thread_service_contacts_test.go`:--```go-package services--import (- "context"- "testing"-- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/repositories"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--type stubThreadRepo struct {- repositories.MessageThreadRepository- threads []entities.MessageThread-}--func (r *stubThreadRepo) Index(_ context.Context, _ entities.UserID, _ string, _ bool, _ repositories.IndexParams) (*[]entities.MessageThread, error) {- out := make([]entities.MessageThread, len(r.threads))- copy(out, r.threads)- return &out, nil-}--type stubContactProvider struct {- contactMap map[string]*entities.Contact- calls int-}--func (p *stubContactProvider) GetContactMap(_ context.Context, _ entities.UserID) (map[string]*entities.Contact, error) {- p.calls++- return p.contactMap, nil-}--func newThreadServiceWithContacts(repo repositories.MessageThreadRepository, provider contactMapProvider) *MessageThreadService {- logger := telemetry.NewZerologLogger("test", nil, nil, nil)- return NewMessageThreadService(logger, telemetry.NewOtelLogger("test", logger), repo, nil, nil, provider)-}--func TestGetThreads_AttachesContactDetailsWhenWithContacts(t *testing.T) {- repo := &stubThreadRepo{threads: []entities.MessageThread{{Contact: "+18005550199"}, {Contact: "+18005550100"}}}- provider := &stubContactProvider{contactMap: map[string]*entities.Contact{"+18005550199": {Name: "Alice"}}}- service := newThreadServiceWithContacts(repo, provider)-- threads, err := service.GetThreads(context.Background(), MessageThreadGetParams{UserID: "u1", WithContacts: true})- require.NoError(t, err)- require.Len(t, *threads, 2)- require.NotNil(t, (*threads)[0].ContactDetails)- assert.Equal(t, "Alice", (*threads)[0].ContactDetails.Name)- assert.Nil(t, (*threads)[1].ContactDetails)-}--func TestGetThreads_SkipsContactLookupWhenFlagOff(t *testing.T) {- repo := &stubThreadRepo{threads: []entities.MessageThread{{Contact: "+18005550199"}}}- provider := &stubContactProvider{contactMap: map[string]*entities.Contact{"+18005550199": {Name: "Alice"}}}- service := newThreadServiceWithContacts(repo, provider)-- threads, err := service.GetThreads(context.Background(), MessageThreadGetParams{UserID: "u1", WithContacts: false})- require.NoError(t, err)- assert.Nil(t, (*threads)[0].ContactDetails)- assert.Equal(t, 0, provider.calls)-}-```--- [ ] **Step 2: Run tests to verify they fail**--Run: `cd api && go test -vet=off ./pkg/requests/ -run TestMessageThreadIndex_ToGetParams && go test -vet=off ./pkg/services/ -run TestGetThreads`-Expected: FAIL / build error — `Contacts`, `WithContacts`, and the 6-arg constructor do not exist yet.--- [ ] **Step 3: Implement request changes**--In `api/pkg/requests/message_thread_index_request.go`, add the field to the struct:--```go- Owner string `json:"owner" query:"owner"`- Contacts string `json:"contacts" query:"contacts" example:"true"`-```--Add sanitisation inside `Sanitize()` (before `return *input`):--```go- input.Contacts = input.sanitizeBool(input.Contacts)-```--Add the field to the returned params in `ToGetParams`:--```go- UserID: userID,- IsArchived: input.getBool(input.IsArchived),- Owner: input.Owner,- WithContacts: input.getBool(input.Contacts),- }-```--- [ ] **Step 4: Implement service changes**--In `api/pkg/services/message_thread_service.go` add the provider interface (top-level, after imports):--```go-// contactMapProvider supplies the phone_number -> *Contact map for a user.-type contactMapProvider interface {- GetContactMap(ctx context.Context, userID entities.UserID) (map[string]*entities.Contact, error)-}-```--Add the field to the struct:--```go- eventDispatcher *EventDispatcher- contactService contactMapProvider-```--Update the constructor:--```go-func NewMessageThreadService(- logger telemetry.Logger,- tracer telemetry.Tracer,- repository repositories.MessageThreadRepository,- phoneRepository repositories.PhoneRepository,- eventDispatcher *EventDispatcher,- contactService contactMapProvider,-) (s *MessageThreadService) {- return &MessageThreadService{- logger: logger.WithService(fmt.Sprintf("%T", s)),- tracer: tracer,- eventDispatcher: eventDispatcher,- repository: repository,- phoneRepository: phoneRepository,- contactService: contactService,- }-}-```--Add `WithContacts` to the params struct:--```go-type MessageThreadGetParams struct {- repositories.IndexParams- IsArchived bool- WithContacts bool- UserID entities.UserID- Owner string-}-```--Extend `GetThreads` to attach contact details (replace its body):--```go-func (service *MessageThreadService) GetThreads(ctx context.Context, params MessageThreadGetParams) (*[]entities.MessageThread, error) {- ctx, span := service.tracer.Start(ctx)- defer span.End()-- ctxLogger := service.tracer.CtxLogger(service.logger, span)-- threads, err := service.repository.Index(ctx, params.UserID, params.Owner, params.IsArchived, params.IndexParams)- if err != nil {- return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(err, "could not fetch messages threads for params [%+#v]", params))- }-- if params.WithContacts && service.contactService != nil && len(*threads) > 0 {- contactMap, mapErr := service.contactService.GetContactMap(ctx, params.UserID)- if mapErr != nil {- ctxLogger.Error(service.tracer.WrapErrorSpan(span, stacktrace.Propagatef(mapErr, "cannot build contact map for user [%s]", params.UserID)))- } else {- for index := range *threads {- if contact, ok := contactMap[(*threads)[index].Contact]; ok {- (*threads)[index].ContactDetails = contact- }- }- }- }-- ctxLogger.Info(fmt.Sprintf("fetched [%d] threads with params [%+#v]", len(*threads), params))- return threads, nil-}-```--- [ ] **Step 5: Update DI wiring and existing callers**--In `api/pkg/di/container.go`, find `NewMessageThreadService(...)` and append `container.ContactService()` as the final argument (the `ContactService()` getter is added in Task 8; if wiring Task 8 first, this compiles immediately — otherwise temporarily pass `nil` and restore in Task 8).--Also update the existing test `api/pkg/handlers/message_thread_handler_test.go`: its call `services.NewMessageThreadService(logger, tracer, &messageThreadHandlerRepositoryStub{}, nil, nil)` now needs a sixth argument — change it to `services.NewMessageThreadService(logger, tracer, &messageThreadHandlerRepositoryStub{}, nil, nil, nil)`.--- [ ] **Step 6: Run tests to verify they pass**--Run: `cd api && go test -vet=off ./pkg/requests/ -run TestMessageThreadIndex_ToGetParams && go test -vet=off ./pkg/services/ -run TestGetThreads`-Expected: PASS--- [ ] **Step 7: Commit**--```bash-git add api/pkg/services/message_thread_service.go api/pkg/services/message_thread_service_contacts_test.go api/pkg/requests/message_thread_index_request.go api/pkg/requests/message_thread_index_request_test.go api/pkg/handlers/message_thread_handler_test.go api/pkg/di/container.go-git commit -m "feat(api): opt-in contact resolution for message threads via ?contacts=true"-```-------### Task 8: ContactHandler + DI wiring + route registration--**Files:**-- Create: `api/pkg/handlers/contact_handler.go`-- Create: `api/pkg/handlers/contact_handler_test.go`-- Modify: `api/pkg/di/container.go` (getters, AutoMigrate, RegisterContactRoutes, wire ContactService into MessageThreadService)--**Interfaces:**-- Consumes: `services.ContactService` (Task 6), `validators.ContactHandlerValidator` (Task 5), `requests.*` (Task 4), `repositories.ErrCodeNotFound`.-- Produces: `handlers.ContactHandler` with `NewContactHandler(logger, tracer, validator *validators.ContactHandlerValidator, service *services.ContactService) *ContactHandler` and `RegisterRoutes(router, ...middlewares)`. Routes: `GET /v1/contacts`, `POST /v1/contacts`, `POST /v1/contacts/upload`, `PUT /v1/contacts/:contactID`, `DELETE /v1/contacts/:contactID`. New DI getters: `container.ContactRepository()`, `container.ContactService()`, `container.ContactHandlerValidator()`, `container.ContactHandler()`, `container.RegisterContactRoutes()`.--- [ ] **Step 1: Write the failing test**--Create `api/pkg/handlers/contact_handler_test.go`:--```go-package handlers--import (- "bytes"- "context"- "net/http"- "net/http/httptest"- "testing"- "time"-- "github.com/NdoleStudio/httpsms/pkg/cache"- "github.com/NdoleStudio/httpsms/pkg/entities"- "github.com/NdoleStudio/httpsms/pkg/middlewares"- "github.com/NdoleStudio/httpsms/pkg/repositories"- "github.com/NdoleStudio/httpsms/pkg/services"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/NdoleStudio/httpsms/pkg/validators"- "github.com/gofiber/fiber/v3"- "github.com/google/uuid"- ttlCache "github.com/patrickmn/go-cache"- "github.com/stretchr/testify/require"-)--type contactHandlerRepoStub struct {- stored []*entities.Contact-}--func (s *contactHandlerRepoStub) Store(_ context.Context, contacts []*entities.Contact) error {- s.stored = append(s.stored, contacts...)- return nil-}-func (s *contactHandlerRepoStub) Update(context.Context, *entities.Contact) error { return nil }-func (s *contactHandlerRepoStub) Load(context.Context, entities.UserID, uuid.UUID) (*entities.Contact, error) {- return nil, nil-}-func (s *contactHandlerRepoStub) Index(context.Context, entities.UserID, repositories.IndexParams) (*[]entities.Contact, error) {- out := []entities.Contact{}- return &out, nil-}-func (s *contactHandlerRepoStub) FetchAll(context.Context, entities.UserID) (*[]entities.Contact, error) {- out := []entities.Contact{}- return &out, nil-}-func (s *contactHandlerRepoStub) Delete(context.Context, entities.UserID, uuid.UUID) error { return nil }-func (s *contactHandlerRepoStub) DeleteAllForUser(context.Context, entities.UserID) error { return nil }--func newContactTestApp(repo repositories.ContactRepository) *fiber.App {- logger := &messageThreadHandlerNoopLogger{}- tracer := telemetry.NewOtelLogger("test", logger)- appCache := cache.NewMemoryCache(tracer, ttlCache.New(time.Minute, time.Minute))- service := services.NewContactService(logger, tracer, repo, appCache)- handler := NewContactHandler(logger, tracer, &validators.ContactHandlerValidator{}, service)-- app := fiber.New()- app.Use(func(c fiber.Ctx) error {- c.Locals(middlewares.ContextKeyAuthUserID, entities.AuthContext{ID: entities.UserID("user-id"), Email: "[email protected]"})- return c.Next()- })- handler.RegisterRoutes(app)- return app-}--func TestContactHandler_Store_CreatesContacts(t *testing.T) {- repo := &contactHandlerRepoStub{}- app := newContactTestApp(repo)-- body := `[{"name":"Alice","phone_numbers":["+18005550199"]}]`- req := httptest.NewRequest(http.MethodPost, "/v1/contacts", bytes.NewBufferString(body))- req.Header.Set("Content-Type", "application/json")-- resp, err := app.Test(req, fiber.TestConfig{Timeout: time.Second})- require.NoError(t, err)- require.Equal(t, http.StatusCreated, resp.StatusCode)- require.Len(t, repo.stored, 1)- require.Equal(t, "Alice", repo.stored[0].Name)-}--func TestContactHandler_Store_ValidationError(t *testing.T) {- app := newContactTestApp(&contactHandlerRepoStub{})-- body := `[{"name":"","phone_numbers":[]}]`- req := httptest.NewRequest(http.MethodPost, "/v1/contacts", bytes.NewBufferString(body))- req.Header.Set("Content-Type", "application/json")-- resp, err := app.Test(req, fiber.TestConfig{Timeout: time.Second})- require.NoError(t, err)- require.Equal(t, http.StatusUnprocessableEntity, resp.StatusCode)-}--func TestContactHandler_Index_ReturnsOK(t *testing.T) {- app := newContactTestApp(&contactHandlerRepoStub{})-- req := httptest.NewRequest(http.MethodGet, "/v1/contacts", nil)- resp, err := app.Test(req, fiber.TestConfig{Timeout: time.Second})- require.NoError(t, err)- require.Equal(t, http.StatusOK, resp.StatusCode)-}-```--- [ ] **Step 2: Run test to verify it fails**--Run: `cd api && go test -vet=off ./pkg/handlers/ -run TestContactHandler`-Expected: FAIL / build error — `NewContactHandler` undefined.--- [ ] **Step 3: Write the handler**--Create `api/pkg/handlers/contact_handler.go`:--```go-package handlers--import (- "fmt"-- "github.com/NdoleStudio/httpsms/pkg/repositories"- "github.com/NdoleStudio/httpsms/pkg/requests"- "github.com/NdoleStudio/httpsms/pkg/services"- "github.com/NdoleStudio/httpsms/pkg/telemetry"- "github.com/NdoleStudio/httpsms/pkg/validators"- "github.com/NdoleStudio/stacktrace"- "github.com/davecgh/go-spew/spew"- "github.com/gofiber/fiber/v3"- "github.com/google/uuid"-)--// ContactHandler handles contact http requests.-type ContactHandler struct {- handler- logger telemetry.Logger- tracer telemetry.Tracer- validator *validators.ContactHandlerValidator- service *services.ContactService-}--// NewContactHandler creates a new ContactHandler.-func NewContactHandler(- logger telemetry.Logger,- tracer telemetry.Tracer,- validator *validators.ContactHandlerValidator,- service *services.ContactService,-) (h *ContactHandler) {- return &ContactHandler{- logger: logger.WithService(fmt.Sprintf("%T", h)),- tracer: tracer,- validator: validator,- service: service,- }-}--// RegisterRoutes registers the routes for the ContactHandler.-func (h *ContactHandler) RegisterRoutes(router fiber.Router, middlewares ...fiber.Handler) {- h.register(router, fiber.MethodGet, "/v1/contacts", middlewares, h.Index)- h.register(router, fiber.MethodPost, "/v1/contacts", middlewares, h.Store)- h.register(router, fiber.MethodPost, "/v1/contacts/upload", middlewares, h.Upload)- h.register(router, fiber.MethodPut, "/v1/contacts/:contactID", middlewares, h.Update)- h.register(router, fiber.MethodDelete, "/v1/contacts/:contactID", middlewares, h.Delete)-}--// Index lists contacts for the authenticated user.-// @Summary List contacts-// @Description Returns the paginated list of contacts for the authenticated user.-// @Security ApiKeyAuth-// @Tags Contacts-// @Accept json-// @Produce json-// @Param skip query int false "number of contacts to skip" minimum(0)-// @Param query query string false "filter contacts containing query"-// @Param limit query int false "number of contacts to return" minimum(1) maximum(100)-// @Success 200 {object} responses.ContactsResponse-// @Failure 400 {object} responses.BadRequest-// @Failure 401 {object} responses.Unauthorized-// @Failure 422 {object} responses.UnprocessableEntity-// @Failure 500 {object} responses.InternalServerError-// @Router /contacts [get]-func (h *ContactHandler) Index(c fiber.Ctx) error {- ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)- defer span.End()-- var request requests.ContactIndex- if err := c.Bind().Query(&request); err != nil {- ctxLogger.Warn(stacktrace.Propagatef(err, "cannot marshall params [%s] into %T", c.OriginalURL(), request))- return h.responseBadRequest(c, err)- }-- sanitized := request.Sanitize()- if errors := h.validator.ValidateIndex(ctx, sanitized); len(errors) != 0 {- ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while listing contacts [%+#v]", spew.Sdump(errors), sanitized))- return h.responseUnprocessableEntity(c, errors, "validation errors while listing contacts")- }-- contacts, err := h.service.Index(ctx, h.userIDFomContext(c), sanitized.ToIndexParams())- if err != nil {- ctxLogger.Error(stacktrace.Propagatef(err, "cannot list contacts for user [%s]", h.userIDFomContext(c)))- return h.responseInternalServerError(c)- }-- return h.responseOK(c, fmt.Sprintf("fetched %d %s", len(*contacts), h.pluralize("contact", len(*contacts))), contacts)-}--// Store creates one or many contacts.-// @Summary Create one or many contacts-// @Description Creates a single contact or a batch of contacts. Accepts a JSON array or an object with a "contacts" array.-// @Security ApiKeyAuth-// @Tags Contacts-// @Accept json-// @Produce json-// @Param payload body requests.ContactStoreRequest true "Contact(s) to create"-// @Success 201 {object} responses.ContactsResponse-// @Failure 400 {object} responses.BadRequest-// @Failure 401 {object} responses.Unauthorized-// @Failure 422 {object} responses.UnprocessableEntity-// @Failure 500 {object} responses.InternalServerError-// @Router /contacts [post]-func (h *ContactHandler) Store(c fiber.Ctx) error {- ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)- defer span.End()-- var request requests.ContactStoreRequest- if err := c.Bind().Body(&request); err != nil {- ctxLogger.Warn(stacktrace.Propagatef(err, "cannot marshall body [%s] into %T", c.Body(), request))- return h.responseBadRequest(c, err)- }-- sanitized := request.Sanitize()- if errors := h.validator.ValidateStore(ctx, sanitized); len(errors) != 0 {- ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while creating contacts", spew.Sdump(errors)))- return h.responseUnprocessableEntity(c, errors, "validation errors while creating contacts")- }-- userID := h.userIDFomContext(c)- contacts := sanitized.ToContacts(userID)- if err := h.service.CreateMany(ctx, userID, contacts); err != nil {- ctxLogger.Error(stacktrace.Propagatef(err, "cannot create [%d] contacts for user [%s]", len(contacts), userID))- return h.responseInternalServerError(c)- }-- return h.responseCreated(c, fmt.Sprintf("created %d %s", len(contacts), h.pluralize("contact", len(contacts))), contacts)-}--// Upload imports contacts from a CSV file.-// @Summary Import contacts from CSV-// @Description Uploads a CSV file (multipart field "document") of contacts. Columns: Name, Emails, PhoneNumbers (multi-values separated by ";").-// @Security ApiKeyAuth-// @Tags Contacts-// @Accept multipart/form-data-// @Produce json-// @Param document formData file true "CSV file of contacts"-// @Success 201 {object} responses.ContactsResponse-// @Failure 400 {object} responses.BadRequest-// @Failure 401 {object} responses.Unauthorized-// @Failure 422 {object} responses.UnprocessableEntity-// @Failure 500 {object} responses.InternalServerError-// @Router /contacts/upload [post]-func (h *ContactHandler) Upload(c fiber.Ctx) error {- ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)- defer span.End()-- file, err := c.FormFile("document")- if err != nil {- ctxLogger.Warn(stacktrace.Propagatef(err, "cannot fetch file with name [%s] from request", "document"))- return h.responseBadRequest(c, err)- }-- userID := h.userIDFomContext(c)- items, errors := h.validator.ValidateUpload(ctx, userID, file)- if len(errors) != 0 {- ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while importing contacts from CSV [%s]", spew.Sdump(errors), file.Filename))- return h.responseUnprocessableEntity(c, errors, "validation errors while importing contacts")- }-- request := (requests.ContactStoreRequest{Contacts: items}).Sanitize()- contacts := request.ToContacts(userID)- if err = h.service.CreateMany(ctx, userID, contacts); err != nil {- ctxLogger.Error(stacktrace.Propagatef(err, "cannot import [%d] contacts for user [%s]", len(contacts), userID))- return h.responseInternalServerError(c)- }-- return h.responseCreated(c, fmt.Sprintf("imported %d %s", len(contacts), h.pluralize("contact", len(contacts))), contacts)-}--// Update updates a single contact.-// @Summary Update a contact-// @Description Updates the details of a single contact.-// @Security ApiKeyAuth-// @Tags Contacts-// @Accept json-// @Produce json-// @Param contactID path string true "ID of the contact"-// @Param payload body requests.ContactUpdateRequest true "Contact details to update"-// @Success 200 {object} responses.ContactResponse-// @Failure 400 {object} responses.BadRequest-// @Failure 401 {object} responses.Unauthorized-// @Failure 404 {object} responses.NotFound-// @Failure 422 {object} responses.UnprocessableEntity-// @Failure 500 {object} responses.InternalServerError-// @Router /contacts/{contactID} [put]-func (h *ContactHandler) Update(c fiber.Ctx) error {- ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)- defer span.End()-- contactID := c.Params("contactID")- if errors := h.validator.ValidateUUID(contactID, "contactID"); len(errors) != 0 {- ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while updating contact [%s]", spew.Sdump(errors), contactID))- return h.responseUnprocessableEntity(c, errors, "validation errors while updating contact")- }-- var request requests.ContactUpdateRequest- if err := c.Bind().Body(&request); err != nil {- ctxLogger.Warn(stacktrace.Propagatef(err, "cannot marshall body into %T", request))- return h.responseBadRequest(c, err)- }-- sanitized := request.Sanitize()- if errors := h.validator.ValidateUpdate(ctx, sanitized); len(errors) != 0 {- ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while updating contact [%s]", spew.Sdump(errors), contactID))- return h.responseUnprocessableEntity(c, errors, "validation errors while updating contact")- }-- userID := h.userIDFomContext(c)- contact, err := h.service.Get(ctx, userID, uuid.MustParse(contactID))- if stacktrace.GetCode(err) == repositories.ErrCodeNotFound {- return h.responseNotFound(c, fmt.Sprintf("cannot find contact with ID [%s]", contactID))- }- if err != nil {- ctxLogger.Error(stacktrace.Propagatef(err, "cannot load contact [%s] for user [%s]", contactID, userID))- return h.responseInternalServerError(c)- }-- sanitized.ApplyTo(contact)- if err = h.service.Update(ctx, contact); err != nil {- ctxLogger.Error(stacktrace.Propagatef(err, "cannot update contact [%s]", contactID))- return h.responseInternalServerError(c)- }-- return h.responseOK(c, "contact updated successfully", contact)-}--// Delete removes a single contact.-// @Summary Delete a contact-// @Description Deletes a single contact from the database.-// @Security ApiKeyAuth-// @Tags Contacts-// @Accept json-// @Produce json-// @Param contactID path string true "ID of the contact"-// @Success 204 {object} responses.NoContent-// @Failure 400 {object} responses.BadRequest-// @Failure 401 {object} responses.Unauthorized-// @Failure 404 {object} responses.NotFound-// @Failure 422 {object} responses.UnprocessableEntity-// @Failure 500 {object} responses.InternalServerError-// @Router /contacts/{contactID} [delete]-func (h *ContactHandler) Delete(c fiber.Ctx) error {- ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)- defer span.End()-- contactID := c.Params("contactID")- if errors := h.validator.ValidateUUID(contactID, "contactID"); len(errors) != 0 {- ctxLogger.Warn(stacktrace.NewErrorf("validation errors [%s], while deleting contact [%s]", spew.Sdump(errors), contactID))- return h.responseUnprocessableEntity(c, errors, "validation errors while deleting contact")- }-- userID := h.userIDFomContext(c)- if err := h.service.Delete(ctx, userID, uuid.MustParse(contactID)); err != nil {- ctxLogger.Error(stacktrace.Propagatef(err, "cannot delete contact [%s] for user [%s]", contactID, userID))- return h.responseInternalServerError(c)- }-- return h.responseNoContent(c, "contact deleted successfully")-}-```--- [ ] **Step 4: Add DI getters and wiring**--In `api/pkg/di/container.go`:--Add a repository getter (near `MessageThreadRepository`):--```go-// ContactRepository creates a new instance of repositories.ContactRepository-func (container *Container) ContactRepository() (repository repositories.ContactRepository) {- container.logger.Debug("creating GORM repositories.ContactRepository")- return repositories.NewGormContactRepository(- container.Logger(),- container.Tracer(),- container.DB(),- )-}-```--Add a service getter (near `MessageThreadService`):--```go-// ContactService creates a new instance of services.ContactService-func (container *Container) ContactService() (service *services.ContactService) {- container.logger.Debug(fmt.Sprintf("creating %T", service))- return services.NewContactService(- container.Logger(),- container.Tracer(),- container.ContactRepository(),- container.Cache(),- )-}-```--Add a validator getter (near `MessageThreadHandlerValidator`):--```go-// ContactHandlerValidator creates a new instance of validators.ContactHandlerValidator-func (container *Container) ContactHandlerValidator() (validator *validators.ContactHandlerValidator) {- container.logger.Debug(fmt.Sprintf("creating %T", validator))- return validators.NewContactHandlerValidator(- container.Logger(),- container.Tracer(),- )-}-```--Add a handler getter (near `MessageThreadHandler`):--```go-// ContactHandler creates a new instance of handlers.ContactHandler-func (container *Container) ContactHandler() (h *handlers.ContactHandler) {- container.logger.Debug(fmt.Sprintf("creating %T", h))- return handlers.NewContactHandler(- container.Logger(),- container.Tracer(),- container.ContactHandlerValidator(),- container.ContactService(),- )-}-```--Add a route registrar (near `RegisterMessageThreadRoutes`):--```go-// RegisterContactRoutes registers routes for the /contacts prefix-func (container *Container) RegisterContactRoutes() {- container.logger.Debug(fmt.Sprintf("registering %T routes", &handlers.ContactHandler{}))- container.ContactHandler().RegisterRoutes(container.App(), container.AuthenticatedMiddleware())-}-```--Call the registrar right after `container.RegisterMessageThreadRoutes()` (around line 123):--```go- container.RegisterMessageThreadRoutes()- container.RegisterContactRoutes()-```--Wire the ContactService into MessageThreadService (finalise Task 7 Step 5): the `MessageThreadService()` getter's `NewMessageThreadService(...)` call's final argument becomes `container.ContactService()`:--```go- return services.NewMessageThreadService(- container.Logger(),- container.Tracer(),- container.MessageThreadRepository(),- container.PhoneRepository(),- container.EventDispatcher(),- container.ContactService(),- )-```--Add the AutoMigrate entry in the AutoMigrate block (around line 413, alongside the other `db.AutoMigrate(&entities.X{})` calls) — this may already be present from Task 2; if not, add:--```go- if err = db.AutoMigrate(&entities.Contact{}); err != nil {- container.logger.Fatal(stacktrace.Propagatef(err, "cannot migrate %T", &entities.Contact{}))- }-```--- [ ] **Step 5: Run test to verify it passes**--Run: `cd api && go test -vet=off ./pkg/handlers/ -run TestContactHandler`-Expected: PASS--- [ ] **Step 6: Build the whole API to confirm wiring compiles**--Run: `cd api && go build ./...`-Expected: no output (success).--- [ ] **Step 7: Commit**--```bash-git add api/pkg/handlers/contact_handler.go api/pkg/handlers/contact_handler_test.go api/pkg/di/container.go-git commit -m "feat(api): add ContactHandler and wire contacts into DI container"-```-------### Task 9: Swagger regeneration + CSV import template--**Files:**-- Modify: `api/docs/*` (generated by swag)-- Create: `web/public/templates/httpsms-contacts.csv`-- Create/verify: `api/pkg/responses/` contact response types if referenced by Swagger annotations (see Step 1).--**Interfaces:**-- Consumes: Swagger annotations added on `ContactHandler` (Task 8), which reference `responses.ContactResponse` and `responses.ContactsResponse`.-- Produces: regenerated `api/docs/swagger.json` / `swagger.yaml` / `docs.go` including the `/contacts` endpoints; a downloadable CSV template served by the web app.--- [ ] **Step 1: Add response wrapper types (if missing)**--Check whether `responses.ContactResponse` and `responses.ContactsResponse` exist:--Run: `cd api && findstr /S /C:"ContactsResponse" pkg\responses\*.go`-Expected: no matches (they don't exist yet).--Create `api/pkg/responses/contact_responses.go`:--```go-package responses--import "github.com/NdoleStudio/httpsms/pkg/entities"--// ContactResponse is the response with a single entities.Contact.-type ContactResponse struct {- response- Data entities.Contact `json:"data"`-}--// ContactsResponse is the response with a list of entities.Contact.-type ContactsResponse struct {- response- Data []entities.Contact `json:"data"`-}-```--(Verify the base embedded type name: open any file in `api/pkg/responses/` and confirm the unexported base struct is `response` with `Status`/`Message` fields; match the exact embed used by e.g. `MessageThreadsResponse`.)--- [ ] **Step 2: Regenerate Swagger docs**--Run:--```bash-cd api && swag init --requiredByDefault --parseDependency --parseInternal-```--Expected: `create docs/docs.go`, `create docs/swagger.json`, `create docs/swagger.yaml` with no errors. Confirm `/contacts` appears:--Run: `cd api && findstr /C:"/contacts" docs\swagger.json`-Expected: matches for `/contacts`, `/contacts/upload`, `/contacts/{contactID}`.--- [ ] **Step 3: Create the CSV import template**--Create `web/public/templates/httpsms-contacts.csv`:--```csv-Name,Emails,PhoneNumbers-John Doe,[email protected],+18005550199-Jane Smith,[email protected];[email protected],+18005550100;+18005550111-Acme Support,,+18005550122-```--(Multiple emails or phone numbers in one cell are separated by `;`, matching the CSV parser in Task 5's `ValidateUpload`.)--- [ ] **Step 4: Commit**--```bash-git add api/docs api/pkg/responses/contact_responses.go web/public/templates/httpsms-contacts.csv-git commit -m "chore(api): regenerate swagger for contacts + add CSV import template"-```-------### Task 10: Regenerate web API TypeScript models--**Files:**-- Modify: `web/shared/types/api.ts` (generated)--**Interfaces:**-- Consumes: `api/docs/swagger.json` (regenerated in Task 9) with the `Contact` schema and `/contacts` paths.-- Produces: generated types `EntitiesContact` and (if the response wrappers were added) `ResponsesContactResponse` / `ResponsesContactsResponse` in `web/shared/types/api.ts`; `EntitiesMessageThread` now includes an optional `contact_details?: EntitiesContact`.--> **Note:** This task must run AFTER Task 9 (swagger regen). No new hand-written code — the model file is generated.--- [ ] **Step 1: Regenerate models**--Run:--```bash-cd web && pnpm api:models-```--Expected: `web/shared/types/api.ts` rewritten with no errors.--- [ ] **Step 2: Verify the Contact type exists**--Run: `cd web && findstr /C:"EntitiesContact" shared\types\api.ts`-Expected: matches for `EntitiesContact` interface and `contact_details` on the message-thread interface.--- [ ] **Step 3: Commit**--```bash-git add web/shared/types/api.ts-git commit -m "chore(web): regenerate API models with Contact types"-```-------### Task 11: Contacts Pinia store--**Files:**-- Create: `web/app/stores/contacts.ts`--**Interfaces:**-- Consumes: `useApi()` (`apiFetch`), `useNotificationsStore()`, `getApiErrorMessage`, `EntitiesContact` (Task 10).-- Produces: `useContactsStore()` exposing state `contacts`, `loading`, `search`; getters `filteredContacts`, `total`; actions `loadContacts(force?)`, `saveContacts(items)`, `updateContact(id, payload)`, `deleteContact(id)`, `uploadCsv(file)`, `resetState()`.--- [ ] **Step 1: Write the store**--Create `web/app/stores/contacts.ts`:--```ts-import { defineStore } from 'pinia'-import { ref, computed } from 'vue'-import type { EntitiesContact } from '~~/shared/types/api'-import { getApiErrorMessage } from '~/utils/api-error'--export interface ContactInput {- name: string- emails: string[]- phone_numbers: string[]- properties?: Record<string, string>-}--export const useContactsStore = defineStore('contacts', () => {- const contacts = ref<EntitiesContact[]>([])- const loading = ref(false)- const search = ref('')- const { apiFetch } = useApi()- const notificationsStore = useNotificationsStore()-- const total = computed(() => contacts.value.length)-- const filteredContacts = computed<EntitiesContact[]>(() => {- const term = search.value.trim().toLowerCase()- if (!term) return contacts.value- return contacts.value.filter((contact) => {- const name = (contact.name ?? '').toLowerCase()- const emails = (contact.emails ?? []).join(' ').toLowerCase()- const numbers = (contact.phone_numbers ?? []).join(' ').toLowerCase()- return (- name.includes(term) ||- emails.includes(term) ||- numbers.includes(term)- )- })- })-- async function loadContacts(force = false) {- if (contacts.value.length > 0 && !force) return- loading.value = true- try {- const response = await apiFetch<{ data: EntitiesContact[] }>(- '/v1/contacts',- { params: { limit: 100 } },- )- contacts.value = response.data ?? []- } catch (error: unknown) {- notificationsStore.addNotification({- message: getApiErrorMessage(error, 'Error while loading contacts'),- type: 'error',- })- throw error- } finally {- loading.value = false- }- }-- async function saveContacts(items: ContactInput[]) {- try {- await apiFetch('/v1/contacts', { method: 'POST', body: items })- notificationsStore.addNotification({- message:- items.length > 1 ? 'Contacts created' : 'Contact created',- type: 'success',- })- await loadContacts(true)- } catch (error: unknown) {- notificationsStore.addNotification({- message: getApiErrorMessage(error, 'Error while saving contacts'),- type: 'error',- })- throw error- }- }-- async function updateContact(id: string, payload: ContactInput) {- try {- await apiFetch(`/v1/contacts/${id}`, { method: 'PUT', body: payload })- notificationsStore.addNotification({- message: 'Contact updated',- type: 'success',- })- await loadContacts(true)- } catch (error: unknown) {- notificationsStore.addNotification({- message: getApiErrorMessage(error, 'Error while updating contact'),- type: 'error',- })- throw error- }- }-- async function deleteContact(id: string) {- try {- await apiFetch(`/v1/contacts/${id}`, { method: 'DELETE' })- contacts.value = contacts.value.filter((contact) => contact.id !== id)- notificationsStore.addNotification({- message: 'Contact deleted',- type: 'success',- })- } catch (error: unknown) {- notificationsStore.addNotification({- message: getApiErrorMessage(error, 'Error while deleting contact'),- type: 'error',- })- throw error- }- }-- async function uploadCsv(file: File) {- try {- const formData = new FormData()- formData.append('document', file)- await apiFetch('/v1/contacts/upload', {- method: 'POST',- body: formData,- })- notificationsStore.addNotification({- message: 'Contacts imported successfully',- type: 'success',- })- await loadContacts(true)- } catch (error: unknown) {- notificationsStore.addNotification({- message: getApiErrorMessage(error, 'Error while importing contacts'),- type: 'error',- })- throw error- }- }-- function resetState() {- contacts.value = []- loading.value = false- search.value = ''- }-- return {- contacts,- loading,- search,- total,- filteredContacts,- loadContacts,- saveContacts,- updateContact,- deleteContact,- uploadCsv,- resetState,- }-})-```--- [ ] **Step 2: Lint the new store**--Run: `cd web && pnpm lint:js`-Expected: no errors for `app/stores/contacts.ts`.--- [ ] **Step 3: Commit**--```bash-git add web/app/stores/contacts.ts-git commit -m "feat(web): add contacts Pinia store"-```-------### Task 12: Contacts page with add/edit/delete/import dialogs--**Files:**-- Create: `web/app/pages/contacts/index.vue`--**Interfaces:**-- Consumes: `useContactsStore()` (Task 11), `useFilters()` (`formatPhoneNumber`), `EntitiesContact` (Task 10).-- Produces: the `/contacts` route (Nuxt file-based routing infers `name: 'contacts'`, used by the nav link in Task 13).--**UI requirements (from spec section 7 / reference screenshot):**-- Page title `text-display-large` (NO gradient/glow — theme text only); subtitle showing total contact count.-- Top-right actions: "Import CSV" (outlined button) + "Add Contact" (filled `color="primary"` button).-- Debounced search field filtering by name/email/phone.-- Table of contacts (Name, Emails, Phone Numbers) with edit + delete icon actions per row.-- Add/Edit/Delete/Import are `VDialog`s. **Every `VDialog` MUST set `opacity="0.9"` and its Close button MUST use `color="warning"`.**--- [ ] **Step 1: Write the page**--Create `web/app/pages/contacts/index.vue`:--```vue-<script setup lang="ts">-import {- mdiArrowLeft,- mdiPlus,- mdiFileUpload,- mdiPencil,- mdiDelete,- mdiMagnify,- mdiClose,-} from '@mdi/js'-import { ref, computed, onMounted } from 'vue'-import type { EntitiesContact } from '~~/shared/types/api'-import { useContactsStore, type ContactInput } from '~/stores/contacts'-import { useFilters } from '~/composables/useFilters'--definePageMeta({- middleware: ['auth'],-})--useHead({- title: 'Contacts - httpSMS',-})--const contactsStore = useContactsStore()-const { formatPhoneNumber } = useFilters()--const editDialog = ref(false)-const deleteDialog = ref(false)-const importDialog = ref(false)-const saving = ref(false)-const editingId = ref<string | null>(null)-const pendingDeleteId = ref<string | null>(null)-const importFile = ref<File | null>(null)--const form = ref<{ name: string; emails: string; phone_numbers: string }>({- name: '',- emails: '',- phone_numbers: '',-})--const dialogTitle = computed(() =>- editingId.value ? 'Edit Contact' : 'Add Contact',-)--function splitList(value: string): string[] {- return value- .split(/[,;]/)- .map((item) => item.trim())- .filter((item) => item.length > 0)-}--function openAdd() {- editingId.value = null- form.value = { name: '', emails: '', phone_numbers: '' }- editDialog.value = true-}--function openEdit(contact: EntitiesContact) {- editingId.value = contact.id ?? null- form.value = {- name: contact.name ?? '',- emails: (contact.emails ?? []).join(', '),- phone_numbers: (contact.phone_numbers ?? []).join(', '),- }- editDialog.value = true-}--function openDelete(contact: EntitiesContact) {- pendingDeleteId.value = contact.id ?? null- deleteDialog.value = true-}--async function submitForm() {- saving.value = true- const payload: ContactInput = {- name: form.value.name.trim(),- emails: splitList(form.value.emails),- phone_numbers: splitList(form.value.phone_numbers),- }- try {- if (editingId.value) {- await contactsStore.updateContact(editingId.value, payload)- } else {- await contactsStore.saveContacts([payload])- }- editDialog.value = false- } catch {- // notification already surfaced by the store- } finally {- saving.value = false- }-}--async function confirmDelete() {- if (!pendingDeleteId.value) return- saving.value = true- try {- await contactsStore.deleteContact(pendingDeleteId.value)- deleteDialog.value = false- } catch {- // notification already surfaced by the store- } finally {- saving.value = false- pendingDeleteId.value = null- }-}--async function submitImport() {- if (!importFile.value) return- saving.value = true- try {- await contactsStore.uploadCsv(importFile.value)- importDialog.value = false- importFile.value = null- } catch {- // notification already surfaced by the store- } finally {- saving.value = false- }-}--onMounted(() => {- contactsStore.loadContacts(true).catch(() => {})-})-</script>--<template>- <VContainer fluid class="px-0 pt-0">- <VAppBar>- <VBtn icon to="/threads">- <VIcon :icon="mdiArrowLeft" />- </VBtn>- <VToolbarTitle>Contacts</VToolbarTitle>- <VProgressLinear- :active="contactsStore.loading"- color="primary"- :indeterminate="contactsStore.loading"- location="bottom"- absolute- />- </VAppBar>-- <VContainer>- <VRow>- <VCol cols="12" md="10" offset-md="1" xxl="8" offset-xxl="2">- <div- class="d-flex flex-column flex-md-row align-md-center mb-6 mt-3"- >- <div>- <h1 class="text-display-large">Contacts</h1>- <p class="text-medium-emphasis mb-0">- {{ contactsStore.total }}- {{ contactsStore.total === 1 ? 'contact' : 'contacts' }}- </p>- </div>- <VSpacer />- <div class="d-flex mt-4 mt-md-0">- <VBtn- variant="outlined"- color="primary"- :prepend-icon="mdiFileUpload"- class="mr-3"- @click="importDialog = true"- >- Import CSV- </VBtn>- <VBtn- color="primary"- :prepend-icon="mdiPlus"- @click="openAdd"- >- Add Contact- </VBtn>- </div>- </div>-- <VTextField- v-model="contactsStore.search"- :prepend-inner-icon="mdiMagnify"- label="Search contacts"- variant="outlined"- density="comfortable"- clearable- hide-details- class="mb-4"- />-- <VTable density="comfortable">- <thead>- <tr class="text-uppercase text-medium-emphasis">- <th class="text-left">Name</th>- <th class="text-left">Emails</th>- <th class="text-left">Phone Numbers</th>- <th class="text-right">Actions</th>- </tr>- </thead>- <tbody>- <tr- v-for="contact in contactsStore.filteredContacts"- :key="contact.id"- >- <td class="text-left">{{ contact.name }}</td>- <td class="text-left">- {{ (contact.emails ?? []).join(', ') }}- </td>- <td class="text-left">- {{- (contact.phone_numbers ?? [])- .map((number) => formatPhoneNumber(number))- .join(', ')- }}- </td>- <td class="text-right">- <VBtn- icon- variant="text"- size="small"- @click="openEdit(contact)"- >- <VIcon :icon="mdiPencil" />- </VBtn>- <VBtn- icon- variant="text"- size="small"- color="error"- @click="openDelete(contact)"- >- <VIcon :icon="mdiDelete" />- </VBtn>- </td>- </tr>- <tr v-if="contactsStore.filteredContacts.length === 0">- <td colspan="4" class="text-center text-medium-emphasis py-8">- No contacts found.- </td>- </tr>- </tbody>- </VTable>- </VCol>- </VRow>- </VContainer>-- <!-- Add / Edit dialog -->- <VDialog v-model="editDialog" max-width="560" opacity="0.9">- <VCard>- <VCardTitle class="d-flex align-center">- <span>{{ dialogTitle }}</span>- <VSpacer />- <VBtn- icon- variant="text"- color="warning"- @click="editDialog = false"- >- <VIcon :icon="mdiClose" />- </VBtn>- </VCardTitle>- <VCardText>- <VTextField- v-model="form.name"- label="Name"- variant="outlined"- class="mb-2"- />- <VTextField- v-model="form.emails"- label="Emails (comma separated)"- variant="outlined"- class="mb-2"- />- <VTextField- v-model="form.phone_numbers"- label="Phone numbers (comma separated)"- variant="outlined"- />- </VCardText>- <VCardActions>- <VSpacer />- <VBtn color="warning" variant="text" @click="editDialog = false">- Close- </VBtn>- <VBtn- color="primary"- :loading="saving"- :disabled="saving"- @click="submitForm"- >- Save- </VBtn>- </VCardActions>- </VCard>- </VDialog>-- <!-- Delete dialog -->- <VDialog v-model="deleteDialog" max-width="460" opacity="0.9">- <VCard>- <VCardTitle class="d-flex align-center">- <span>Delete Contact</span>- <VSpacer />- <VBtn- icon- variant="text"- color="warning"- @click="deleteDialog = false"- >- <VIcon :icon="mdiClose" />- </VBtn>- </VCardTitle>- <VCardText>- Are you sure you want to delete this contact? This action cannot be- undone.- </VCardText>- <VCardActions>- <VSpacer />- <VBtn color="warning" variant="text" @click="deleteDialog = false">- Close- </VBtn>- <VBtn- color="error"- :loading="saving"- :disabled="saving"- @click="confirmDelete"- >- Delete- </VBtn>- </VCardActions>- </VCard>- </VDialog>-- <!-- Import CSV dialog -->- <VDialog v-model="importDialog" max-width="560" opacity="0.9">- <VCard>- <VCardTitle class="d-flex align-center">- <span>Import Contacts from CSV</span>- <VSpacer />- <VBtn- icon- variant="text"- color="warning"- @click="importDialog = false"- >- <VIcon :icon="mdiClose" />- </VBtn>- </VCardTitle>- <VCardText>- <p class="mb-3">- Download our- <a- class="text-decoration-none hover:text-decoration-underline"- download- href="/templates/httpsms-contacts.csv"- >CSV template</a- >, fill it in and upload it here. Columns: Name, Emails,- PhoneNumbers (multiple values separated by ";").- </p>- <VFileInput- v-model="importFile"- label="CSV file"- color="primary"- accept=".csv,text/csv"- variant="outlined"- hide-details- />- </VCardText>- <VCardActions>- <VSpacer />- <VBtn color="warning" variant="text" @click="importDialog = false">- Close- </VBtn>- <VBtn- color="primary"- :loading="saving"- :disabled="saving || !importFile"- @click="submitImport"- >- Import- </VBtn>- </VCardActions>- </VCard>- </VDialog>- </VContainer>-</template>-```--- [ ] **Step 2: Lint the page**--Run: `cd web && pnpm lint:js && pnpm lint:prettier`-Expected: no errors for `app/pages/contacts/index.vue`. If Prettier reports formatting, run `pnpm lintfix` and re-check.--- [ ] **Step 3: Build the site to confirm it compiles**--Run: `cd web && pnpm generate`-Expected: build completes without type errors (the `/contacts` route is emitted).--- [ ] **Step 4: Commit**--```bash-git add web/app/pages/contacts/index.vue-git commit -m "feat(web): add contacts page with add/edit/delete/import dialogs"-```-------### Task 13: Show contact names on threads + Contacts nav link--**Files:**-- Modify: `web/app/stores/threads.ts` (send `contacts: true`)-- Modify: `web/app/components/MessageThread.vue` (list title + avatar initial)-- Modify: `web/app/pages/threads/[id]/index.vue` (toolbar title)-- Modify: `web/app/components/MessageThreadHeader.vue` (Contacts nav item + icon import)--**Interfaces:**-- Consumes: `EntitiesMessageThread.contact_details?: EntitiesContact` (Task 10), the `/contacts` route (Task 12).-- Produces: no new exports — UI wiring only.--- [ ] **Step 1: Request contact resolution when loading threads**--In `web/app/stores/threads.ts`, add `contacts: true` to the `loadThreads` request params:--```ts- const response = await apiFetch<{ data: EntitiesMessageThread[] }>(- '/v1/message-threads',- {- params: {- owner: phonesStore.owner ?? phonesStore.phones[0]?.phone_number,- limit: 100,- is_archived: archivedThreads.value,- contacts: true,- },- },- )-```--- [ ] **Step 2: Show the contact name in the threads list**--In `web/app/components/MessageThread.vue`, replace the list-item title expression:--```vue- <v-list-item-title :class="{ 'font-weight-bold': !thread.is_read }">{{- thread.contact_details?.name ?? formatPhoneNumber(thread.contact)- }}</v-list-item-title>-```--And update the avatar initial to prefer the contact name (replace the existing `<template #prepend>` avatar content):--```vue- <template #prepend>- <v-avatar- :color="thread.color"- size="40"- :badge="thread.is_read ? false : { color: 'primary', dotSize: 12 }"- >- <v-icon- v-if="!(thread.contact_details?.name || startsWithLetter(thread.contact))"- color="white"- >{{ mdiAccount }}</v-icon- >- <span v-else class="text-white text-headline-small">{{- (thread.contact_details?.name ?? thread.contact).substring(0, 1)- }}</span>- </v-avatar>- </template>-```--- [ ] **Step 3: Show the contact name in the thread header**--In `web/app/pages/threads/[id]/index.vue`, replace the toolbar title expression (around line 271):--```vue- <VToolbarTitle v-if="threadsStore.currentThread">- {{- threadsStore.currentThread.contact_details?.name ??- formatPhoneNumber(threadsStore.currentThread.contact)- }}- </VToolbarTitle>-```--- [ ] **Step 4: Add the Contacts navigation item**--In `web/app/components/MessageThreadHeader.vue`, add `mdiAccountMultiple` to the `@mdi/js` import block:--```ts- mdiCommentTextMultipleOutline,- mdiAccountMultiple,- mdiCircle,-```--Add a nav item right after the "Search Messages" `v-list-item` (before the Settings item):--```vue- <v-list-item :to="{ name: 'contacts' }">- <template #prepend><v-icon :icon="mdiAccountMultiple" /></template>- <v-list-item-title>Contacts</v-list-item-title>- </v-list-item>-```--- [ ] **Step 5: Lint and build**--Run: `cd web && pnpm lint:js && pnpm generate`-Expected: no errors; the build succeeds.--- [ ] **Step 6: Commit**--```bash-git add web/app/stores/threads.ts web/app/components/MessageThread.vue web/app/pages/threads/[id]/index.vue web/app/components/MessageThreadHeader.vue-git commit -m "feat(web): display contact names on threads and add Contacts nav link"-```-------## Final Verification--- [ ] **API full test + build**--```bash-cd api && go test -vet=off ./... && go build ./...-```-Expected: all packages pass; build succeeds.--- [ ] **Web lint + build**--```bash-cd web && pnpm lint && pnpm generate-```-Expected: lint clean; static build succeeds.--- [ ] **Manual smoke test (optional, with Docker stack)**--```bash-docker compose up --build-```-Then: create a contact via `POST /v1/contacts`, load `/threads` and confirm the contact name shows for a matching phone number; open `/contacts` and exercise add/edit/delete/import.diff --git a/docs/superpowers/plans/2026-07-23-signup-name.md b/docs/superpowers/plans/2026-07-23-signup-name.mddeleted file mode 100644index 1bebf08a..00000000--- a/docs/superpowers/plans/2026-07-23-signup-name.md+++ /dev/null@@ -1,167 +0,0 @@-# Signup Name Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Require a name during Firebase email/password signup, persist it to the Firebase profile, and clear stale form errors when switching authentication modes.--**Architecture:** Keep the change inside the existing `FirebaseAuth.vue` component. The component will conditionally render and validate the name, call Firebase `updateProfile` immediately after account creation, and use a dedicated mode-toggle handler to clear errors.--**Tech Stack:** Nuxt 4, Vue 3 Composition API, Vuetify 4, TypeScript, Firebase Authentication--## Global Constraints--- The visible field label must be `Name`.-- The name is required only for email/password signup.-- Persist the trimmed name as Firebase `displayName`.-- Do not add a new test framework; this web project currently has no configured tests.-------### Task 1: Add signup name collection and profile persistence--**Files:**-- Modify: `web/app/components/FirebaseAuth.vue`--**Interfaces:**-- Consumes: Firebase `createUserWithEmailAndPassword(auth, email, password)` and `updateProfile(user, { displayName })`-- Produces: `toggleAuthMode(): void`, required signup `name` state, and Firebase users with a populated `displayName`--- [ ] **Step 1: Confirm the current web test command**--Run:--```bash-cd web-pnpm test-```--Expected: PASS with `No tests configured yet`. Do not introduce a test framework for this focused change.--- [ ] **Step 2: Add Firebase profile support and name state**--In `web/app/components/FirebaseAuth.vue`, add `updateProfile` to the existing-`firebase/auth` import:--```ts-import {- getAuth,- signInWithPopup,- GoogleAuthProvider,- GithubAuthProvider,- signInWithEmailAndPassword,- createUserWithEmailAndPassword,- sendPasswordResetEmail,- updateProfile,-} from 'firebase/auth'-```--Add the name state beside the existing email and password state:--```ts-const name = ref('')-const email = ref('')-const password = ref('')-```--- [ ] **Step 3: Require the name during signup validation**--At the start of `validateLoginForm`, after `let valid = true`, add:--```ts-if (isSignUp.value && !name.value.trim()) {- errorMessages.value.add('name', 'Please provide your name')- valid = false-}-```--This preserves sign-in validation while requiring a non-whitespace name only-in signup mode.--- [ ] **Step 4: Persist the name after Firebase account creation**--Replace the signup branch in `submitEmail` with:--```ts-if (isSignUp.value) {- result = await createUserWithEmailAndPassword(- auth,- email.value.trim(),- password.value,- )- await updateProfile(result.user, {- displayName: name.value.trim(),- })-} else {- result = await signInWithEmailAndPassword(- auth,- email.value.trim(),- password.value,- )-}-```--Keep the existing `onSuccess(result.user, 'email')` call after the branch so-the auth store receives the updated Firebase user before redirecting.--- [ ] **Step 5: Clear errors when switching sign-in and signup modes**--Add this function beside the existing form navigation helpers:--```ts-function toggleAuthMode() {- clearErrors()- isSignUp.value = !isSignUp.value-}-```--Change the mode-toggle button handler from:--```vue-@click="isSignUp = !isSignUp"-```--to:--```vue-@click="toggleAuthMode"-```--- [ ] **Step 6: Render the signup-only Name field**--Before the email field in the sign-in/sign-up form, add:--```vue-<v-text-field- v-if="isSignUp"- v-model="name"- label="Name"- color="primary"- type="text"- variant="outlined"- density="comfortable"- class="mb-2"- :error="errorMessages.has('name')"- :error-messages="errorMessages.get('name')"-/>-```--- [ ] **Step 7: Run focused web validation**--Run:--```bash-cd web-pnpm exec eslint app/components/FirebaseAuth.vue-pnpm exec prettier --check app/components/FirebaseAuth.vue-pnpm exec stylelint app/components/FirebaseAuth.vue-```--Expected: all three commands exit successfully with no lint, formatting, or-style errors.--- [ ] **Step 8: Commit the implementation**--```bash-git add web/app/components/FirebaseAuth.vue-git commit -m "feat(web): collect name during signup"-```diff --git a/docs/superpowers/plans/2026-09-02-url-backed-phone-notification-adapter.md b/docs/superpowers/plans/2026-09-02-url-backed-phone-notification-adapter.mddeleted file mode 100644index 6b81ee35..00000000--- a/docs/superpowers/plans/2026-09-02-url-backed-phone-notification-adapter.md+++ /dev/null@@ -1,1863 +0,0 @@-# URL-backed Phone Notification Adapter Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Allow a phone whose existing `fcm_token` is an HTTPS URL to receive message and heartbeat wake-ups over HTTP while preserving the current scheduling, backpressure, outstanding-message, and status-event flows.--**Architecture:** Add transport helpers to `entities.Phone`, inject a map of existing `FCMClient` implementations keyed by transport, and let `PhoneNotificationService` select the client through map lookup. The HTTP path uses a standard OpenTelemetry-wrapped `http.Client`, application retries with `github.com/avast/retry-go/v5`, FCM-compatible JSON, and the existing notification success/failure state transitions.--**Tech Stack:** Go 1.25.8, Fiber v3, Firebase Admin Messaging, OpenTelemetry, `net/http`, `retry-go/v5`, Testify, Docker Compose.--**Spec:** `docs/superpowers/specs/2026-09-02-url-backed-phone-notification-adapter-design.md`--## Final Accepted Architecture--This section supersedes later historical task text and code samples that-introduce an endpoint policy, DNS/IP filtering, custom dialing, or a-private-host allowlist.--- `Phone.NotificationTransport` performs only URL syntax, HTTPS scheme, and- hostname classification; URL user information remains valid.-- `Container.NotificationHTTPClient` uses the existing- `go-otelroundtripper` pattern with the `phone_notification_http` name and- the default transport, matching the webhook client style without custom URL- redaction.-- `HTTPNotificationSender` creates one reusable `*retry.Retrier` during- initialization. It owns exactly three application attempts with exponential- backoff, a fresh request/body, and a five-second child context per attempt;- caller contexts are enforced per operation rather than stored on the- reusable retrier.-- Payload encoding, request creation, one-attempt delivery, and retry- configuration are separate focused methods. OpenTelemetry HTTP telemetry is- owned by the injected round-tripper, with no sender-specific attempt metrics- or spans.-- No endpoint DNS/IP/SSRF policy, custom notification transport, or private-host- allowlist is part of the final implementation.-- `PhoneNotificationService` receives- `map[entities.NotificationTransport]FCMClient`, determines transport once,- selects the client by map lookup, sets the trimmed destination in- `message.Token`, and passes the same pointer to `FCMClient.Send`. There is no- extra sender interface, Firebase wrapper, or dispatcher class.-- `HTTPNotificationSender` implements `FCMClient` exactly and returns- `http/success` after a successful callback response.-- Domain events continue to use the existing `EventDispatcher` directly.--## Global Constraints--- Reuse the existing `Phone.FcmToken` database field and `fcm_token` API field; add no transport or endpoint columns.-- A valid `https://` URL with a hostname selects HTTP; an opaque non-URL token selects Firebase.-- URL-like malformed or unsupported tokens are invalid and must never fall through to Firebase.-- Send both outstanding-message and heartbeat notifications through the selected transport.-- HTTP callback requests are unsigned and contain no message content, user API key, phone API key, or other credentials.-- HTTPS callback URLs may include standard URL user information.-- Accept any HTTP `2xx`; ignore response content.-- Make at most three HTTP attempts with a five-second timeout per attempt.-- Retry network failures, `408`, `429`, and `5xx`; do not retry other non-`2xx` responses.-- Use the standard OpenTelemetry-wrapped HTTP transport without destination- DNS/IP filtering, custom dialing, or a private-host allowlist.-- Preserve existing schedules, per-minute backpressure, message expiration, send-attempt counting, outstanding-message fetching, and message event routes.-- Use `stacktrace.Propagate` or `stacktrace.Propagatef` for returned errors.-- Use GORM query builders with context propagation; this feature requires no database query changes or migration.-- Format Go code with `go-fumpt` through the repository's existing tooling.-------## File Structure--### Create--- `api/pkg/entities/phone_test.go` - table-driven transport classification tests.-- `api/pkg/services/notification_endpoint_policy.go` - public HTTPS URL validation, reserved-IP rejection, and validated dialing.-- `api/pkg/services/notification_endpoint_policy_test.go` - deterministic resolver/dialer tests, including DNS rebinding protection.-- `api/pkg/services/fcm_client.go` - common phone notification client contract and Firebase client.-- `api/pkg/services/phone_notification_service.go` - message construction and transport-client lookup.-- `api/pkg/services/http_notification_sender.go` - HTTP request encoding, retry classification, and timeout.-- `api/pkg/services/http_notification_sender_test.go` - payload, retry, and response tests.-- `api/pkg/services/phone_notification_service_test.go` - message and heartbeat integration tests with hand-written fakes.-- `api/pkg/validators/phone_handler_validator_test.go` - URL token validation tests for both phone update routes.-- `tests/adapter-emulator/Dockerfile` - container image for the HTTPS adapter emulator.-- `tests/adapter-emulator/go.mod` - isolated emulator module.-- `tests/adapter-emulator/main.go` - HTTPS callback and HTTP control server startup.-- `tests/adapter-emulator/emulator.go` - gateway registry, deduplication, and callback records.-- `tests/adapter-emulator/api_client.go` - existing httpSMS phone API calls.-- `tests/adapter-emulator/notification_handler.go` - FCM-envelope message and heartbeat handling.-- `tests/adapter-emulator/control_handler.go` - test registration, incoming-message, and record endpoints.-- `tests/adapter_integration_test.go` - outgoing, incoming, and heartbeat end-to-end tests.-- `tests/generate-adapter-certificates.sh` - throwaway CA and server-certificate generation.--### Modify--- `api/pkg/entities/phone.go` - add `NotificationTransport`, `NotificationTransport()`, and `NotificationURL()`.-- `api/pkg/services/fcm_client.go` - keep the SDK wrapper; document its role as the low-level Firebase client.-- `api/pkg/services/phone_notification_service.go` - replace direct Firebase messages with neutral notifications and transport-aware failure text.-- `api/pkg/validators/phone_handler_validator.go` - inject and apply the endpoint policy for URL-like tokens.-- `api/pkg/di/container.go` - construct the HTTP client, transport-client map,- and updated service dependencies.-- `api/pkg/requests/phone_update_request.go` - document dual-purpose `fcm_token`.-- `api/pkg/requests/phone_fcm_token_request.go` - document dual-purpose `fcm_token`.-- `api/pkg/entities/phone_notification.go` - update FCM-specific comments to transport-neutral wording.-- `api/docs/docs.go` - regenerate with `swag`.-- `api/docs/swagger.json` - regenerate with `swag`.-- `api/docs/swagger.yaml` - regenerate with `swag`.-- `tests/docker-compose.yml` - run the emulator and mount TLS material.-- `tests/.env.test` - allowlist the emulator hostname only in local mode.-- `tests/helpers_test.go` - adapter setup, control client, and internal-event helpers.-- `tests/README.md` - document emulator architecture and commands.-- `.github/workflows/api.yml` - generate adapter certificates before Docker startup.-- `.gitignore` - ignore generated adapter certificates.-------### Task 1: Classify the Existing Token Field--**Files:**-- Modify: `api/pkg/entities/phone.go`-- Create: `api/pkg/entities/phone_test.go`--**Interfaces:**-- Consumes: `Phone.FcmToken *string`-- Produces:--```go-type NotificationTransport string--const (- NotificationTransportFCM NotificationTransport = "fcm"- NotificationTransportHTTP NotificationTransport = "http"-)--func (phone *Phone) NotificationTransport() (NotificationTransport, error)-func (phone *Phone) NotificationURL() (*url.URL, error)-```--- [ ] **Step 1: Write failing transport-classification tests**--Create `api/pkg/entities/phone_test.go`:--```go-package entities--import (- "testing"-- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--func stringPointer(value string) *string {- return &value-}--func TestPhoneNotificationTransport(t *testing.T) {- tests := []struct {- name string- token *string- transport NotificationTransport- hasError bool- }{- {name: "firebase token", token: stringPointer("fcm-token:value"), transport: NotificationTransportFCM},- {name: "public https url", token: stringPointer("https://adapter.example.com/notify"), transport: NotificationTransportHTTP},- {name: "missing token", token: nil, hasError: true},- {name: "empty token", token: stringPointer(" "), hasError: true},- {name: "http url", token: stringPointer("http://adapter.example.com/notify"), hasError: true},- {name: "ftp url", token: stringPointer("ftp://adapter.example.com/notify"), hasError: true},- {name: "missing host", token: stringPointer("https:///notify"), hasError: true},- {name: "embedded credentials", token: stringPointer("https://user:[email protected]/notify"), hasError: true},- {name: "malformed url", token: stringPointer("https://[::1"), hasError: true},- }-- for _, test := range tests {- t.Run(test.name, func(t *testing.T) {- phone := &Phone{FcmToken: test.token}-- transport, err := phone.NotificationTransport()-- if test.hasError {- require.Error(t, err)- return- }- require.NoError(t, err)- assert.Equal(t, test.transport, transport)- })- }-}--func TestPhoneNotificationURL(t *testing.T) {- phone := &Phone{FcmToken: stringPointer("https://adapter.example.com/notify?tenant=42")}-- endpoint, err := phone.NotificationURL()-- require.NoError(t, err)- assert.Equal(t, "https", endpoint.Scheme)- assert.Equal(t, "adapter.example.com", endpoint.Hostname())- assert.Equal(t, "/notify", endpoint.Path)- assert.Equal(t, "tenant=42", endpoint.RawQuery)-}--func TestPhoneNotificationURLRejectsFCMToken(t *testing.T) {- phone := &Phone{FcmToken: stringPointer("fcm-token:value")}-- _, err := phone.NotificationURL()-- require.Error(t, err)-}-```--- [ ] **Step 2: Run the entity tests and confirm the new API is missing**--Run:--```bash-cd api-go test ./pkg/entities -run 'TestPhoneNotification' -count=1-```--Expected: compilation fails because `NotificationTransport`,-`NotificationTransportFCM`, `NotificationTransportHTTP`,-`Phone.NotificationTransport`, and `Phone.NotificationURL` do not exist.--- [ ] **Step 3: Implement token classification once on `Phone`**--Add imports for `fmt`, `net/url`, and `strings` in-`api/pkg/entities/phone.go`, then add:--```go-// NotificationTransport identifies how a phone receives wake-up notifications.-type NotificationTransport string--const (- // NotificationTransportFCM sends notifications through Firebase.- NotificationTransportFCM NotificationTransport = "fcm"- // NotificationTransportHTTP sends notifications to a public HTTPS endpoint.- NotificationTransportHTTP NotificationTransport = "http"-)--// NotificationTransport returns the transport encoded by FcmToken.-func (phone *Phone) NotificationTransport() (NotificationTransport, error) {- if phone.FcmToken == nil || strings.TrimSpace(*phone.FcmToken) == "" {- return "", fmt.Errorf("phone has no notification token")- }-- token := strings.TrimSpace(*phone.FcmToken)- endpoint, err := url.Parse(token)- if err != nil {- if strings.Contains(token, "://") {- return "", fmt.Errorf("invalid notification URL: %w", err)- }- return NotificationTransportFCM, nil- }-- if endpoint.Scheme == "" {- return NotificationTransportFCM, nil- }- if endpoint.Scheme != "https" {- return "", fmt.Errorf("notification URL must use https")- }- if endpoint.Hostname() == "" {- return "", fmt.Errorf("notification URL must include a hostname")- }- return NotificationTransportHTTP, nil-}--// NotificationURL returns the parsed endpoint for an HTTP notification token.-func (phone *Phone) NotificationURL() (*url.URL, error) {- transport, err := phone.NotificationTransport()- if err != nil {- return nil, err- }- if transport != NotificationTransportHTTP {- return nil, fmt.Errorf("phone notification transport is [%s], not HTTP", transport)- }-- endpoint, err := url.Parse(strings.TrimSpace(*phone.FcmToken))- if err != nil {- return nil, fmt.Errorf("cannot parse notification URL: %w", err)- }- return endpoint, nil-}-```--Before finishing this step, replace the plain `fmt.Errorf` wrappers with-`stacktrace.Propagatef` or `stacktrace.NewErrorf` to match repository error-conventions. Preserve the exact public method signatures above.--- [ ] **Step 4: Run the focused entity tests**--Run:--```bash-cd api-go test ./pkg/entities -run 'TestPhoneNotification' -count=1-```--Expected: PASS.--- [ ] **Step 5: Format and commit**--Run:--```bash-cd api-go-fumpt -w pkg/entities/phone.go pkg/entities/phone_test.go-git add pkg/entities/phone.go pkg/entities/phone_test.go-git commit -m "feat(api): classify phone notification tokens"-```-------### Task 2: Enforce Public HTTPS Endpoint Policy--**Files:**-- Create: `api/pkg/services/notification_endpoint_policy.go`-- Create: `api/pkg/services/notification_endpoint_policy_test.go`--**Interfaces:**-- Consumes: parsed HTTPS endpoints from `Phone.NotificationURL()`-- Produces:--```go-type HostResolver interface {- LookupNetIP(ctx context.Context, network string, host string) ([]netip.Addr, error)-}--type NotificationEndpointPolicy struct {- resolver HostResolver- allowedPrivateHosts map[string]struct{}-}--func NewNotificationEndpointPolicy(resolver HostResolver, allowedPrivateHosts []string) *NotificationEndpointPolicy-func (policy *NotificationEndpointPolicy) Validate(ctx context.Context, endpoint *url.URL) ([]netip.Addr, error)-func (policy *NotificationEndpointPolicy) DialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error)-```--- [ ] **Step 1: Write failing policy tests with a deterministic resolver**--Create `api/pkg/services/notification_endpoint_policy_test.go` with:--```go-package services--import (- "context"- "net/netip"- "net/url"- "testing"-- "github.com/stretchr/testify/assert"- "github.com/stretchr/testify/require"-)--type staticHostResolver struct {- addresses map[string][]netip.Addr- err error-}--func (resolver *staticHostResolver) LookupNetIP(_ context.Context, _ string, host string) ([]netip.Addr, error) {- if resolver.err != nil {- return nil, resolver.err- }- return resolver.addresses[host], nil-}--func TestNotificationEndpointPolicyValidate(t *testing.T) {- tests := []struct {- name string- rawURL string- addresses []netip.Addr- hasError bool- }{- {name: "public IPv4", rawURL: "https://adapter.example.com/notify", addresses: []netip.Addr{netip.MustParseAddr("8.8.8.8")}},- {name: "public IPv6", rawURL: "https://adapter.example.com/notify", addresses: []netip.Addr{netip.MustParseAddr("2606:4700:4700::1111")}},- {name: "loopback", rawURL: "https://adapter.example.com/notify", addresses: []netip.Addr{netip.MustParseAddr("127.0.0.1")}, hasError: true},- {name: "private", rawURL: "https://adapter.example.com/notify", addresses: []netip.Addr{netip.MustParseAddr("10.0.0.5")}, hasError: true},- {name: "link local", rawURL: "https://adapter.example.com/notify", addresses: []netip.Addr{netip.MustParseAddr("169.254.169.254")}, hasError: true},- {name: "carrier grade NAT", rawURL: "https://adapter.example.com/notify", addresses: []netip.Addr{netip.MustParseAddr("100.64.0.1")}, hasError: true},- {name: "documentation range", rawURL: "https://adapter.example.com/notify", addresses: []netip.Addr{netip.MustParseAddr("203.0.113.1")}, hasError: true},- {name: "unique local IPv6", rawURL: "https://adapter.example.com/notify", addresses: []netip.Addr{netip.MustParseAddr("fd00::1")}, hasError: true},- {name: "mixed public and private", rawURL: "https://adapter.example.com/notify", addresses: []netip.Addr{netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("10.0.0.5")}, hasError: true},- {name: "embedded credentials", rawURL: "https://user:[email protected]/notify", addresses: []netip.Addr{netip.MustParseAddr("8.8.8.8")}, hasError: true},- {name: "insecure scheme", rawURL: "http://adapter.example.com/notify", addresses: []netip.Addr{netip.MustParseAddr("8.8.8.8")}, hasError: true},- }-- for _, test := range tests {- t.Run(test.name, func(t *testing.T) {- endpoint, err := url.Parse(test.rawURL)- require.NoError(t, err)- policy := NewNotificationEndpointPolicy(&staticHostResolver{- addresses: map[string][]netip.Addr{endpoint.Hostname(): test.addresses},- }, nil)-- addresses, err := policy.Validate(context.Background(), endpoint)-- if test.hasError {- require.Error(t, err)- return- }- require.NoError(t, err)- assert.Equal(t, test.addresses, addresses)- })- }-}-```--Add a connection-time test whose resolver returns a public address during the-first `Validate` call and `127.0.0.1` during `DialContext`. Assert that the-recording dialer is never invoked. Implement the recording dialer as a local-function injected through an unexported `dialValidated` helper so the test does-not make a real network connection.--Add an exact-host allowlist test:--```go-func TestNotificationEndpointPolicyAllowsPrivateAddressForExactLocalHost(t *testing.T) {- endpoint, err := url.Parse("https://adapter-emulator:9091/notifications/gateway-1")- require.NoError(t, err)- policy := NewNotificationEndpointPolicy(&staticHostResolver{- addresses: map[string][]netip.Addr{- "adapter-emulator": {netip.MustParseAddr("172.20.0.8")},- },- }, []string{"adapter-emulator"})-- addresses, err := policy.Validate(context.Background(), endpoint)-- require.NoError(t, err)- assert.Equal(t, []netip.Addr{netip.MustParseAddr("172.20.0.8")}, addresses)-}-```--Also assert that `adapter-emulator.example.com`, a private IP-literal URL, and-any non-allowlisted private hostname remain rejected.--- [ ] **Step 2: Run the policy tests and confirm the types are missing**--Run:--```bash-cd api-go test ./pkg/services -run 'TestNotificationEndpointPolicy' -count=1-```--Expected: compilation fails because `NotificationEndpointPolicy` and its-constructor do not exist.--- [ ] **Step 3: Implement reserved-range checks**--Create `api/pkg/services/notification_endpoint_policy.go`. Define the resolver-interface above and these blocked prefixes:--```go-var blockedNotificationPrefixes = []netip.Prefix{- netip.MustParsePrefix("0.0.0.0/8"),- netip.MustParsePrefix("10.0.0.0/8"),- netip.MustParsePrefix("100.64.0.0/10"),- netip.MustParsePrefix("127.0.0.0/8"),- netip.MustParsePrefix("169.254.0.0/16"),- netip.MustParsePrefix("172.16.0.0/12"),- netip.MustParsePrefix("192.0.0.0/24"),- netip.MustParsePrefix("192.0.2.0/24"),- netip.MustParsePrefix("192.168.0.0/16"),- netip.MustParsePrefix("198.18.0.0/15"),- netip.MustParsePrefix("198.51.100.0/24"),- netip.MustParsePrefix("203.0.113.0/24"),- netip.MustParsePrefix("224.0.0.0/4"),- netip.MustParsePrefix("240.0.0.0/4"),- netip.MustParsePrefix("::/128"),- netip.MustParsePrefix("::1/128"),- netip.MustParsePrefix("100::/64"),- netip.MustParsePrefix("2001:db8::/32"),- netip.MustParsePrefix("fc00::/7"),- netip.MustParsePrefix("fe80::/10"),- netip.MustParsePrefix("ff00::/8"),-}-```--Implement:--```go-func isPublicNotificationAddress(address netip.Addr) bool {- address = address.Unmap()- if !address.IsValid() || !address.IsGlobalUnicast() {- return false- }- for _, prefix := range blockedNotificationPrefixes {- if prefix.Contains(address) {- return false- }- }- return true-}-```--`Validate` must verify HTTPS, hostname presence, at least one DNS result, and-every resolved address passing-`isPublicNotificationAddress`. Private addresses are accepted only when the-lowercased hostname exactly matches `allowedPrivateHosts`; never wildcard or-suffix-match. Wrap resolver and validation errors with stacktrace context-without including the raw URL.--- [ ] **Step 4: Implement validated dialing**--Add:--```go-func (policy *NotificationEndpointPolicy) DialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {- return func(ctx context.Context, network string, address string) (net.Conn, error) {- host, port, err := net.SplitHostPort(address)- if err != nil {- return nil, stacktrace.Propagatef(err, "cannot split notification endpoint address")- }-- endpoint := &url.URL{Scheme: "https", Host: net.JoinHostPort(host, port)}- addresses, err := policy.Validate(ctx, endpoint)- if err != nil {- return nil, stacktrace.Propagatef(err, "notification endpoint is not public")- }-- var lastErr error- for _, resolved := range addresses {- connection, dialErr := dialer.DialContext(ctx, network, net.JoinHostPort(resolved.String(), port))- if dialErr == nil {- return connection, nil- }- lastErr = dialErr- }- return nil, stacktrace.Propagatef(lastErr, "cannot connect to notification endpoint")- }-}-```--Factor the final connection loop through an unexported function variable or-method that accepts a dial function, allowing the DNS-rebinding test to assert-the selected address without opening a socket. Do not perform a normal second-hostname dial after validation.--- [ ] **Step 5: Run focused tests**--Run:--```bash-cd api-go test ./pkg/services -run 'TestNotificationEndpointPolicy' -count=1-```--Expected: PASS.--- [ ] **Step 6: Format and commit**--Run:--```bash-cd api-go-fumpt -w pkg/services/notification_endpoint_policy.go pkg/services/notification_endpoint_policy_test.go-git add pkg/services/notification_endpoint_policy.go pkg/services/notification_endpoint_policy_test.go-git commit -m "feat(api): validate adapter endpoints"-```-------### Task 3: Add the Transport Client Map--**Files:**-- Modify: `api/pkg/services/fcm_client.go`-- Modify: `api/pkg/services/phone_notification_service.go`-- Modify: `api/pkg/services/phone_notification_service_test.go`--**Interfaces:**-- Consumes:--```go-func (phone *entities.Phone) NotificationTransport() (entities.NotificationTransport, error)-```--- Produces:--```go-type FCMClient interface {- Send(context.Context, *messaging.Message) (string, error)-}-```--- [ ] **Step 1: Write failing transport-client map tests**--Create a recording client in `phone_notification_service_test.go`:--```go-type recordingPhoneNotificationClient struct {- message *messaging.Message- result string- err error- calls int-}--func (client *recordingPhoneNotificationClient) Send(_ context.Context, message *messaging.Message) (string, error) {- client.calls++- client.message = message- return client.result, client.err-}-```--Add tests for map-based FCM and HTTP selection, the same message pointer,-trimmed `message.Token`, absent transport entries, invalid tokens, and nil-messages.--- [ ] **Step 2: Run the service tests and confirm the map dependency is missing**--Run:--```bash-cd api-go test ./pkg/services -run 'TestPhoneNotificationService' -count=1-```--Expected: compilation fails because the service does not accept the client map.--- [ ] **Step 3: Implement focused map-based delivery**--Store `map[entities.NotificationTransport]FCMClient` on-`PhoneNotificationService` and implement:--```go-func (service *PhoneNotificationService) sendPhoneNotification(- ctx context.Context,- phone *entities.Phone,- message *messaging.Message,-) (string, entities.NotificationTransport, error) {- // Validate message, classify once, map lookup, set trimmed token, send.-}-```--Update comments in `api/pkg/services/fcm_client.go` to describe `FCMClient` as-the common phone notification transport boundary. Use the Firebase client-directly; do not add a wrapper or dispatcher.--- [ ] **Step 4: Run focused tests**--Run:--```bash-cd api-go test ./pkg/services -run 'TestPhoneNotificationService' -count=1-```--Expected: PASS.--- [ ] **Step 5: Format and commit**--Run:--```bash-cd api-go-fumpt -w pkg/services/fcm_client.go pkg/services/phone_notification_service.go pkg/services/phone_notification_service_test.go-git add pkg/services/fcm_client.go pkg/services/phone_notification_service.go pkg/services/phone_notification_service_test.go-git commit -m "refactor(api): dispatch gateway notifications"-```-------### Task 4: Implement the SSRF-safe HTTP Sender--**Files:**-- Create: `api/pkg/services/http_notification_sender.go`-- Create: `api/pkg/services/http_notification_sender_test.go`--**Interfaces:**-- Consumes:--```go-type FCMClient interface {- Send(context.Context, *messaging.Message) (string, error)-}-```--- Produces:--```go-type HTTPNotificationSender struct {- logger telemetry.Logger- client *http.Client- retrier *retry.Retrier- timeout time.Duration-}--func NewHTTPNotificationSender(- logger telemetry.Logger,- client *http.Client,-) *HTTPNotificationSender--func (sender *HTTPNotificationSender) Send(- ctx context.Context,- message *messaging.Message,-) (string, error)-```--- [ ] **Step 1: Write failing payload and success tests**--Create `api/pkg/services/http_notification_sender_test.go`. Use a custom-`roundTripFunc`:--```go-type roundTripFunc func(*http.Request) (*http.Response, error)--func (roundTrip roundTripFunc) RoundTrip(request *http.Request) (*http.Response, error) {- return roundTrip(request)-}-```--Construct the sender in tests with a reusable retrier configured through-`newHTTPNotificationRetrier(0)` so retry delay is zero from initialization.-Use a public address from the test resolver, and a client whose custom-RoundTripper does not dial.--Assert the request:--```go-assert.Equal(t, http.MethodPost, request.Method)-assert.Equal(t, "application/json", request.Header.Get("Content-Type"))-```--Keep a test-only decoding struct and assert this structure:--```go-type httpNotificationRequest struct {- Message struct {- Token string `json:"token"`- Data map[string]string `json:"data"`- Android struct {- Priority string `json:"priority"`- TTL string `json:"ttl,omitempty"`- } `json:"android"`- } `json:"message"`-}-```--Return `204 No Content` and assert `Send` succeeds with result `http/success`.--- [ ] **Step 2: Write failing retry-classification tests**--Add table-driven tests for:--- network error then `202`: two calls, success;-- `408` then `200`: two calls, success;-- `429` then `204`: two calls, success;-- `500`, `502`, then `204`: three calls, success;-- `400`: one call, error;-- three `503` responses: three calls, error;-- redirects use Go's default client behavior; do not add terminal redirect- handling;-- response with a body larger than the discard limit: success without reading- unbounded content.--Assert retry attempts receive fresh requests and bodies.--- [ ] **Step 3: Run the HTTP sender tests and confirm the type is missing**--Run:--```bash-cd api-go test ./pkg/services -run 'TestHTTPNotificationSender' -count=1-```--Expected: compilation fails because `HTTPNotificationSender` does not exist.--- [ ] **Step 4: Implement the FCM-compatible HTTP payload**--Create `api/pkg/services/http_notification_sender.go` and build the one-use-payload directly with `map[string]any`:--```go-payload := map[string]any{- "message": message,-}-```--Obtain the destination from `message.Token`. Rely on-`messaging.Message.MarshalJSON` and `messaging.AndroidConfig.MarshalJSON` for-the FCM shape and protobuf TTL, including `10*time.Minute` as `"600s"`. Build a-new request body for every attempt so retries never reuse a consumed reader.-Reject nil messages explicitly with a stacktrace-consistent error.--- [ ] **Step 5: Implement bounded retries**--Implement these helpers:--```go-func isRetryableNotificationStatus(statusCode int) bool {- return statusCode == http.StatusRequestTimeout ||- statusCode == http.StatusTooManyRequests ||- statusCode >= http.StatusInternalServerError-}--func notificationRetryDelay(attempt uint) time.Duration {- return time.Duration(1<<(attempt-1)) * 250 * time.Millisecond-}-```--Create one reusable retrier during sender initialization:--```go-func newHTTPNotificationRetrier(delay time.Duration) *retry.Retrier {- return retry.New(- retry.Attempts(3),- retry.Delay(delay),- retry.DelayType(retry.BackOffDelay),- retry.LastErrorOnly(true),- retry.RetryIf(isRetryableNotificationError),- )-}-```--Do not configure this retrier with `retry.Context`: each `Send` has a different-caller context. Instead, check caller cancellation in the operation and return-a terminal error, while deriving each attempt's five-second context from that-caller.--Focused sender methods must:--1. parse `message.Token`;-2. marshal the request body once, then create a fresh reader per request;-3. create a child context with the configured timeout per attempt;-4. set `Content-Type`;-5. call `client.Do`;-6. close each response body after copying at most 4 KiB to `io.Discard`;-7. return `http/success` for any `2xx`;-8. retry only network errors, `408`, `429`, and `5xx` while attempts remain;-9. treat request construction, caller cancellation, and other statuses as- terminal;-10. return a stacktrace-wrapped error.--Do not use the container's retrying HTTP client; retries belong in this sender-so status classification and attempt count are explicit.--- [ ] **Step 6: Add heartbeat tests**--Add a heartbeat payload test with `KEY_HEARTBEAT_ID`, high priority, and nil-TTL; assert the `ttl` field is omitted.-Use the standard HTTP telemetry and logging path without feature-specific URL-redaction.--- [ ] **Step 7: Run focused tests**--Run:--```bash-cd api-go test ./pkg/services -run 'TestHTTPNotificationSender' -count=1-```--Expected: PASS.--- [ ] **Step 8: Format and commit**--Run:--```bash-cd api-go-fumpt -w pkg/services/http_notification_sender.go pkg/services/http_notification_sender_test.go-git add pkg/services/http_notification_sender.go pkg/services/http_notification_sender_test.go-git commit -m "feat(api): send notifications to adapters"-```-------### Task 5: Integrate Message and Heartbeat Notifications--**Files:**-- Modify: `api/pkg/services/phone_notification_service.go`-- Create: `api/pkg/services/phone_notification_service_test.go`-- Modify: `api/pkg/entities/phone_notification.go`--**Interfaces:**-- Consumes:--```go-map[entities.NotificationTransport]FCMClient-```--- Produces:--```go-type NotificationEventDispatcher interface {- Dispatch(ctx context.Context, event cloudevents.Event) error- DispatchWithTimeout(ctx context.Context, event cloudevents.Event, timeout time.Duration) (string, error)-}--func NewNotificationService(- logger telemetry.Logger,- tracer telemetry.Tracer,- phoneNotificationClients map[entities.NotificationTransport]FCMClient,- phoneRepository repositories.PhoneRepository,- phoneNotificationRepository repositories.PhoneNotificationRepository,- messageSendScheduleRepository repositories.MessageSendScheduleRepository,- dispatcher NotificationEventDispatcher,-) *PhoneNotificationService-```--- [ ] **Step 1: Write failing service tests with hand-written fakes**--Create `api/pkg/services/phone_notification_service_test.go`.--Define repository fakes by embedding the interfaces and overriding only methods-used by the tests:--```go-type phoneNotificationPhoneRepository struct {- repositories.PhoneRepository- phone *entities.Phone- err error-}--func (repository *phoneNotificationPhoneRepository) LoadByID(- _ context.Context,- _ entities.UserID,- _ uuid.UUID,-) (*entities.Phone, error) {- return repository.phone, repository.err-}--type phoneNotificationRepository struct {- repositories.PhoneNotificationRepository- notificationID uuid.UUID- status entities.PhoneNotificationStatus-}--func (repository *phoneNotificationRepository) UpdateStatus(- _ context.Context,- notificationID uuid.UUID,- status entities.PhoneNotificationStatus,-) error {- repository.notificationID = notificationID- repository.status = status- return nil-}-```--Add a fake event dispatcher that records CloudEvents and returns no error. Add-recording `FCMClient` implementations through a transport-keyed map.--Test `Send` with an HTTPS token and assert:--- `KEY_MESSAGE_ID` equals `params.MessageID.String()`;-- priority is `normal`;-- TTL equals `phone.MessageExpirationDuration()`;-- the same `messaging.Message` pointer reaches the HTTP client;-- a `message.notification.sent` event is dispatched;-- phone-notification status becomes sent.--Test an HTTP sender error and assert:--- `message.notification.failed` is dispatched;-- status becomes failed;-- the payload error says the adapter endpoint could not be notified;-- the payload does not tell the user to reinstall Android.--Test an FCM sender error and assert the existing Android reinstallation guidance-is preserved.--Test `SendHeartbeatFCM` with an HTTPS token and assert:--- `KEY_HEARTBEAT_ID` parses as RFC3339;-- priority is `high`;-- TTL is nil;-- heartbeat sender errors are logged and return nil, preserving current- heartbeat behavior.--Also test explicit nil-message handling and a missing transport map entry.--- [ ] **Step 2: Run the service tests and confirm the constructor mismatch**--Run:--```bash-cd api-go test ./pkg/services -run 'TestPhoneNotificationService' -count=1-```--Expected: compilation fails because `PhoneNotificationService` still consumes-`FCMClient` and a concrete `*EventDispatcher`.--- [ ] **Step 3: Replace direct Firebase message creation**--In `api/pkg/services/phone_notification_service.go`:--- construct Firebase `messaging.Message` values directly;-- replace the direct client with- `phoneNotificationClients map[entities.NotificationTransport]FCMClient`;-- change the constructor to the exact signature above;-- change `eventDispatcher` to `NotificationEventDispatcher`.--Add a private `sendPhoneNotification` helper that validates the message,-classifies transport once, performs a map lookup, sets the trimmed token, calls-the selected client, and returns the transport with the result or error.--For message notifications, construct:--```go-ttl := phone.MessageExpirationDuration()-message := &messaging.Message{- Data: map[string]string{- "KEY_MESSAGE_ID": params.MessageID.String(),- },- Android: &messaging.AndroidConfig{- Priority: "normal",- TTL: &ttl,- },-}-```--For heartbeat notifications, call:--```go-message := &messaging.Message{- Data: map[string]string{- "KEY_HEARTBEAT_ID": time.Now().UTC().Format(time.RFC3339),- },- Android: &messaging.AndroidConfig{Priority: "high"},-}-```--- [ ] **Step 4: Add transport-aware failure text**--Use the transport returned by `sendPhoneNotification`; do not classify the-phone a second time.--For HTTP use:--```go-msg := fmt.Sprintf(- "cannot notify the configured adapter for phone [%s]. Check the adapter URL and availability.",- phone.PhoneNumber,-)-```--For Firebase preserve:--```go-msg := fmt.Sprintf(- "cannot send notification to your phone [%s]. Reinstall the httpSMS app on your Android phone.",- phone.PhoneNumber,-)-```--Log the technical wrapped error without logging the raw token. If transport-classification unexpectedly fails here, send that error through-`handleNotificationFailed` with a generic notification-configuration message.--- [ ] **Step 5: Update transport-specific comments**--In `api/pkg/entities/phone_notification.go`, change:--```go-// PhoneNotification represents an FCM notification to a mobile phone-```--to:--```go-// PhoneNotification represents a scheduled wake-up notification for a phone gateway.-```--Update `PhoneNotificationService` and `SendHeartbeatFCM` comments so they refer-to phone gateway notifications rather than only mobile phones. Keep the method-name `SendHeartbeatFCM` in this change to avoid an unrelated listener rename.--- [ ] **Step 6: Run focused tests**--Run:--```bash-cd api-go test ./pkg/services -run 'TestPhoneNotificationService|TestHTTPNotificationSender' -count=1-```--Expected: PASS.--- [ ] **Step 7: Format and commit**--Run:--```bash-cd api-go-fumpt -w pkg/services/phone_notification_service.go pkg/services/phone_notification_service_test.go pkg/entities/phone_notification.go-git add pkg/services/phone_notification_service.go pkg/services/phone_notification_service_test.go pkg/entities/phone_notification.go-git commit -m "feat(api): route phone gateway wake-ups"-```-------### Task 6: Validate URL Tokens, Wire Dependencies, and Regenerate Swagger--**Files:**-- Modify: `api/pkg/validators/phone_handler_validator.go`-- Create: `api/pkg/validators/phone_handler_validator_test.go`-- Modify: `api/pkg/di/container.go`-- Modify: `api/pkg/requests/phone_update_request.go`-- Modify: `api/pkg/requests/phone_fcm_token_request.go`-- Modify: `api/docs/docs.go`-- Modify: `api/docs/swagger.json`-- Modify: `api/docs/swagger.yaml`--**Interfaces:**-- Consumes:--```go-func (container *Container) FCMClient() services.FCMClient-func NewHTTPNotificationSender(logger telemetry.Logger, client *http.Client) *HTTPNotificationSender-```--- Produces container factories:--```go-func (container *Container) NotificationHTTPClient() *http.Client-func (container *Container) PhoneNotificationClients() map[entities.NotificationTransport]services.FCMClient-```--- Produces validator constructor:--```go-func NewPhoneHandlerValidator(- logger telemetry.Logger,- tracer telemetry.Tracer,- scheduleService *services.MessageSendScheduleService,- endpointPolicy *services.NotificationEndpointPolicy,-) *PhoneHandlerValidator-```--- [ ] **Step 1: Write failing validator tests**--Create `api/pkg/validators/phone_handler_validator_test.go`.--Build the validator with a static public resolver and nil schedule service for-requests without a schedule ID. Add tests for both `ValidateUpsert` and-`ValidateFCMToken`:--```go-func TestPhoneHandlerValidatorAcceptsPublicHTTPSNotificationURL(t *testing.T) {- validator := newPhoneHandlerValidatorWithAddresses(map[string][]netip.Addr{- "adapter.example.com": {netip.MustParseAddr("8.8.8.8")},- })-- errors := validator.ValidateFCMToken(context.Background(), requests.PhoneFCMToken{- PhoneNumber: "+18005550199",- FcmToken: "https://adapter.example.com/notify",- SIM: entities.SIM1.String(),- })-- assert.Empty(t, errors)-}-```--Add rejection tests for `http://`, loopback resolution, private resolution,-mixed public/private resolution, and malformed HTTPS.-Add an opaque FCM token test to prove the resolver is not required for Firebase-tokens.--- [ ] **Step 2: Run validator tests and confirm unsafe URLs are accepted**--Run:--```bash-cd api-go test ./pkg/validators -run 'TestPhoneHandlerValidator.*Notification' -count=1-```--Expected: tests fail because the validator only checks token length.--- [ ] **Step 3: Inject and apply endpoint policy**--Add `endpointPolicy *services.NotificationEndpointPolicy` to-`PhoneHandlerValidator` and its constructor.--Add:--```go-func (validator *PhoneHandlerValidator) validateNotificationToken(- ctx context.Context,- token string,- result url.Values,-) {- token = strings.TrimSpace(token)- if token == "" {- return- }-- phone := &entities.Phone{FcmToken: &token}- transport, err := phone.NotificationTransport()- if err != nil {- result.Add("fcm_token", err.Error())- return- }- if transport != entities.NotificationTransportHTTP {- return- }-- endpoint, err := phone.NotificationURL()- if err != nil {- result.Add("fcm_token", err.Error())- return- }- if _, err = validator.endpointPolicy.Validate(ctx, endpoint); err != nil {- result.Add("fcm_token", "fcm_token must be a public HTTPS adapter URL")- }-}-```--Call it after structural validation succeeds in both `ValidateUpsert` and-`ValidateFCMToken`. Change `ValidateFCMToken` to use its context argument.--- [ ] **Step 4: Add SSRF-safe container factories**--In `api/pkg/di/container.go`, add:--```go-func (container *Container) NotificationEndpointPolicy() *services.NotificationEndpointPolicy {- if container.notificationEndpointPolicy != nil {- return container.notificationEndpointPolicy- }-- allowedPrivateHosts := []string{} // Superseded: no private-host allowlist is configured.- container.notificationEndpointPolicy = services.NewNotificationEndpointPolicy(- net.DefaultResolver,- allowedPrivateHosts,- )- return container.notificationEndpointPolicy-}-```--Add a client factory:--```go-func (container *Container) NotificationHTTPClient() *http.Client {- policy := container.NotificationEndpointPolicy()- transport := &http.Transport{- Proxy: nil,- DialContext: policy.DialContext(&net.Dialer{- Timeout: 5 * time.Second,- KeepAlive: 30 * time.Second,- }),- ForceAttemptHTTP2: true,- TLSClientConfig: &tls.Config{- MinVersion: tls.VersionTLS12,- },- }-- return &http.Client{- Transport: otelroundtripper.New(- otelroundtripper.WithName("phone_notification_http"),- otelroundtripper.WithParent(transport),- otelroundtripper.WithMeter(otel.GetMeterProvider().Meter(container.projectID)),- ),- }-}-```--Do not set a client-wide timeout; the sender creates the approved five-second-context for each attempt.--Add:--```go-func (container *Container) PhoneNotificationClients() map[entities.NotificationTransport]services.FCMClient {- return map[entities.NotificationTransport]services.FCMClient{- entities.NotificationTransportFCM: container.FCMClient(),- entities.NotificationTransportHTTP: services.NewHTTPNotificationSender(- container.Logger(),- container.NotificationHTTPClient(),- ),- }-}-```--Add this field to `Container`:--```go-notificationEndpointPolicy *services.NotificationEndpointPolicy-```--The cached policy ensures validation and connection-time checks use the same-allowlist. Do not cache per-request sender state.--- [ ] **Step 5: Wire service and validator constructors**--Change `container.NotificationService()` to pass-`container.PhoneNotificationClients()`.--Find `container.PhoneHandlerValidator()` and pass-`container.NotificationEndpointPolicy()` as its fourth argument. Keep existing-logger, tracer, and schedule-service arguments unchanged.--- [ ] **Step 6: Run focused package tests**--Run:--```bash-cd api-go test ./pkg/entities ./pkg/services ./pkg/validators ./pkg/di -count=1-```--Expected: PASS.--- [ ] **Step 7: Update API descriptions**--In both phone request structs, replace the generic FCM token comment with:--```go-// FcmToken is either a Firebase registration token or a public HTTPS adapter callback URL.-FcmToken string `json:"fcm_token" example:"https://adapter.example.com/notifications"`-```--Update handler Swagger descriptions for phone upsert and FCM-token upsert to-state that URL-backed phones receive FCM-compatible HTTP wake-ups. Do not add or-rename routes or JSON fields.--- [ ] **Step 8: Regenerate Swagger**--Run:--```bash-cd api-swag init --requiredByDefault --parseDependency --parseInternal-```--Expected: `docs/docs.go`, `docs/swagger.json`, and `docs/swagger.yaml` update-with the dual-purpose `fcm_token` descriptions.--- [ ] **Step 9: Run the complete API test suite**--Run:--```bash-cd api-go test ./...-```--Expected: PASS.--- [ ] **Step 10: Build the API**--Run:--```bash-cd api-go build -o ./tmp/main.exe .-```--Expected: build succeeds.--- [ ] **Step 11: Inspect the final diff for forbidden changes**--Run:--```bash-git diff --check-git diff --stat-git grep -n "fcm_token" -- api/pkg/entities/phone.go api/pkg/requests/phone_update_request.go api/pkg/requests/phone_fcm_token_request.go-```--Confirm:--- no database field or migration was added;-- `fcm_token` remains the persisted/API field;-- no message content or API key is added to the HTTP callback payload;-- scheduling and repository code are unchanged;--- [ ] **Step 12: Format and commit**--Run:--```bash-cd api-go-fumpt -w pkg/validators/phone_handler_validator.go pkg/validators/phone_handler_validator_test.go pkg/di/container.go pkg/requests/phone_update_request.go pkg/requests/phone_fcm_token_request.go-git add pkg/validators/phone_handler_validator.go pkg/validators/phone_handler_validator_test.go pkg/di/container.go pkg/requests/phone_update_request.go pkg/requests/phone_fcm_token_request.go pkg/handlers/phone_handler.go docs/docs.go docs/swagger.json docs/swagger.yaml-git commit -m "feat(api): enable URL-backed phone gateways"-```-------### Task 7: Build the Adapter Emulator and End-to-End Scenarios--**Files:**-- Create: `tests/adapter-emulator/Dockerfile`-- Create: `tests/adapter-emulator/go.mod`-- Create: `tests/adapter-emulator/main.go`-- Create: `tests/adapter-emulator/emulator.go`-- Create: `tests/adapter-emulator/api_client.go`-- Create: `tests/adapter-emulator/notification_handler.go`-- Create: `tests/adapter-emulator/control_handler.go`-- Create: `tests/adapter_integration_test.go`-- Create: `tests/generate-adapter-certificates.sh`-- Modify: `tests/docker-compose.yml`-- Modify: `tests/.env.test`-- Modify: `tests/helpers_test.go`-- Modify: `tests/README.md`-- Modify: `.github/workflows/api.yml`-- Modify: `.gitignore`--**Interfaces:**-- Emulator callback: `POST https://adapter-emulator:9091/notifications/{gatewayID}`-- Emulator control:--```text-PUT http://localhost:9092/test/gateways/{gatewayID}-POST http://localhost:9092/test/gateways/{gatewayID}/incoming-GET http://localhost:9092/test/gateways/{gatewayID}/notifications-GET http://localhost:9092/health-```--- Gateway registration:--```go-type gatewayRegistration struct {- PhoneNumber string `json:"phone_number"`- PhoneAPIKey string `json:"phone_api_key"`-}-```--- Incoming control payload:--```go-type incomingMessageRequest struct {- Contact string `json:"contact"`- Content string `json:"content"`- Encrypted bool `json:"encrypted"`-}-```--- Callback record:--```go-type notificationRecord struct {- GatewayID string `json:"gateway_id"`- Data map[string]string `json:"data"`- MessageID string `json:"message_id,omitempty"`- Kind string `json:"kind"`- Processed bool `json:"processed"`- Error string `json:"error,omitempty"`-}-```--- [ ] **Step 1: Generate throwaway TLS material**--Create `tests/generate-adapter-certificates.sh`:--```bash-#!/usr/bin/env bash-set -euo pipefail--output_dir="${1:-certs}"-mkdir -p "$output_dir"--openssl req -x509 -newkey rsa:2048 -nodes \- -keyout "$output_dir/ca-key.pem" \- -out "$output_dir/ca.pem" \- -days 2 \- -subj "/CN=httpSMS integration adapter CA"--openssl req -newkey rsa:2048 -nodes \- -keyout "$output_dir/server-key.pem" \- -out "$output_dir/server.csr" \- -subj "/CN=adapter-emulator"--cat >"$output_dir/server.ext" <<'EOF'-subjectAltName=DNS:adapter-emulator-extendedKeyUsage=serverAuth-EOF--openssl x509 -req \- -in "$output_dir/server.csr" \- -CA "$output_dir/ca.pem" \- -CAkey "$output_dir/ca-key.pem" \- -CAcreateserial \- -out "$output_dir/server.pem" \- -days 2 \- -extfile "$output_dir/server.ext"-```--Add `tests/certs/` to `.gitignore`. Do not commit generated keys or-certificates.--- [ ] **Step 2: Scaffold the isolated emulator module**--Create `tests/adapter-emulator/go.mod`:--```go-module github.com/NdoleStudio/httpsms/tests/adapter-emulator--go 1.25.0-```--Use only the standard library. Run:--```bash-cd tests/adapter-emulator-go mod tidy-```--Expected: the command succeeds without adding dependencies.--- [ ] **Step 3: Implement emulator state and deduplication**--In `tests/adapter-emulator/emulator.go`, implement:--```go-type gateway struct {- PhoneNumber string- PhoneAPIKey string-}--type emulator struct {- apiBaseURL string- client *http.Client- mu sync.RWMutex- gateways map[string]gateway- records []*notificationRecord-}--func newEmulator(apiBaseURL string, client *http.Client) *emulator {- return &emulator{- apiBaseURL: strings.TrimRight(apiBaseURL, "/"),- client: client,- gateways: make(map[string]gateway),- }-}-```--Add locked methods to register a gateway, load a gateway, record each callback,-mark it processed/failed, and list copied records for one gateway.--- [ ] **Step 4: Implement existing phone API calls**--In `tests/adapter-emulator/api_client.go`, implement:--```go-func (emulator *emulator) fetchOutstanding(- ctx context.Context,- gateway gateway,- messageID string,-) (map[string]any, error)--func (emulator *emulator) fireMessageEvent(- ctx context.Context,- gateway gateway,- messageID string,- eventName string,-) error--func (emulator *emulator) receiveMessage(- ctx context.Context,- gateway gateway,- request incomingMessageRequest,-) (map[string]any, error)--func (emulator *emulator) storeHeartbeat(- ctx context.Context,- gateway gateway,-) error-```--Use the existing routes:--```text-GET /v1/messages/outstanding?message_id={messageID}-POST /v1/messages/{messageID}/events-POST /v1/messages/receive-POST /v1/heartbeats-```--Every request sets `x-api-key`. Message events use `SENT` then `DELIVERED` with-UTC RFC3339 timestamps. Incoming messages use the gateway phone number as `to`,-the control request contact as `from`, `SIM1`, and the requested encryption-flag. Return contextual `fmt.Errorf` errors because the emulator module-intentionally does not depend on the production API module.--- [ ] **Step 5: Implement FCM-compatible callback handling**--In `tests/adapter-emulator/notification_handler.go`, decode:--```go-type callbackEnvelope struct {- Message struct {- Token string `json:"token"`- Data map[string]string `json:"data"`- } `json:"message"`-}-```--The handler must:--1. load `gatewayID` from the route;-2. return `404` for unknown gateways;-3. return `400` for unsupported data;-4. record every callback;-5. for `KEY_MESSAGE_ID`, fetch outstanding, fire `SENT`, fire `DELIVERED`, and- mark the record processed with kind `message`;-6. for `KEY_HEARTBEAT_ID`, store a heartbeat and mark the record processed with- kind `heartbeat`;-7. return `500` and retain the error string in the record when processing- fails, allowing the API sender's retry behavior to be exercised.--Processing may be synchronous because the API accepts any `2xx` and the-integration stack controls response time.--- [ ] **Step 6: Implement control and server endpoints**--In `tests/adapter-emulator/control_handler.go`, implement registration,-incoming-message, record listing, and health handlers using `http.ServeMux`.--In `main.go`, read:--```text-API_BASE_URL=http://api:8000-ADAPTER_TLS_CERT=/certs/server.pem-ADAPTER_TLS_KEY=/certs/server-key.pem-```--Start:--- HTTPS callback server on `:9091`;-- HTTP control server on `:9092`.--Use `http.Server` with finite `ReadHeaderTimeout`, `ReadTimeout`,-`WriteTimeout`, and `IdleTimeout`. Shut both servers down on SIGINT/SIGTERM.--- [ ] **Step 7: Add the emulator container**--Create `tests/adapter-emulator/Dockerfile`:--```dockerfile-FROM golang:1.25-alpine AS build-WORKDIR /src-COPY go.mod ./-RUN go mod download-COPY . .-RUN CGO_ENABLED=0 go build -o /out/adapter-emulator .--FROM alpine:3.22-RUN adduser -D -u 10001 app-USER app-COPY --from=build /out/adapter-emulator /usr/local/bin/adapter-emulator-ENTRYPOINT ["adapter-emulator"]-```--In `tests/docker-compose.yml`, add `adapter-emulator`:--```yaml-adapter-emulator:- build:- context: ./adapter-emulator- ports:- - "9092:9092"- environment:- API_BASE_URL: http://api:8000- ADAPTER_TLS_CERT: /certs/server.pem- ADAPTER_TLS_KEY: /certs/server-key.pem- volumes:- - ./certs:/certs:ro- healthcheck:- test: ["CMD", "wget", "-qO-", "http://localhost:9092/health"]- interval: 5s- timeout: 5s- retries: 10-```--Make `api` depend on the healthy emulator. Mount `./certs/ca.pem` into the API-container and set:--```yaml-SSL_CERT_FILE: /adapter-certs/ca.pem-```--Do not add a private-host allowlist; Docker DNS is used through the standard Go-HTTP transport. Keep `SSL_CERT_FILE` so the emulator certificate remains-trusted.--- [ ] **Step 8: Add adapter test helpers**--In `tests/helpers_test.go`, add `adapterControlURL`,-`systemAPIKey`, and:--```go-type adapterTestPhone struct {- testPhone- PhoneID string- GatewayID string-}--func setupAdapterPhone(ctx context.Context, t *testing.T, messagesPerMinute uint) adapterTestPhone-func dispatchInternalEvent(ctx context.Context, t *testing.T, event map[string]any)-func waitForAdapterMessageRecords(t *testing.T, gatewayID string, messageID string, timeout time.Duration) []notificationRecord-func waitForAdapterHeartbeatRecord(t *testing.T, gatewayID string, timeout time.Duration) notificationRecord-func triggerAdapterIncoming(ctx context.Context, t *testing.T, phone adapterTestPhone, contact string, content string) string-```--`setupAdapterPhone` must:--1. generate a gateway UUID and phone number;-2. create a phone API key;-3. register the gateway with the emulator control API;-4. use callback URL- `https://adapter-emulator:9091/notifications/{gatewayID}`;-5. upsert the phone through the user API and capture its phone ID;-6. bind the same callback through the phone API-key route;-7. wait for phone authorization using the existing helper.--`dispatchInternalEvent` posts a valid CloudEvent JSON body to `/v1/events` with-`x-api-key: system-user-api-key`.--- [ ] **Step 9: Write the outgoing adapter integration test**--Create `tests/adapter_integration_test.go`:--```go-func TestAdapterGatewayOutgoingMessage(t *testing.T) {- ctx := context.Background()- phone := setupAdapterPhone(ctx, t, 60)- contact := randomPhoneNumber()- content := "Adapter outgoing " + randomEncryptionKey()-- response, httpResponse, err := newAPIClient().Messages.Send(ctx, &httpsms.MessageSendParams{- From: phone.PhoneNumber,- To: contact,- Content: content,- })- require.NoError(t, err)- require.Equal(t, http.StatusOK, httpResponse.HTTPResponse.StatusCode)-- messageID := response.Data.ID.String()- message := pollMessageStatus(ctx, t, messageID, "delivered", 30*time.Second)-- assert.Equal(t, phone.PhoneNumber, message.Owner)- assert.Equal(t, contact, message.Contact)- assert.Equal(t, content, message.Content)- records := waitForAdapterMessageRecords(t, phone.GatewayID, messageID, 30*time.Second)- require.Len(t, records, 1)- assert.Equal(t, "message", records[0].Kind)- assert.True(t, records[0].Processed)- assert.Equal(t, messageID, records[0].Data["KEY_MESSAGE_ID"])-}-```--The record-list helper queries by message ID. Assert one processed record for-the successful callback flow.--- [ ] **Step 10: Write the incoming adapter integration test**--Add:--```go-func TestAdapterGatewayIncomingMessage(t *testing.T) {- ctx := context.Background()- phone := setupAdapterPhone(ctx, t, 60)- contact := randomPhoneNumber()- content := "Adapter incoming " + randomEncryptionKey()-- messageID := triggerAdapterIncoming(ctx, t, phone, contact, content)- message := pollMessageStatus(ctx, t, messageID, "received", 15*time.Second)-- assert.Equal(t, phone.PhoneNumber, message.Owner)- assert.Equal(t, contact, message.Contact)- assert.Equal(t, content, message.Content)- assert.Equal(t, "received", message.Status)-}-```--This test must call the emulator control endpoint; it must not post-`/v1/messages/receive` directly from the test runner.--- [ ] **Step 11: Write the heartbeat callback integration test**--Add:--```go-func TestAdapterGatewayHeartbeatWakeUp(t *testing.T) {- ctx := context.Background()- phone := setupAdapterPhone(ctx, t, 60)- monitorID := uuid.NewString()-- dispatchInternalEvent(ctx, t, map[string]any{- "specversion": "1.0",- "id": uuid.NewString(),- "source": "/tests/adapter-emulator",- "type": "phone.heartbeat.missed",- "time": time.Now().UTC().Format(time.RFC3339),- "datacontenttype": "application/json",- "data": map[string]any{- "phone_id": phone.PhoneID,- "user_id": "test-user-id",- "last_heartbeat_timestamp": time.Now().UTC().Add(-20 * time.Minute).Format(time.RFC3339),- "timestamp": time.Now().UTC().Format(time.RFC3339),- "monitor_id": monitorID,- "owner": phone.PhoneNumber,- },- })-- record := waitForAdapterHeartbeatRecord(t, phone.GatewayID, 30*time.Second)- assert.Equal(t, "heartbeat", record.Kind)- assert.NotEmpty(t, record.Data["KEY_HEARTBEAT_ID"])-- heartbeats, response, err := newAPIClient().Heartbeats.Index(ctx, &httpsms.HeartbeatIndexParams{- Owner: phone.PhoneNumber,- Limit: 1,- })- require.NoError(t, err)- require.Equal(t, http.StatusOK, response.HTTPResponse.StatusCode)- require.NotEmpty(t, heartbeats.Data)- assert.Equal(t, phone.PhoneNumber, heartbeats.Data[0].Owner)-}-```--The direct internal event avoids waiting for the production 16-minute monitor-interval while still exercising `PhoneNotificationListener`,-`PhoneNotificationService`, the HTTP client, the emulator callback, and the-existing heartbeat API.--- [ ] **Step 12: Update local and CI commands**--In `.github/workflows/api.yml`, after Firebase credential generation, add:--```yaml-- name: Generate adapter certificates- run: bash tests/generate-adapter-certificates.sh tests/certs-```--Update `tests/README.md` architecture, project tree, coverage checklist,-troubleshooting logs, and setup commands. The documented local sequence must-run both credential scripts before `docker compose up`.--- [ ] **Step 13: Run the complete integration suite**--Run:--```bash-cd tests-bash generate-firebase-credentials.sh firebase-credentials.json-bash generate-adapter-certificates.sh certs-docker compose up -d --build --wait-docker compose wait seed-go test -v -timeout 300s ./...-docker compose down -v-```--Expected: existing FCM/WireMock tests and all three adapter tests pass.--- [ ] **Step 14: Inspect failure logs if a scenario times out**--Run:--```bash-cd tests-docker compose logs --tail 200 api adapter-emulator-```--The outgoing logs must show callback receipt, outstanding fetch, `SENT`, and-`DELIVERED`. Incoming logs must show the emulator calling the receive route.-Heartbeat logs must show `KEY_HEARTBEAT_ID` and a successful heartbeat POST.--- [ ] **Step 15: Commit integration coverage**--Run:--```bash-git add .gitignore .github/workflows/api.yml tests-git commit -m "test(api): cover URL-backed phone gateways"-```diff --git a/docs/superpowers/specs/2026-05-26-nuxt4-vuetify4-migration-design.md b/docs/superpowers/specs/2026-05-26-nuxt4-vuetify4-migration-design.mddeleted file mode 100644index bc982b57..00000000--- a/docs/superpowers/specs/2026-05-26-nuxt4-vuetify4-migration-design.md+++ /dev/null@@ -1,385 +0,0 @@-# httpSMS Frontend Migration: Nuxt 2 + Vuetify 2 → Nuxt 4 + Vuetify 4--## Summary--Migrate the `web/` frontend from Nuxt 2 (Vue 2, Vuetify 2, Vuex, class-based components) to Nuxt 4 (Vue 3, Vuetify 4, Pinia, `<script setup lang="ts">`). Use a fresh Nuxt 4 project approach with incremental porting.--## Target Versions--| Library | Current | Target |-|---------|---------|--------|-| Nuxt | 2.18.1 | 4.x (latest) |-| Vue | 2.7.16 | 3.x (latest) |-| Vuetify | 2.7.2 | 4.x (latest) |-| State management | Vuex 3 | Pinia |-| Firebase | @nuxtjs/firebase | nuxt-vuefire |-| Component style | vue-property-decorator classes | `<script setup lang="ts">` |-| TypeScript | Partial | Full TypeScript everywhere |--## Decisions--- **Approach**: Fresh Nuxt 4 project with incremental file porting (not in-place upgrade)-- **Component style**: `<script setup lang="ts">` with Composition API-- **State**: Pinia stores split by domain-- **Firebase**: nuxt-vuefire module with composables-- **Rendering**: Static site generation (SSG)-- **Vuetify migration tool**: Use Vuetify MCP (`vuetify-mcp-get_upgrade_guide`, `vuetify-mcp-get_v4_breaking_changes`, `vuetify-mcp-get_component_api_by_version`) for every component to track breaking changes-- **Breakpoints**: Restore Vuetify 2/3 breakpoints via config (960/1280/1920/2560) to minimize layout changes--## Architecture--### Directory Structure (Nuxt 4)--```-web/-├── app/ ← All client-side code-│ ├── assets/-│ │ ├── img/-│ │ ├── styles/-│ │ │ └── settings.scss ← Vuetify SASS overrides-│ │ └── variables.scss-│ ├── components/-│ │ ├── BackButton.vue-│ │ ├── BlogAuthorBio.vue-│ │ ├── BlogInfo.vue-│ │ ├── CopyButton.vue-│ │ ├── FirebaseAuth.vue-│ │ ├── FixedHeader.vue-│ │ ├── LoadingButton.vue-│ │ ├── LoadingDashboard.vue-│ │ ├── MessageThread.vue-│ │ ├── MessageThreadHeader.vue-│ │ ├── NuxtLogo.vue-│ │ └── Toast.vue-│ ├── composables/-│ │ ├── useApi.ts ← replaces plugins/axios.ts-│ │ ├── useAuth.ts ← Firebase auth helpers-│ │ └── useNotification.ts ← Toast/snackbar helpers-│ ├── layouts/-│ │ ├── default.vue-│ │ ├── error.vue-│ │ └── website.vue-│ ├── middleware/-│ │ ├── auth.ts-│ │ └── guest.ts-│ ├── pages/ ← same structure, [id] instead of _id-│ │ ├── index.vue-│ │ ├── login.vue-│ │ ├── billing/index.vue-│ │ ├── blog/...-│ │ ├── bulk-messages/index.vue-│ │ ├── heartbeats/[id].vue-│ │ ├── messages/index.vue-│ │ ├── phone-api-keys/index.vue-│ │ ├── privacy-policy/index.vue-│ │ ├── search-messages/index.vue-│ │ ├── settings/index.vue-│ │ ├── terms-and-conditions/index.vue-│ │ └── threads/-│ │ ├── index.vue-│ │ └── [id]/index.vue-│ ├── plugins/-│ │ ├── vuetify.ts-│ │ ├── chart.client.ts-│ │ └── vue-glow.client.ts-│ ├── stores/ ← Pinia stores-│ │ ├── auth.ts-│ │ ├── messages.ts-│ │ ├── threads.ts-│ │ ├── phones.ts-│ │ ├── billing.ts-│ │ ├── notifications.ts-│ │ └── app.ts-│ ├── utils/-│ │ ├── errors.ts-│ │ ├── filters.ts-│ │ ├── capitalize.ts-│ │ └── bag.ts-│ └── app.vue-├── shared/-│ └── types/ ← API models-│ ├── api.ts-│ ├── billing.ts-│ ├── heartbeat.ts-│ ├── message-thread.ts-│ ├── message.ts-│ └── user.ts-├── public/ ← renamed from static/-│ ├── favicon.ico-│ ├── integrations.js-│ ├── header.png-│ └── templates/-├── nuxt.config.ts-├── package.json-└── tsconfig.json-```--### Key Migration Patterns--#### Components: Class-based → `<script setup>`--**Before (Vue 2):**-```vue-<script lang="ts">-import { Vue, Component, Prop } from 'vue-property-decorator'--@Component-export default class FirebaseAuth extends Vue {- @Prop({ required: false, type: String, default: '/' }) to!: string- firebaseUIInitialized = false-- mounted(): void { /* ... */ }- beforeDestroy(): void { /* ... */ }-}-</script>-```--**After (Vue 3):**-```vue-<script setup lang="ts">-import { ref, onMounted, onBeforeUnmount } from 'vue'--const props = withDefaults(defineProps<{- to?: string-}>(), { to: '/' })--const firebaseUIInitialized = ref(false)--onMounted(() => { /* ... */ })-onBeforeUnmount(() => { /* ... */ })-</script>-```--#### Vuetify Breakpoints: `$vuetify.breakpoint` → `useDisplay()`--**Before:**-```vue-<v-col :class="{ 'text-center': $vuetify.breakpoint.mdAndDown }">-```--**After:**-```vue-<script setup lang="ts">-import { useDisplay } from 'vuetify'-const { mdAndDown, lgAndUp } = useDisplay()-</script>-<template>- <v-col :class="{ 'text-center': mdAndDown }">-</template>-```--#### State: Vuex → Pinia--**Before:**-```ts-this.$store.dispatch('loadPhones', true)-this.$store.getters.getAuthUser-```--**After:**-```ts-const phonesStore = usePhonesStore()-await phonesStore.loadPhones(true)-phonesStore.authUser-```--#### Firebase: `this.$fire.auth` → VueFire composables--**Before:**-```ts-await this.$fire.auth.currentUser?.getIdToken()-```--**After:**-```ts-import { useCurrentUser } from 'vuefire'-const user = useCurrentUser()-const token = await user.value?.getIdToken()-```--#### Dynamic Routes: `_id` → `[id]`--- `pages/threads/_id/index.vue` → `pages/threads/[id]/index.vue`-- `pages/heartbeats/_id.vue` → `pages/heartbeats/[id].vue`--### Vuetify 4 Breaking Changes to Address--Using the Vuetify MCP for each component, the key changes are:--1. **CSS Layers** — mandatory in v4; adjust any custom style overrides-2. **Theme** — default is now "system" (we want dark, configure explicitly)-3. **Typography** — MD2 → MD3 type scale (text-h1 → text-display-large, etc.)-4. **Breakpoints** — reduced default sizes (restore v3 values via config)-5. **Elevation** — 25 levels → 6 levels (MD3)-6. **VBtn** — no default uppercase, grid → flex layout-7. **VSnackbar** — removed multi-line prop-8. **VSelect** — "item" slot → "internalItem"-9. **Grid** — v-row/v-col overhauled-10. **CSS Reset** — mostly removed, add selective resets--### Vuetify MCP Usage Per Component--For EVERY component/page being migrated, the implementation must:-1. Call `vuetify-mcp-get_component_api_by_version` for each Vuetify component used-2. Call `vuetify-mcp-get_v4_breaking_changes` filtered by relevant category-3. Apply the correct v4 API (props, slots, events) based on MCP output-4. Verify no deprecated props/events remain--### Pinia Store Design--Split the monolithic Vuex store into domain stores:--| Store | Responsibility |-|-------|---------------|-| `auth.ts` | Firebase auth state, user profile, onAuthStateChanged |-| `messages.ts` | Messages CRUD, search |-| `threads.ts` | Message threads, current thread |-| `phones.ts` | Phone list, heartbeats, polling |-| `billing.ts` | Usage, subscription, payments |-| `notifications.ts` | Toast/snackbar queue |-| `app.ts` | App metadata, polling state, runtime config |--### Plugin Migrations--| Old Plugin | New Approach |-|-----------|-------------|-| `plugins/axios.ts` | `composables/useApi.ts` using `$fetch` with auth header |-| `plugins/filters.ts` | `utils/filters.ts` (import explicitly or app.config globalProperties) |-| `plugins/vue-glow.ts` | `plugins/vue-glow.client.ts` (client-only plugin) |-| `plugins/chart.ts` | `plugins/chart.client.ts` (client-only plugin) |-| `plugins/errors.ts` | `utils/errors.ts` |-| `plugins/bag.ts` | `utils/bag.ts` |-| `plugins/capitalize.ts` | `utils/capitalize.ts` |-| `plugins/veutify.ts` | `plugins/vuetify.ts` (createVuetify setup) |--## Migration Order (Tasks)--### Phase 1: Scaffold & Configuration-1. Initialize fresh Nuxt 4 project in `web/` (backup old code)-2. Install dependencies (vuetify, pinia, nuxt-vuefire, sass, @mdi/js, pusher-js, etc.)-3. Configure `nuxt.config.ts` (SSG, runtime config, modules)-4. Set up Vuetify plugin with dark theme, restored breakpoints, MDI SVG icons-5. Set up nuxt-vuefire with Firebase config-6. Configure TypeScript strictly--### Phase 2: Foundation-7. Port `shared/types/` (API models — mostly copy)-8. Port `utils/` (errors, filters, bag, capitalize)-9. Create `composables/useApi.ts` (replace Axios plugin)-10. Create `composables/useAuth.ts` (Firebase auth helpers)--### Phase 3: State Management-11. Create Pinia store: `stores/auth.ts`-12. Create Pinia store: `stores/notifications.ts`-13. Create Pinia store: `stores/app.ts`-14. Create Pinia store: `stores/phones.ts`-15. Create Pinia store: `stores/messages.ts`-16. Create Pinia store: `stores/threads.ts`-17. Create Pinia store: `stores/billing.ts`--### Phase 4: Layouts & Middleware-18. Port `middleware/auth.ts`-19. Port `middleware/guest.ts`-20. Port `layouts/default.vue` (with Vuetify MCP)-21. Port `layouts/website.vue` (with Vuetify MCP)-22. Port `layouts/error.vue` (with Vuetify MCP)-23. Create `app.vue`--### Phase 5: Components (use Vuetify MCP for each)-24. Port `components/Toast.vue`-25. Port `components/LoadingDashboard.vue`-26. Port `components/LoadingButton.vue`-27. Port `components/BackButton.vue`-28. Port `components/CopyButton.vue`-29. Port `components/FixedHeader.vue`-30. Port `components/BlogAuthorBio.vue`-31. Port `components/BlogInfo.vue`-32. Port `components/NuxtLogo.vue`-33. Port `components/FirebaseAuth.vue`-34. Port `components/MessageThread.vue`-35. Port `components/MessageThreadHeader.vue`--### Phase 6: Pages (use Vuetify MCP for each)-36. Port `pages/index.vue` (homepage)-37. Port `pages/login.vue`-38. Port `pages/threads/index.vue`-39. Port `pages/threads/[id]/index.vue`-40. Port `pages/messages/index.vue`-41. Port `pages/search-messages/index.vue`-42. Port `pages/bulk-messages/index.vue`-43. Port `pages/settings/index.vue`-44. Port `pages/billing/index.vue`-45. Port `pages/heartbeats/[id].vue`-46. Port `pages/phone-api-keys/index.vue`-47. Port `pages/privacy-policy/index.vue`-48. Port `pages/terms-and-conditions/index.vue`-49. Port `pages/blog/index.vue`-50. Port `pages/blog/how-to-send-sms-messages-from-excel.vue`-51. Port `pages/blog/grant-send-and-read-sms-permissions-on-android.vue`-52. Port `pages/blog/forward-incoming-sms-from-phone-to-webhook.vue`-53. Port `pages/blog/end-to-end-encryption-to-sms-messages.vue`-54. Port `pages/blog/send-bulk-sms-from-csv-file-with-no-code.vue`-55. Port `pages/blog/send-sms-from-android-phone-with-python.vue`-56. Port `pages/blog/send-sms-when-new-row-is-added-to-google-sheets-using-zapier.vue`--### Phase 7: Final Setup-57. Port static assets (`public/`)-58. Port environment files (`.env`, `.env.production`)-59. Update Dockerfile and nginx.conf-60. Update sitemap configuration-61. Configure highlight.js (nuxt-highlightjs or manual)--### Phase 8: Verification (EVERY component and page)-62. Verify `app.vue` renders-63. Verify `layouts/default.vue` renders correctly-64. Verify `layouts/website.vue` renders correctly-65. Verify `layouts/error.vue` renders correctly-66. Verify `components/Toast.vue` renders correctly-67. Verify `components/LoadingDashboard.vue` renders correctly-68. Verify `components/LoadingButton.vue` renders correctly-69. Verify `components/BackButton.vue` renders correctly-70. Verify `components/CopyButton.vue` renders correctly-71. Verify `components/FixedHeader.vue` renders correctly-72. Verify `components/BlogAuthorBio.vue` renders correctly-73. Verify `components/BlogInfo.vue` renders correctly-74. Verify `components/NuxtLogo.vue` renders correctly-75. Verify `components/FirebaseAuth.vue` renders correctly-76. Verify `components/MessageThread.vue` renders correctly-77. Verify `components/MessageThreadHeader.vue` renders correctly-78. Verify `pages/index.vue` renders correctly-79. Verify `pages/login.vue` renders correctly-80. Verify `pages/threads/index.vue` renders correctly-81. Verify `pages/threads/[id]/index.vue` renders correctly-82. Verify `pages/messages/index.vue` renders correctly-83. Verify `pages/search-messages/index.vue` renders correctly-84. Verify `pages/bulk-messages/index.vue` renders correctly-85. Verify `pages/settings/index.vue` renders correctly-86. Verify `pages/billing/index.vue` renders correctly-87. Verify `pages/heartbeats/[id].vue` renders correctly-88. Verify `pages/phone-api-keys/index.vue` renders correctly-89. Verify `pages/privacy-policy/index.vue` renders correctly-90. Verify `pages/terms-and-conditions/index.vue` renders correctly-91. Verify `pages/blog/index.vue` renders correctly-92. Verify all blog subpages render correctly-93. Run `pnpm build` (static generation) successfully-94. Verify no TypeScript errors (`pnpm typecheck`)-95. Verify lint passes (`pnpm lint`)--## Verification Strategy--Each verification task in Phase 8 means:-1. Start the dev server (`pnpm dev`)-2. Navigate to the page/route in question-3. Confirm no console errors, no hydration mismatches-4. Confirm visual layout matches intent (Vuetify components render, dark theme active, responsive breakpoints work)-5. For interactive components (forms, modals, auth), confirm basic interactions work--The build verification (`pnpm build`) confirms all pages can be statically generated without errors.--## Risk Mitigations--- **Backup old code**: Keep old `web/` contents in a branch before starting-- **Incremental porting**: Each file is ported and verified before moving to the next-- **Vuetify MCP**: Use for every Vuetify component to catch breaking changes-- **Restored breakpoints**: Keep v2/v3 breakpoint values to minimize layout drift-- **CSS Reset compatibility**: Add selective reset CSS to maintain existing spacing behaviordiff --git a/docs/superpowers/specs/2026-06-24-login-last-used-badge-design.md b/docs/superpowers/specs/2026-06-24-login-last-used-badge-design.mddeleted file mode 100644index f264a926..00000000--- a/docs/superpowers/specs/2026-06-24-login-last-used-badge-design.md+++ /dev/null@@ -1,75 +0,0 @@-# Login "Last Used" Badge — Design--## Problem--The login page (`web/app/pages/login.vue` → `web/app/components/FirebaseAuth.vue`)-offers three authentication methods: Continue with Google, Continue with GitHub,-and Continue with email. Returning users don't get any hint about which method-they used last, so they may pick the wrong provider and end up creating a second-account or failing to sign in.--## Goal--Show a small "Last Used" badge on the button corresponding to the login method-the user most recently used successfully on this device, so they can quickly pick-the right one next time.--## Scope--Single component change: `web/app/components/FirebaseAuth.vue`. No API, store, or-backend changes.--## Approach--### Storage--- Persist the last successful method in `localStorage` under the key- `httpsms_last_login_method`.-- Value is one of `'google' | 'github' | 'email'`.-- The value is written only **after a successful login** (inside `onSuccess`),- never on click/attempt.--### Recording the method--- `onSuccess(user)` is currently shared by all three flows. Extend it to- `onSuccess(user, method)` where `method` is `'google' | 'github' | 'email'`.- - `signInWithGoogle` → `onSuccess(result.user, 'google')`- - `signInWithGithub` → `onSuccess(result.user, 'github')`- - `submitEmail` → `onSuccess(result.user, 'email')`-- Inside `onSuccess`, write the method to `localStorage` before redirecting.--### Reading the method--- A reactive `lastUsedMethod = ref<string | null>(null)`.-- Populated in `onMounted` from `localStorage` (client-only, SSR-safe; the- component is already rendered inside `<ClientOnly>` on the login page).--### Display--- Each of the three method buttons gets `class="position-relative"`.-- A floating `v-chip` is rendered in the top-right corner of the matching button:- - Vuetify `v-chip` with `label`, `size="x-small"`, `color="primary"`.- - `class="position-absolute"` pinned to the top-right corner (slightly- overlapping), text `Last Used`.- - Shown via `v-if="lastUsedMethod === 'google'"` (and `'github'`, `'email'`- respectively).--### Edge cases--- The email button is hidden once the inline email form opens- (`v-if="!showEmailForm"`), so its badge hides with it automatically. No extra- handling needed.-- An unknown/empty stored value shows no badge anywhere.-- `localStorage` access is guarded (wrapped in try/catch or `onMounted` only) so- it never runs during SSR.--## Testing--- Manual verification: sign in with each method, confirm the badge appears on the- correct button on the next visit to the login page.-- Confirm no SSR/hydration errors (badge logic runs client-side only).--## Out of scope--- Syncing the preference across devices.-- Remembering the specific email address used.diff --git a/docs/superpowers/specs/2026-07-05-affiliates-landing-page-design.md b/docs/superpowers/specs/2026-07-05-affiliates-landing-page-design.mddeleted file mode 100644index 31203352..00000000--- a/docs/superpowers/specs/2026-07-05-affiliates-landing-page-design.md+++ /dev/null@@ -1,109 +0,0 @@-# 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.mddeleted file mode 100644index 15ca3de4..00000000--- a/docs/superpowers/specs/2026-07-13-getting-started-page-design.md+++ /dev/null@@ -1,88 +0,0 @@-# 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/docs/superpowers/specs/2026-07-18-message-thread-archive-ui-design.md b/docs/superpowers/specs/2026-07-18-message-thread-archive-ui-design.mddeleted file mode 100644index 6023fdce..00000000--- a/docs/superpowers/specs/2026-07-18-message-thread-archive-ui-design.md+++ /dev/null@@ -1,37 +0,0 @@-# Message Thread Archive UI Design--## Goal--Improve message-thread selection styling and keep archive actions within the-current thread-list filter.--## Active Thread Styling--Add `color="primary"` to every thread `v-list-item` in-`web/app/components/MessageThread.vue`. Vuetify will apply the primary color-when the route-backed item is active without changing inactive items.--## Archive and Unarchive Behavior--`useThreadsStore.updateThread` will continue to send the existing-`PUT /v1/message-threads/:id` request. After a successful response, it will:--1. Preserve the current `archivedThreads` filter.-2. Remove the moved thread from the currently displayed thread collection.-3. Clear the selected thread ID.-4. Show a success notification containing `Archived` or `Unarchived`.--The thread page will route to `/threads` after the store update succeeds.-Archiving therefore returns to the unarchived list, while unarchiving returns-to the archived list. Neither action switches the list filter.--## Error Handling--API errors will continue to propagate from `apiFetch`. Local thread state,-notifications, and navigation will only change after a successful response.--## Validation--The web package has no configured automated tests. Validate the changed files-with the existing lint commands and run the existing static generation command-to confirm the production frontend builds successfully.diff --git a/docs/superpowers/specs/2026-07-18-read-receipts-design.md b/docs/superpowers/specs/2026-07-18-read-receipts-design.mddeleted file mode 100644index 6462cbaa..00000000--- a/docs/superpowers/specs/2026-07-18-read-receipts-design.md+++ /dev/null@@ -1,286 +0,0 @@-# Message Thread Read Receipts--- Date: 2026-07-18-- Status: Approved (design)-- Scope: `api/` Go backend and `web/` Nuxt frontend. Android is unchanged.-- Branch: `feat/read-receipts`, based on `origin/main`--## Problem--The message-thread list does not distinguish conversations with unseen inbound-activity from conversations the user has already opened. Users need unread-threads to stand out and become read automatically when opened.--The change must be backward compatible: every thread that exists when the new-schema is deployed starts as read.--## Decisions--- Unread state is stored per message thread.-- Existing threads are read after migration.-- A new incoming SMS or missed call marks its thread unread.-- Outbound messages and later delivery/status updates do not change read state.-- Opening a thread in the web UI marks it read automatically.-- A thread that receives inbound activity while already open remains read.-- There is no manual "Mark as read/unread" UI.-- Unread threads use bold contact/preview text and a subtle primary-tinted- background.-- The existing `PUT /v1/message-threads/{messageThreadID}` endpoint handles the- read update; no new endpoint is added.--## Design--### 1. Thread persistence--Add these fields to `api/pkg/entities/message_thread.go`:--```go-IsRead bool `json:"is_read" gorm:"not null;default:true" example:"true"`-LastReadAt time.Time `json:"-" gorm:"not null;default:CURRENT_TIMESTAMP"`-```--`IsRead` is the public binary state used by API clients and the web UI.-`LastReadAt` is internal ordering metadata used to make concurrent event-processing deterministic.--GORM `AutoMigrate` adds both columns. The database defaults make all existing-rows read and give them a migration-time read watermark. New-thread creation-sets `IsRead` explicitly according to whether the triggering activity is-inbound.--Existing-row updates must not use the repository's current full-row `Save`-method. A stale entity loaded by one event handler could otherwise overwrite a-newer read action from the web request.--### 2. Atomic repository updates--Add field-scoped repository operations for the two update paths:--- **Message activity update:** update only `order_timestamp`,- `last_message_id`, `last_message_content`, and `status`. For inbound activity,- conditionally set `is_read = false` only where the stored `last_read_at` is- older than the CloudEvent creation time.-- **User status update:** update only the supplied `is_archived` and `is_read`- fields. Marking read writes `is_read = true` and `last_read_at = now` in the- same database update.--The message activity update runs its metadata and conditional unread statements-inside one GORM transaction. Both operations remain scoped by `user_id` and-thread ID and use GORM's query builder with context propagation.--After a user status update, reload the thread for the API response. Do not use-`Save` in either path, because it writes unrelated columns and reintroduces lost-updates.--The stored timestamp condition prevents this race:--1. An inbound event is created.-2. The websocket listener notifies the open web page.-3. The web page marks the thread read.-4. The message-thread listener finishes later.--Because CloudEvent creation time precedes the read request, the late listener-checks the newer database watermark and does not overwrite the read action. If-the message listener commits first, the later read update wins normally.--### 3. Thread update parameters--Extend `services.MessageThreadUpdateParams` with:--```go-MarksUnread bool-EventTimestamp time.Time-```--Inbound SMS and missed-call listeners set `MarksUnread = true` and use-`event.Time()` as `EventTimestamp`. Other message events leave `MarksUnread`-false, so sending, scheduling, delivery, failure, and expiry updates preserve-the current read state.--For an existing thread, the service delegates the field-scoped message update-and optional conditional unread transition to the repository.--For a newly created thread:--- inbound SMS or missed call: `IsRead = false`;-- outbound activity: `IsRead = true`.--### 4. Missed-call thread updates--`MessageThreadListener` currently handles received SMS events but not-`message.call.missed`. Register the missed-call event and update/create the-corresponding thread with:--- owner and contact from `MessageCallMissedPayload`;-- message ID and event timestamp;-- received status;-- a concise preview such as `Missed phone call`;-- `MarksUnread = true`.--This ensures a missed call is visible as thread activity even when no auto-reply-is configured.--### 5. Existing update endpoint--Change `requests.MessageThreadUpdate` to use optional fields:--```go-IsArchived *bool `json:"is_archived,omitempty" example:"true"`-IsRead *bool `json:"is_read,omitempty" example:"true"`-```--The validator requires at least one supported field. Pointer fields distinguish-"not supplied" from `false`, preventing a read-only update from unarchiving a-thread and an archive-only update from changing read state.--`MessageThreadStatusParams` receives the optional fields. `UpdateStatus`:--- loads the authenticated user's thread;-- builds an update map containing only supplied fields;-- writes `last_read_at = time.Now().UTC()` alongside `is_read = true`;-- supports `IsRead = false` at the API level without adding a web control;-- persists one combined partial update and reloads the updated thread.--The handler preserves repository error codes so a missing thread returns 404.-Invalid IDs or empty/unsupported update bodies return validation errors.--### 6. Web store behavior--Regenerate the API model so `EntitiesMessageThread` includes `is_read` and-`RequestsMessageThreadUpdate` has optional `is_archived` and `is_read`.--In `web/app/stores/threads.ts`:--- keep archive updates on the existing endpoint with- `{ is_archived: value }`;-- add `markThreadRead(threadId)` using `{ is_read: true }`;-- replace the matching thread in local state with the successful API response;-- make the operation idempotent and skip the request when the local thread is- already read unless it is called after an inbound realtime event.--Opening a thread invokes `markThreadRead` automatically as part of the thread-loading flow. Message fetching remains independent: if the read update fails,-messages still display, the thread remains/reloads as unread, and the existing-notification system reports the failure.--### 7. Realtime behavior--The message detail page already reloads messages for incoming SMS websocket-events. That reload also marks the currently selected thread read.--Add `message.call.missed` to:--- `WebsocketListener` registrations in the API;-- the Pusher bindings on the thread detail page.--The websocket payload can remain the event ID. The selected thread is marked-read idempotently after any inbound realtime refresh; a different thread's-backend state remains unread.--### 8. Thread-list presentation--In `web/app/components/MessageThread.vue`, unread list items receive:--- bold contact title;-- bold message preview;-- a subtle background using the Vuetify primary theme color at low opacity.--Read threads retain the current appearance. Active-route styling remains-visible and takes precedence where Vuetify applies it.--The highlight is applied in the shared thread-list component, so it works in-both the mobile thread page and desktop navigation drawer, including archived-threads.--### 9. Swagger and generated types--After changing the entity and request annotations:--1. Run `swag init --requiredByDefault --parseDependency --parseInternal` in- `api/`.-2. Run `pnpm api:models` in `web/`.--Generated Swagger files and `web/shared/types/api.ts` are committed with the-implementation.--## Error Handling--- Repository and service errors continue to use `stacktrace.Propagate`.-- The update handler returns 404 for a thread that does not belong to the- authenticated user.-- A failed automatic read update is not swallowed and does not block message- display.-- Local UI state changes only from a successful response or a subsequent thread- reload; the UI does not claim a persisted read state after an API failure.-- Realtime callbacks report failures through the existing notification/error- path rather than using empty catches.--## Testing--### API--Add targeted tests for:--- entity schema defaults and new-thread read-state initialization;-- an inbound SMS making an existing thread unread;-- a missed call creating or updating an unread thread;-- outbound and delivery/status events preserving read state;-- a read action winning when its timestamp is newer than an inbound event;-- concurrent message/read updates changing only their owned columns;-- archive-only updates preserving read state;-- read-only updates preserving archive state;-- missing threads preserving the not-found error code;-- existing-row migration defaults (`is_read = true`).--Run:--```bash-cd api-go test ./...-```--### Web--No frontend unit-test runner is configured. Validate the generated types,-Pinia/Vue changes, styles, and production output with:--```bash-cd web-pnpm lint-pnpm run generate-```--### Integration--Add `tests/read_receipts_test.go` to exercise the feature against the Docker-integration stack:--- an inbound SMS creates or updates an unread thread;-- marking the thread read through the existing update endpoint persists;-- a missed call makes the thread unread again;-- subsequent outbound activity does not clear that unread state.--Update `tests/README.md` coverage and run:--```bash-cd tests-go test -v -timeout 120s -run TestMessageThreadReadReceipts ./...-```--Manual acceptance checks:--1. Existing threads appear read immediately after migration.-2. A new incoming SMS highlights its closed thread.-3. A missed call highlights its closed thread.-4. Opening an unread thread removes the highlight and persists across refresh.-5. Incoming activity in the currently open thread does not leave it unread.-6. Sending or receiving delivery updates does not clear another unread state.-7. Archiving/unarchiving does not change read state.--## Out of Scope--- Per-message read receipts.-- Android read/unread UI.-- Unread counts or badges outside the thread list.-- Manual read/unread controls.-- Cross-user/group-conversation receipt tracking.diff --git a/docs/superpowers/specs/2026-07-18-unarchive-thread-on-receive-design.md b/docs/superpowers/specs/2026-07-18-unarchive-thread-on-receive-design.mddeleted file mode 100644index 94849004..00000000--- a/docs/superpowers/specs/2026-07-18-unarchive-thread-on-receive-design.md+++ /dev/null@@ -1,118 +0,0 @@-# Auto-unarchive Message Threads on Inbound Message (per-phone)--- Date: 2026-07-18-- Status: Approved (design)-- Scope: `api/` (Go backend) and `web/` (Nuxt frontend). Android app not touched.--## Problem--When a message thread is archived it stays archived even if the contact sends a-new inbound message. Users want an archived thread to move back to the-unarchived (inbox) state when a new message is received. This behaviour must be-configurable.--## Decisions--- **Granularity:** configurable per **phone number** (per `Phone`), consistent- with other per-phone settings such as `MessagesPerMinute` and- `MissedCallAutoReply`.-- **Trigger:** only **inbound** messages received from the contact- (`entities.MessageStatusReceived`). Outbound activity (sent/sending/delivered/- scheduled/expired) does not unarchive a thread.-- **Default:** **disabled** (opt-in). Existing and new phones default to `false`.-- **Field name:** `UnarchiveThread` (JSON `unarchive_thread`).-- **Data flow:** the flag travels on the received-message event payload- (Option B), so `MessageThreadService` gains **no** new repository dependency.--## Design--### 1. Data model — `api/pkg/entities/phone.go`--Add a boolean to the `Phone` entity:--```go-UnarchiveThread bool `json:"unarchive_thread" gorm:"default:false" example:"false"`-```--GORM auto-migrates the column. Existing rows default to `false`.--### 2. Event payload — `api/pkg/events/message_phone_received_event.go`--Add the flag to `MessagePhoneReceivedPayload`:--```go-UnarchiveThread bool `json:"unarchive_thread"`-```--### 3. Populate the flag — `api/pkg/services/message_service.go`--In `ReceiveMessage`, before building `eventPayload`, load the owner phone using-the already-injected `phoneService` (same pattern as `RespondToMissedCall`,-which calls `service.phoneService.Load(ctx, payload.UserID, payload.Owner)`) and-copy `phone.UnarchiveThread` onto the payload.--- The owner E.164 string is `phonenumbers.Format(¶ms.Owner, phonenumbers.E164)`.-- If the phone lookup fails, log and default `UnarchiveThread` to `false`; do not- fail message reception because of a missing/failed phone lookup.--### 4. Thread service trigger — `api/pkg/services/message_thread_service.go`--- Add `UnarchiveThread bool` to `MessageThreadUpdateParams`.-- In `UpdateThread`, after the thread is loaded, if the thread `IsArchived` is- true **and** `params.Status == entities.MessageStatusReceived` **and**- `params.UnarchiveThread` is true, set the thread's `IsArchived = false` as part- of the same update that persists the new last message. Reuse- `thread.UpdateArchive(false)` or set the field directly before- `repository.Update`.-- The existing early-return guards (out-of-order timestamp, already-delivered)- must not skip the unarchive when a genuinely new inbound message arrives; the- unarchive is applied on the same path as the normal thread update.--### 5. Listener — `api/pkg/listeners/message_thread_listener.go`--In `OnMessagePhoneReceived`, set `UnarchiveThread: payload.UnarchiveThread` on-the `MessageThreadUpdateParams`. No other listener passes this flag (only inbound-received messages should unarchive).--### 6. Request/params — phone upsert--- `api/pkg/requests/phone_update_request.go`: add `UnarchiveThread *bool`- (pointer, applied only when present in the JSON body — same partial-update- pattern as `MessagesPerMinute`, using the `fields` map check on key- `unarchive_thread`).-- `api/pkg/services/phone_service.go` `PhoneUpsertParams`: add- `UnarchiveThread *bool` and apply it in the upsert when non-nil.--### 7. Web frontend — `web/`--- `web/app/stores/phones.ts` `updatePhone`: include- `unarchive_thread: phone.unarchive_thread` in the PUT body.-- `web/app/pages/settings/index.vue`: add a toggle (switch/checkbox) for the- per-phone "Unarchive thread when a new message is received" setting, alongside- the existing per-phone settings.-- Regenerate TypeScript API models with `pnpm api:models` after the Swagger spec- is regenerated so `EntitiesPhone` in `web/shared/types/api.ts` includes- `unarchive_thread`.--### 8. Swagger--Run `swag init --requiredByDefault --parseDependency --parseInternal` in `api/`-after adding the annotation-affecting struct field so the generated docs and the-web model regeneration stay in sync.--## Testing--- **API unit test** (`message_thread_service` test): archived thread + inbound- received message + `UnarchiveThread=true` -> thread becomes unarchived;- `UnarchiveThread=false` -> stays archived; outbound status with the flag true- -> stays archived.-- **API**: `MessageService.ReceiveMessage` populates `UnarchiveThread` from the- loaded phone; a failed phone lookup yields `false` and does not error.-- Run `go test ./...` in `api/`.-- **Web**: `pnpm lint` and `pnpm test` in `web/`.--## Out of scope--- Android app settings UI.-- Global (user-level) or per-thread configuration.-- Auto-archiving behaviour (this design only unarchives).diff --git a/docs/superpowers/specs/2026-07-18-webhook-email-payload-formatting-design.md b/docs/superpowers/specs/2026-07-18-webhook-email-payload-formatting-design.mddeleted file mode 100644index 56e2e7e8..00000000--- a/docs/superpowers/specs/2026-07-18-webhook-email-payload-formatting-design.md+++ /dev/null@@ -1,116 +0,0 @@-# Webhook Email Payload Formatting--- Date: 2026-07-18-- Status: Approved (design)-- Scope: `api/` email rendering only.--## Problem--Failed-webhook notification emails currently display the event payload as an-unformatted dictionary value. Nested JSON is difficult to scan, and multiline-payloads lose the visual structure users need when diagnosing webhook failures.--## Decisions--- Format only the webhook email's **Event Payload** value.-- Leave SMS content, failure reasons, HTTP responses, and every other email- field unchanged.-- Pretty-print valid JSON with indentation.-- Render valid JSON in the HTML email with lightweight colors for keys, strings,- numbers, booleans, and `null`.-- Render non-JSON payloads in the same monospace block while preserving their- original whitespace, without syntax colors.-- Use only the Go standard library and the existing Hermes email integration.-- Keep the plain-text email readable with indentation but no HTML styling.--## Design--### 1. Payload formatter--Add a focused formatter under `api/pkg/emails` that accepts the event payload-string and returns:--- a plain-text value for `hermes.Entry.Value`; and-- safely escaped highlighted markup for `hermes.Entry.UnsafeValue`.--For valid JSON, use the Go standard library to produce deterministic-indentation. A small JSON-aware tokenizer will wrap keys, strings, numbers,-booleans, and `null` in spans with inline colors. Inline styles are preferred-because many email clients strip style blocks or external styles.--All payload tokens must be HTML-escaped before they are inserted into the-trusted template value. Payload content must never be interpreted as HTML.--For invalid JSON, return the original payload unchanged as the plain-text value-and HTML-escape it into an unhighlighted code block. Invalid JSON is an expected-fallback and must not prevent email generation or delivery.--### 2. Hermes dictionary rendering--Update the custom HTML template in `api/pkg/emails/hermes_theme.go` so dictionary-entries render `UnsafeValue` when it is present and otherwise retain the current-escaped `Value` rendering.--The payload block will use email-compatible markup and inline styles:--- a neutral light background and subtle border;-- padding and a monospace font;-- `white-space: pre-wrap` to preserve indentation and line breaks; and-- safe wrapping for long values so the email remains usable on narrow clients.--The plain-text template continues to render `Entry.Value`, so it contains-readable indented JSON without HTML tags or colors.--### 3. Webhook email factory--In `hermesNotificationEmailFactory.WebhookSendFailed`, pass-`payload.EventPayload` through the formatter. Set both `Value` and-`UnsafeValue` only on the existing `Event Payload` dictionary entry.--No other dictionary entry or notification email uses the new unsafe rendering-path. The order, subject, explanatory text, action button, and delivery behavior-of the webhook failure email remain unchanged.--## Data Flow--1. `WebhookSendFailed` receives `payload.EventPayload`.-2. The formatter checks whether the string is valid JSON.-3. Valid JSON is indented and highlighted; invalid JSON preserves its original- text and receives code-block styling only.-4. Hermes uses the plain value for the text email and the escaped styled value- for the HTML email.-5. The existing mailer sends both representations without service or listener- changes.--## Error Handling and Security--- Invalid JSON falls back to a whitespace-preserving code block.-- Formatting does not introduce a new email-generation failure path.-- Payload markup, quotes, ampersands, and other special characters are escaped- before insertion.-- Highlighting is generated server-side and requires no JavaScript, remote- assets, or external CSS.-- Existing Hermes generation errors continue to use the current stacktrace- propagation behavior.--## Testing--Add targeted tests under `api/pkg/emails` covering:--- nested valid JSON is consistently indented;-- keys, strings, numbers, booleans, and `null` receive the expected HTML spans;-- payload HTML is escaped and cannot inject markup;-- invalid JSON preserves whitespace and is not syntax-highlighted;-- the webhook email HTML renders only `Event Payload` as a code block;-- the webhook email plain text contains readable indented JSON; and-- existing non-payload dictionary entries keep their current rendering.--Run the targeted email package tests, then `go test ./...` in `api/`.--## Out of Scope--- Formatting SMS message content or failure reasons.-- Formatting HTTP response bodies or error messages.-- Highlighting non-JSON languages.-- Adding a third-party syntax-highlighting dependency.-- Changing webhook retries, event payload generation, or email delivery logic.diff --git a/docs/superpowers/specs/2026-07-19-contacts-feature-design.md b/docs/superpowers/specs/2026-07-19-contacts-feature-design.mddeleted file mode 100644index 58f9d9e4..00000000--- a/docs/superpowers/specs/2026-07-19-contacts-feature-design.md+++ /dev/null@@ -1,252 +0,0 @@-# Contacts Feature — Design--Date: 2026-07-19-Status: Approved (pending implementation plan)--## 1. Summary--Add a **Contacts** feature to httpSMS. Users can store contacts (name, emails,-phone numbers, and free-form properties) and manage them through a dedicated web-page and a REST API. Once contacts exist, the threads page displays the-contact's **name** instead of the raw phone number.--Design priority (explicit user goal): resolve contact names into the threads-page with **as few database queries as possible**, and make **changing a-contact's name cheap** (no write amplification across threads).--## 2. Goals--- CRUD for contacts via a REST API under `/v1/contacts`.-- A single create endpoint that accepts **one or many** contacts in one request.-- Import contacts from **CSV** (Excel/XLSX is **not** supported for contacts).-- A contact has: `Name` (required), `Emails` (optional array), `PhoneNumbers`- (array, >= 1), and free-form `Properties` (`map[string]string`).-- Contacts are **global to the user account** (name shows across all the user's- owner phones).-- Threads display the resolved contact name (and expose full contact details)- when requested, everywhere the peer number is shown (threads list + thread- header/title).-- Dedicated Contacts web page with full CRUD + import.--## 3. Non-goals / Explicit decisions--- **No uniqueness constraint** on phone numbers. Multiple contacts may share a- phone number. There is **no** normalized `contact_phone_numbers` lookup table- and **no** DB-level unique index on numbers.-- When a thread's number matches **multiple** contacts, the **most recently- updated** contact wins for display.-- Thread-name resolution is **opt-in** per request (default off).-- `Properties` are API/JSON only; not part of the flat CSV template.--## 4. Data model--### 4.1 `Contact` entity (`api/pkg/entities/contact.go`)--| Field | Type | GORM / notes |-| -------------- | ------------------- | --------------------------------------------- |-| `ID` | `uuid.UUID` | `primaryKey;type:uuid` |-| `UserID` | `entities.UserID` | indexed |-| `Name` | `string` | required |-| `Emails` | `pq.StringArray` | `gorm:"type:text[]"` `swaggertype:"array,string"`; optional, each validated |-| `PhoneNumbers` | `pq.StringArray` | `gorm:"type:text[]"` `swaggertype:"array,string"`; >= 1, each valid E.164 |-| `Properties` | `ContactProperties` | `gorm:"type:jsonb"`; free-form key/value map |-| `CreatedAt` | `time.Time` | |-| `UpdatedAt` | `time.Time` | |--Follows the existing `pq.StringArray` convention used in `webhook.go` and-`phone_api_key.go`. Auto-migrated in `pkg/di/container.go` alongside the other-entities.--### 4.2 `ContactProperties` custom type--A small custom type to avoid adding a new dependency (`gorm.io/datatypes` is not-currently used):--```go-// ContactProperties is a free-form key/value map persisted as a jsonb column.-type ContactProperties map[string]string--func (p ContactProperties) Value() (driver.Value, error) // json.Marshal -> []byte-func (p *ContactProperties) Scan(src any) error // json.Unmarshal from []byte/string-```--Includes unit tests for `Value`/`Scan` round-trips (nil, empty, populated).--### 4.3 `MessageThread` additions (`api/pkg/entities/message_thread.go`)--Add a **non-persisted** field carrying the resolved contact:--```go-ContactDetails *Contact `json:"contact_details,omitempty" gorm:"-"`-```--- `gorm:"-"` — never read/written to the DB.-- `omitempty` — absent from responses unless resolution attached it.-- Named `ContactDetails` (JSON `contact_details`) to avoid colliding with the- existing `Contact string json:"contact"` field, which holds the peer phone- number.--## 5. API--New `ContactHandler` mirroring existing handler/service/repository/validator-layering. Routes registered via the `handler.register(...)` helper (Fiber v3),-wired in the DI container. All routes are under `/v1/` and behind the standard-auth middleware chain.--| Method | Route | Purpose |-| -------- | ------------------------ | ------------------------------------------------------------- |-| `GET` | `/v1/contacts` | List (paginated; `?query=` searches name / email / number) |-| `POST` | `/v1/contacts` | Create **one or many** — body is a JSON array of contacts |-| `POST` | `/v1/contacts/upload` | Import from CSV (`document` multipart form field; CSV only) |-| `PUT` | `/v1/contacts/:contactID`| Update name / emails / phone numbers / properties |-| `DELETE` | `/v1/contacts/:contactID`| Delete a contact |--### 5.1 Create (one or many)--Request body (array form or `{ "contacts": [...] }`):--```json-{- "contacts": [- {- "name": "Alice Smith",- "emails": ["[email protected]"],- "phone_numbers": ["+18005550199", "+18005550100"],- "properties": { "company": "Acme", "role": "CTO" }- }- ]-}-```--- Per-item validation with row-indexed error messages (mirroring bulk-message- validation style using `url.Values`).-- Batch capped at <= 1000 contacts.-- Cache invalidated **once** after the batch commits.--### 5.2 CSV import (CSV only)--- Reuses the bulk-message CSV parsing pattern (`csvutil`; <= 500 KB; <= 1000- rows). **Excel/XLSX is not supported** — only `text/csv` / `.csv` is accepted;- any other file type returns a validation error.-- Columns: `Name, Emails, PhoneNumbers`. `Emails` and `PhoneNumbers` cells hold- multiple values separated by `;` (or `,`). `Properties` is not part of the- flat template.-- Published template: `httpsms-contacts.csv` (same location/convention as the- bulk-message template).--### 5.3 Validation rules--- `Name` required and non-empty per contact.-- Each phone number must parse as E.164 (`nyaruka/phonenumbers`); >= 1 required.-- Each email (if present) must be a valid email.-- `properties` keys/values are free-form strings.--## 6. Thread name resolution + caching--### 6.1 Contact map cache--- A per-user map `phone_number -> *Contact` is built from **all** the user's- contacts. On phone-number collisions, the **most recently updated** contact- wins (sort by `UpdatedAt` ascending while building so later writes overwrite).-- Serialized as JSON in `cache.Cache` under key `contacts.map.<userID>`,- TTL ~24h.-- `cache.Cache` exposes only `Get`/`Set` (no delete), so **invalidation =- overwrite** the key with an empty marker after any contact mutation; the next- request that needs it lazily rebuilds from the DB.--### 6.2 `GetThreads` flow--1. Load threads (existing single query, unchanged).-2. **If** the request's `Contacts` flag is true: fetch the user's contact map- (cache hit → 0 DB queries; miss → one query to rebuild), then attach- `ContactDetails` to each thread in memory by looking up `thread.contact`.-3. If the flag is false/absent: skip resolution entirely (no cache/DB work);- behavior identical to today.--Cost profile:--- Threads read: **1 DB query** (unchanged).-- Contact resolution: usually a **cache hit → 0 DB queries**; DB touched only on- cache miss or right after a contact write.-- Contact **name change**: single-row `UPDATE` + cache invalidation.- **Zero thread writes / zero propagation.**--### 6.3 Opt-in filter--- `GET /v1/message-threads` gains an optional query param `?contacts=true`- bound onto `requests.MessageThreadIndex` (`Contacts bool`, default `false`).-- Threaded through `MessageThreadGetParams` to the service, controlling whether- step 2 above runs.--## 7. Frontend (Nuxt 4 / Pinia)--- **`useContactsStore`** (`web/app/stores/contacts.ts`): `loadContacts`,- `saveContacts` (array), `updateContact`, `deleteContact`, `uploadCsv`.-- **Contacts page** (`web/app/pages/contacts/index.vue`) — layout modeled on the- provided reference (Plunk-style):- - **Header row**: large `Contacts` title (`text-display-large`, no glowing- gradient) with a subtitle like `Manage your contacts. {total} total`, and,- aligned top-right, an outlined **Import CSV** button and a filled primary- **Add Contact** button.- - **Search bar** below the header filtering by name / email / phone number- (drives the `?query=` API param, debounced).- - **Data table** (`VDataTable`) with columns: `Name`, `Phone Numbers`,- `Emails`, `Created`, `Updated`, and a right-aligned **Actions** column with- per-row **edit** (pencil, `mdiPencil`) and **delete** (trash,- `mdiDelete`) icon buttons.- - Timestamps rendered relatively (e.g. "31 minutes ago") via `useFilters()`.- - Pagination for large lists.- - **Modals** (all `VDialog` with `opacity="0.9"`, Close button- `color="warning"`):- - **Add / Edit Contact** dialog — form for `Name`, repeatable- `PhoneNumbers`, repeatable `Emails`, and free-form `Properties`- (key/value rows). Same dialog component for create and edit.- - **Delete Contact** confirmation dialog.- - **Import CSV** dialog — file input accepting `.csv` only, a link to the- `httpsms-contacts.csv` template, and inline row-indexed error display.- - Hyperlinks use `text-decoration-none hover:text-decoration-underline`.-- **Threads UI**:- - `threads` store `loadThreads` passes `contacts: true`.- - `MessageThread.vue` title and `MessageThreadHeader.vue` render- `thread.contact_details?.name ?? formatPhoneNumber(thread.contact)`; the- avatar uses the resolved name's first letter when present.- - Filter helpers pulled from `useFilters()` in `<script setup>` and used- directly in the template.-- **Types**: regenerate `shared/types/api` from Swagger (`pnpm api:models`)- after the API annotations land — provides `EntitiesContact` and- `contact_details` on `EntitiesMessageThread`.-- **Navigation**: add a Contacts link in the default layout.--## 8. Testing--### API (Go) — run with `go test -vet=off ./...`--- `ContactProperties` `Value`/`Scan` round-trip tests.-- Contact repository: create (one/many), update, delete, list + search,- contact-map build with most-recently-updated tie-break.-- Validator: name required, E.164 numbers, email format, batch cap, CSV- parsing (valid + malformed); non-CSV upload rejected.-- Handler tests mirroring `message_thread_handler_test.go`.-- Resolution: threads get `ContactDetails` attached only when `contacts=true`;- cache-hit path performs no DB query; tie-break correctness; unaffected when- the flag is off.--### Web--- Store unit tests for contacts CRUD/import.-- Thread rendering falls back to formatted number when no contact is resolved.--## 9. Rollout / migration--- `Contact` auto-migrated by GORM (new table). No backfill required — resolution- is computed at read time, so existing threads immediately benefit once- contacts are created. No changes to existing thread rows.--## 10. Efficiency summary (why this design)--- Threads list stays **one query**.-- Contact names are resolved from an in-memory per-user **cache**, so the common- path adds **zero** DB queries.-- Because the name lives only on the contact row, a **name change is a single- `UPDATE`** plus a cache invalidation — no fan-out writes across threads.-- Resolution is **opt-in**, so callers that don't need names pay nothing.diff --git a/docs/superpowers/specs/2026-07-19-email-number-formatting-design.md b/docs/superpowers/specs/2026-07-19-email-number-formatting-design.mddeleted file mode 100644index 6e715b1d..00000000--- a/docs/superpowers/specs/2026-07-19-email-number-formatting-design.md+++ /dev/null@@ -1,30 +0,0 @@-# Email Number Formatting Design--## Goal--Format integer quantities in generated emails with comma thousands separators. For example, `20000` becomes `20,000`.--## Scope--Apply formatting to message counts and subscription limits in usage-limit emails:--- sent messages-- received messages-- total messages-- plan message limits--Do not change dates, percentages, HTTP status codes, phone numbers, years, or numeric event payload values.--## Design--Add a private integer-formatting helper to the shared email `factory`. The helper will produce deterministic comma-grouped decimal output without adding a dependency.--Use the helper in `hermes_user_email_factory.go` anywhere a message count or subscription limit is rendered. Because Hermes generates both HTML and plain text from the same content model, both email formats will receive identical formatting.--## Error Handling--Formatting is a pure operation and introduces no new error path. Existing email generation errors continue to propagate unchanged.--## Testing--Add focused tests for integer grouping, including values below and above one thousand. Update usage-limit email tests to assert formatted quantities in both generated plain text and HTML.diff --git a/docs/superpowers/specs/2026-07-23-signup-name-design.md b/docs/superpowers/specs/2026-07-23-signup-name-design.mddeleted file mode 100644index 5e3e8aa0..00000000--- a/docs/superpowers/specs/2026-07-23-signup-name-design.md+++ /dev/null@@ -1,33 +0,0 @@-# Signup Name Design--## Goal--Collect a required name during Firebase email/password signup and persist it as-the Firebase user's display name.--## User Interface--- Show a `Name` field only when the email form is in signup mode.-- Keep the existing email and password fields unchanged.-- Clear field-level and general errors whenever the user switches between sign- in and sign up.--## Signup Flow--1. Validate name, email, and password.-2. Create the Firebase email/password user.-3. Set the new user's Firebase profile `displayName` to the trimmed name.-4. Update the auth store and continue through the existing success redirect.--## Error Handling--- An empty name produces an inline error on the `Name` field.-- Firebase account creation and profile update errors use the existing Firebase- error handling path.-- Switching form modes removes stale errors before rendering the other mode.--## Validation--- Add or update focused component tests if the component has an existing test- harness.-- Run the web lint command and the smallest relevant web test command.diff --git a/docs/superpowers/specs/2026-08-21-contact-phone-input-design.md b/docs/superpowers/specs/2026-08-21-contact-phone-input-design.mddeleted file mode 100644index 2bca6d00..00000000--- a/docs/superpowers/specs/2026-08-21-contact-phone-input-design.md+++ /dev/null@@ -1,29 +0,0 @@-# Contact Phone Input Design--## Goal--Use the existing `v-phone-input` component for phone numbers in the contact-add/edit dialog.--## Design--Represent each form phone row with a phone number value and its own country.-Bind those fields to `v-phone-input` using `v-model` and `v-model:country`,-following the messages page configuration.--Existing E.164 phone numbers derive their country with `libphonenumber-js`.-Numbers without a detectable country and newly added rows default to `US`.-Removing a row removes both its number and country because they are stored in-one object.--## Behavior--- Keep support for multiple phone numbers.-- Preserve current required-phone validation and server error display.-- Submit only trimmed, non-empty phone number values to the API.-- Keep add, edit, and remove behavior unchanged apart from the country-aware- input.--## Validation--Run ESLint, Stylelint, and Prettier against the changed contact page.diff --git a/docs/superpowers/specs/2026-08-21-contacts-table-header-design.md b/docs/superpowers/specs/2026-08-21-contacts-table-header-design.mddeleted file mode 100644index afa59dfd..00000000--- a/docs/superpowers/specs/2026-08-21-contacts-table-header-design.md+++ /dev/null@@ -1,29 +0,0 @@-# Contacts Table Header Styling Design--## Goal--Make every header in the contacts data table uppercase and grey using Vuetify's-standard text utility classes.--## Design--Add the `headers` slot to the existing `VDataTableServer` in-`web/app/pages/contacts/index.vue`. Render each header title with-`text-uppercase text-medium-emphasis` while retaining Vuetify's existing header-layout and per-column alignment.--This approach keeps presentation in the template, avoids brittle selectors-against Vuetify internals, and leaves the header definitions and table data flow-unchanged.--## Scope--- Apply the styling to Name, Phone Numbers, Emails, Created, Updated, and- Actions.-- Preserve the existing data, pagination, loading, and item slot behavior.-- Do not introduce component-level CSS or change the displayed header labels.--## Validation--Run the existing web lint command and confirm the contacts page template passes-Vue and TypeScript validation.diff --git a/docs/superpowers/specs/2026-09-02-url-backed-phone-notification-adapter-design.md b/docs/superpowers/specs/2026-09-02-url-backed-phone-notification-adapter-design.mddeleted file mode 100644index 5d833dfb..00000000--- a/docs/superpowers/specs/2026-09-02-url-backed-phone-notification-adapter-design.md+++ /dev/null@@ -1,514 +0,0 @@-# URL-backed Phone Notification Adapter--- Date: 2026-09-02-- Status: Approved (design)-- Scope: `api/` Go backend plus `tests/` integration infrastructure and API CI.- Web and Android clients are unchanged.--## Problem--httpSMS currently wakes an Android phone through Firebase Cloud Messaging when-an outgoing message is ready. The phone then fetches the outstanding message,-sends it, and reports sent, delivered, or failed events through the phone API.--Users should be able to register a non-Android gateway, such as a WhatsApp-adapter, as a phone number. The gateway must reuse the existing message queue,-send schedules, per-phone backpressure, expiration, retry, incoming-message,-and status-event flows. The only behavioral difference is how httpSMS wakes the-gateway: when the stored `fcm_token` is a URL, httpSMS calls that URL instead of-Firebase.--Customer-controlled callback URLs create additional security and delivery-requirements:--- callbacks are wake-up hints, not proof that a message was sent;-- callback delivery is at least once, so adapters must tolerate duplicate- wake-up hints;-- transient endpoint failures need bounded retries;-- existing Android registrations must retain their current behavior.--## Decisions--- Reuse the existing `Phone.FcmToken` database field and `fcm_token` API field.- Do not add transport or callback URL columns.-- Determine transport through helper methods on `Phone`; callers do not inspect- or parse `FcmToken` directly.-- A valid `https://` URL with a hostname selects HTTP delivery. Non-URL tokens- select Firebase. URL-like but malformed or unsupported values are rejected.-- Inject phone notification clients as a map keyed by- `entities.NotificationTransport`; domain events continue to use the existing- `EventDispatcher`.-- Send both outstanding-message and heartbeat notifications to URL-backed- phones.-- POST an FCM-compatible JSON envelope to adapter endpoints.-- Treat any `2xx` response as successful wake-up acceptance and ignore its- body.-- Make up to three total HTTP attempts with `retry-go/v5` and a five-second- timeout per attempt.-- Retry network failures, HTTP `408`, HTTP `429`, and `5xx` responses. Other- non-`2xx` responses fail immediately.-- After callback retries are exhausted, use the current notification failure- path and mark the message failed.-- Do not sign or authenticate callback requests. The payload contains no- message content or API credentials.-- Use a standard OpenTelemetry-wrapped `http.Client` without endpoint DNS/IP- filtering, custom dialing, or a private-host allowlist.-- Preserve all existing phone API-key authorization and message-processing- behavior.--## Existing Flow--The current backend already isolates scheduling from phone wake-up delivery:--1. `MessageService.SendMessage` creates the outgoing message event using the- phone's configured send attempts, SIM, and rate settings.-2. `PhoneNotificationService.Schedule` persists a `PhoneNotification` and uses- `PhoneNotificationRepository.Schedule` or `ScheduleExact` to apply- per-minute limits and send schedules.-3. `message.notification.send` invokes `PhoneNotificationService.Send`.-4. The service sends an FCM data notification containing `KEY_MESSAGE_ID`.-5. A successful notification increments the message send-attempt count and- schedules the existing expiration check.-6. The Android phone fetches- `GET /v1/messages/outstanding?message_id=<id>` using a phone API key scoped- to its number.-7. The phone reports sent, delivered, or failed events and submits inbound- messages through the existing phone API routes.--The adapter feature changes step 4 only. The same dispatcher also applies to-the heartbeat notification currently sent by `SendHeartbeatFCM`.--## Design--### 1. Phone transport helpers--Add helpers to `api/pkg/entities/phone.go` that classify and expose the-notification destination while continuing to store only `FcmToken`.--The helpers provide three outcomes:--- **Firebase:** the token has no URL syntax and is passed unchanged to Firebase.-- **HTTP:** the token is an absolute, syntactically valid `https://` URL.-- **Invalid:** the value is URL-like but malformed, uses another scheme, or has- no hostname.--Use these entity-level types and methods:--```go-type NotificationTransport string--const (- NotificationTransportFCM NotificationTransport = "fcm"- NotificationTransportHTTP NotificationTransport = "http"-)--func (phone *Phone) NotificationTransport() (NotificationTransport, error)-func (phone *Phone) NotificationURL() (*url.URL, error)-```--`NotificationTransport` returns an error for a missing token or a URL-like-invalid token. `NotificationURL` succeeds only for the HTTP transport.-`PhoneNotificationService`, validation, and tests must not duplicate-string-prefix checks.--A token is considered URL-like when it declares a URI scheme. This prevents an-invalid `http://`, `ftp://`, or malformed HTTPS endpoint from falling through-to Firebase as if it were an FCM token. Ordinary FCM tokens remain opaque.--### 2. Transport client map--Use the existing `FCMClient` contract for every phone notification transport:--```go-type FCMClient interface {- Send(context.Context, *messaging.Message) (string, error)-}-```--`PhoneNotificationService` receives-`map[entities.NotificationTransport]FCMClient` and constructs-`messaging.Message` directly. A focused private helper:--1. rejects a nil message with a stacktrace error;-2. determines the phone transport once;-3. looks up the matching client in the map;-4. trims the configured token into `message.Token`;-5. passes the same message pointer to the client;-6. returns the selected transport with the result or error for existing- Firebase-versus-HTTP failure guidance.--The result string is used only by existing notification event bookkeeping.-Firebase keeps the message name returned by the SDK. HTTP delivery uses a-generated identifier that does not expose the callback URL.--### 3. Firebase client--The Firebase map entry is the existing production or emulator `FCMClient`-directly. There is no wrapper sender and no separate dispatcher class.--The production Firebase client and emulator client remain available. Android-tokens follow the same SDK path, payload keys, priorities, TTL values, success-events, and failure events as before.--### 4. HTTP sender and request contract--The HTTP sender posts `Content-Type: application/json` with an FCM-compatible-envelope:--```json-{- "message": {- "token": "https://adapter.example.com/notifications",- "data": {- "KEY_MESSAGE_ID": "32343a19-da5e-4b1b-a767-3298a73703cb"- },- "android": {- "priority": "normal",- "ttl": "600s"- }- }-}-```--Heartbeat notifications use the same shape with:--```json-{- "data": {- "KEY_HEARTBEAT_ID": "2026-09-02T19:22:20Z"- },- "android": {- "priority": "high"- }-}-```--Adapters should depend on `message.data`; the Android object exists for payload-compatibility and communicates priority and expiration hints.--`HTTPNotificationSender` obtains the destination from `message.Token` and-marshals `map[string]any{"message": message}`. Firebase's-`messaging.Message` and `messaging.AndroidConfig.MarshalJSON` own the FCM JSON-shape and protobuf duration formatting, including a ten-minute TTL as `600s`.--Every request includes:--```text-Content-Type: application/json-```--`HTTPNotificationSender` returns the stable result `http/success` after any-successful callback response. The persisted `PhoneNotification.ID` remains in-the existing repository and event flow but is not sent to the callback.--The response contract is deliberately small:--- any `2xx` status means the adapter accepted the wake-up;-- response headers and body do not affect message state;-- the sender reads at most a small bounded amount needed to safely reuse or- close the connection, then discards the body.--The callback is not sent the message content, phone API key, user ID, or-credentials.--### 5. HTTP retry and state semantics--Each HTTP delivery makes no more than three total attempts. Each attempt has a-five-second context timeout and uses short exponential backoff.--Retryable failures are:--- connection, DNS, TLS, and timeout failures;-- HTTP `408 Request Timeout`;-- HTTP `429 Too Many Requests`;-- HTTP `5xx`.--Other non-`2xx` statuses are terminal for that notification and are not-retried. Ignore `Retry-After`; use the sender's bounded exponential backoff so-a customer response cannot extend the listener into an unbounded worker.--When a callback returns `2xx`, `PhoneNotificationService` uses its existing-success path:--1. dispatch `message.notification.sent`;-2. set the `PhoneNotification` status to sent;-3. increment the message send-attempt count;-4. schedule the configured message expiration check.--This means callback success is only proof that the adapter was notified. The-message remains pending/scheduled until the adapter fetches it, at which point-the existing `message.phone.sending` path runs.--When callback delivery reaches a terminal failure or exhausts retries,-`PhoneNotificationService` uses its existing failed-notification path:--1. dispatch `message.notification.failed`;-2. set the `PhoneNotification` status to failed;-3. store a failed message event through the existing message listener.--The HTTP-specific error message tells the user that the configured adapter-endpoint could not be notified. It must not reuse the current Android-reinstallation guidance.--### 6. At-least-once delivery--HTTP wake-up delivery is at least once. A request may reach the adapter even if-httpSMS observes a timeout or connection failure while receiving the response.-The retry can therefore deliver the same wake-up payload again.--Adapters must:--- treat callbacks as hints to fetch work, not as message content;-- tolerate repeated callbacks and use the outstanding message state and- message ID to avoid sending external messages twice;-- retain their own provider-level idempotency and reconciliation where the- external channel supports it.--httpSMS does not add a new acknowledgement endpoint. Fetching the outstanding-message and posting existing message events remain the source of truth.--### 7. Adapter API flow--A URL-backed adapter uses the existing public API in the same way as the-Android gateway:--1. A user creates or updates a phone with an E.164 number and sets `fcm_token`- to the adapter's HTTPS URL.-2. The user creates a phone API key assigned to that phone/number and configures- the adapter with it.-3. httpSMS schedules outgoing messages with the existing rate limit and send- schedule.-4. When a message becomes due, httpSMS POSTs the callback containing- `KEY_MESSAGE_ID`.-5. The adapter fetches the message through `/v1/messages/outstanding` using its- phone API key.-6. The adapter sends the message through WhatsApp or another external channel.-7. The adapter posts the existing sent, delivered, or failed message events.-8. The adapter posts inbound messages through `/v1/messages/receive`.-9. For `KEY_HEARTBEAT_ID`, the adapter performs the same heartbeat callback flow- expected from the Android application.--The phone API key's existing phone-number scope prevents an adapter from-fetching messages belonging to another number. The adapter must not use a-general user API key for gateway operations.--Encrypted message content remains unchanged. If a user enables encryption, the-adapter is responsible for implementing the same compatible encryption and-decryption behavior expected of the Android gateway.--### 8. HTTP client and retry ownership--Phone registration validates only URL syntax, the HTTPS scheme, and the-presence of a hostname. URL user information remains valid. The feature does-not perform endpoint DNS/IP classification, custom dialing, or private-host-allowlisting.--`Container.NotificationHTTPClient` is a standard `http.Client` using the-existing webhook-style `go-otelroundtripper` pattern without transport-level-retries or custom URL redaction. The client preserves Go's default transport-and redirect behavior.--`HTTPNotificationSender` creates one reusable `retry-go/v5` retrier during-initialization. The retrier owns exactly three total attempts and exponential-backoff, but does not bind a caller context because it is reused across sends.-Each delivery checks its caller context, creates a fresh request and body, and-applies a five-second child context per attempt. Payload encoding, request-creation, one-attempt delivery, and retry configuration remain focused-operations.--### 9. Validation and API compatibility--Keep these public fields and routes unchanged:--- `Phone.FcmToken` / JSON `fcm_token`;-- `PUT /v1/phones`;-- `PUT /v1/phones/fcm-token`;-- all outstanding-message, event, receive-message, and heartbeat routes.--Extend phone validation only when `fcm_token` is URL-like:--- enforce valid HTTPS syntax and require a hostname;-- preserve the existing maximum token length;-- return field-level `fcm_token` validation errors for malformed or non-HTTPS- URL-like values.--Opaque FCM token validation remains unchanged. Existing stored Android tokens-require no migration.--Update request and Swagger descriptions to explain that `fcm_token` accepts-either an FCM registration token or an HTTPS adapter callback URL.-Regenerate Swagger documentation after implementation.--### 10. Observability--Use the existing request, database, and OpenTelemetry logging behavior without-special redaction for notification tokens or callback URLs. Rely on the-existing OpenTelemetry HTTP round-tripper for outbound request spans and-metrics; do not add sender-specific attempt spans or metrics.--## Components and Expected Files--Implementation is expected to touch:--- `api/pkg/entities/phone.go` for transport and URL helpers;-- `api/pkg/validators/phone_handler_validator.go` for URL-token validation;-- `api/pkg/services/phone_notification_service.go` for transport-client lookup,- message construction, and existing state transitions;-- `api/pkg/services/fcm_client.go` for the common transport-client contract and- Firebase implementation;-- `api/pkg/services/http_notification_sender.go` for HTTP payload encoding and- delivery;-- `api/pkg/services/emulator_fcm_client.go` only as needed to preserve the- emulator behind the adapted interface;-- `api/pkg/di/container.go` for dispatcher, OpenTelemetry HTTP client, and- sender construction;-- phone request annotations and generated Swagger files.-- `tests/adapter-emulator/` for an HTTPS gateway emulator that consumes- callbacks and exercises existing phone API routes;-- `tests/adapter_integration_test.go`, `tests/docker-compose.yml`, test- certificate generation, CI setup, and `tests/README.md` for end-to-end- coverage.--The implementation must not move scheduling, message expiration, message event-handling, or phone API-key authorization into the new transport code.--## Testing--### Phone helper tests--Cover:--- ordinary FCM tokens selecting Firebase;-- valid HTTPS URLs selecting HTTP;-- empty and nil tokens;-- `http`, `ftp`, missing host, and malformed URLs being invalid;-- URL-like invalid values never falling through to Firebase.--### HTTP client wiring tests--Cover the standard OpenTelemetry round-tripper wrapping-`http.DefaultTransport` without retryable HTTP transport attempts. URL-validation must not perform DNS or address checks.--### HTTP sender tests--Use an HTTP test server or controlled transport to cover:--- FCM-compatible message and heartbeat JSON;-- message priority and TTL mapping;-- stable `http/success` result for successful delivery;-- any `2xx` response succeeding with the body ignored;-- retrying network errors, `408`, `429`, and `5xx`;-- not retrying other `4xx` responses;-- three-attempt maximum and five-second per-attempt timeout;-- bounded response-body handling;-- errors and logs not exposing the complete URL.--### Dispatcher and service tests--Cover:--- Firebase tokens using the Firebase sender;-- URL tokens using the HTTP sender;-- outgoing messages and heartbeats using the same dispatcher;-- HTTP success using the existing sent-notification path;-- HTTP terminal failure using the existing failed-notification path;-- message send-attempt count and expiration scheduling remaining unchanged;-- scheduling, exact-send time, per-minute limits, and send schedules remaining- independent of transport.--### Adapter integration emulator--Add a dedicated Go service under `tests/adapter-emulator/`. It exposes:--- an HTTPS callback listener used by the API;-- an HTTP-only test control listener exposed to the host test runner;-- an in-memory gateway registry mapping a unique callback path to a phone- number and phone API key;-- callback records for integration assertions.--For `KEY_MESSAGE_ID`, the emulator:--1. fetches `/v1/messages/outstanding` using the registered phone API key;-2. posts the existing `SENT` event;-3. posts the existing `DELIVERED` event;-4. records the fetched message and final adapter action for test assertions.--For `KEY_HEARTBEAT_ID`, the emulator posts `/v1/heartbeats` for the registered-phone and records the heartbeat wake-up. A control endpoint also instructs the-emulator to submit an incoming message through `/v1/messages/receive`.--The integration stack generates a throwaway CA and server certificate whose SAN-contains `adapter-emulator`, mounts the server certificate into the emulator,-and makes the CA available to the API's Go trust store through `SSL_CERT_FILE`.-Docker DNS resolves the private emulator hostname through the standard Go HTTP-transport; no private-host allowlist is configured.--Add end-to-end tests for:--- **Outgoing:** URL-backed phone callback -> outstanding fetch -> sent event ->- delivered event -> final delivered API status.-- **Incoming:** emulator control request -> existing receive-message API ->- final received API status and matching owner/contact/content.-- **Heartbeat:** internal `phone.heartbeat.missed` CloudEvent -> URL callback ->- emulator heartbeat POST -> heartbeat visible through the user API.-- Callback payload keys, callback processing, and phone API-key scoping.--Run:--```bash-cd api-go test ./...-```--After annotation changes, regenerate Swagger:--```bash-cd api-swag init --requiredByDefault --parseDependency --parseInternal-```--Run the Docker integration suite:--```bash-cd tests-bash generate-firebase-credentials.sh-bash generate-adapter-certificates.sh-docker compose up -d --build --wait-docker compose wait seed-go test -v -timeout 300s ./...-docker compose down -v-```--## Rollout--The feature is backward compatible and requires no data migration. Deploy the-backend before configuring URL tokens.--Operational monitoring should distinguish Firebase and HTTP notification-delivery. Initial rollout should watch:--- HTTP callback success and retry rates;-- terminal failures by status class;-- callback latency;-- transport failures;-- message expiration after a successful HTTP wake-up;-- repeated callback processing observed by test adapters.--Rollback is code-only: existing Android tokens continue to be valid, while-URL-backed phones stop receiving wake-ups if the feature is rolled back.--## Out of Scope--- WhatsApp provider integration or any adapter implementation.-- Provider credentials, sessions, QR-code login, templates, or media mapping.-- New polling/list-outstanding APIs.-- A new adapter acknowledgement endpoint.-- Signed callbacks, HMAC, JWT, or mutual TLS.-- Separate transport or callback URL database columns.-- Changes to message scheduling, backpressure, expiration, or retry-count- algorithms.-- Web UI for configuring adapters.-- Android application changes.-- General-purpose outbound webhook refactoring.-- Destination-specific DNS/IP filtering or allowlists.