Files
CatoandClaude Opus 5 6090c7e0d0 fix: the Follow button, and three more bugs it was hiding (#902)
* fix(social): the Follow button never knew you already followed someone

/api/social/following|followers/[id] answer
`{ success, data: { data: [...], pagination } }` — rows two levels deep.
useProfileActions read `data.data` (the object) behind an `Array.isArray()`
guard, so the guard failed silently and `isFollowing` stayed false forever.
The button always read "Follow"; clicking it on someone you already followed
returned 409 "Already following this user" and surfaced as an error toast.
Observed in production 2026-09-05 16:39:33Z.

The dashboard People page had the sibling of the same bug: its row transform
read the join key `profiles` (plural), but the API aliases it to `profile`,
so every API row resolved to null and both lists rendered empty.

Fixes, class-level rather than instance-level:
- services/social/followList.ts is now the single reader for that endpoint
  pair; all three call sites go through it instead of unwrapping by hand.
- transformConnectionItem accepts either join key.
- A 409 now reconciles the button to "following" instead of reporting a
  failure for a state that is in fact true.
- __tests__/unit/api/follow-list-envelope.test.ts is a contract test running
  the REAL route factory into the REAL client parser.
- scripts/check-follow-envelope.mjs forbids reading those endpoints outside
  the shared reader, and is wired into `verify` (which CI runs verbatim).

Both gates were proven by mutation: reintroducing the nested-unwrap bug fails
the test, and reintroducing a raw endpoint reference fails the check.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019ns25hxd1ExZsmCJz9nNhe

* fix(messaging,currency): a missing FK silenced the personal actor; a rate fix was inert

Two production errors, both from today's logs.

1. actors.user_id was never declared a foreign key to profiles.
   /api/messages/actors embeds `profiles:user_id (name, avatar_url)`, and
   PostgREST resolves embeds from declared foreign keys, so every call got
   PGRST200 and fetchMessagingActors — which is best-effort and logs-and-skips
   — dropped the personal actor. Nobody could send a message as themselves,
   and it presented as an empty picker rather than an error. The table already
   declares actors_group_id_fkey for the other branch of its own check
   constraint; only this one was missing. 74/74 user actors resolve to a live
   profile (0 orphans), and the migration was dry-run against production
   inside a rolled-back transaction.

2. The /discover "static to dynamic" fix from #814 never worked.
   It escaped Next's render attribution with setTimeout(..., 0), on the theory
   that a macrotask boundary leaves the render's async context. It does not:
   AsyncLocalStorage propagates through timers by design (verified). The error
   was still firing in production today, and the page painted with no rate —
   which is how "amounts stay in BTC" reached /discover.
   The real fix is to stop the fetch being dynamic at all: it now declares a
   revalidate window instead of `cache: 'no-store'`, so Next has nothing to
   reclassify regardless of which context starts it. The window is FRESH_MS,
   the constant this module already calls "fresh enough to serve", so both
   caches answer "how old is this rate" the same way.
   The comment asserting the setTimeout mechanism is corrected in place rather
   than deleted — it was load-bearing misinformation for the next reader.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019ns25hxd1ExZsmCJz9nNhe

* fix(api): every failed request showed the user "[object Object]"

apiError() answers `{ success: false, error: { code, message } }` — `error` is
an OBJECT. 100 call sites did `X.error || 'Something failed'` and passed the
result to new Error(), toast.error() or setState(). A non-empty object is
truthy, so the fallback never fired and the object went through as-is:

  new Error({code, message})  -> err.message === '[object Object]'
  setError({code, message})   -> React throws "Objects are not valid as a
                                 React child" when it is rendered

So the server's actual reason was computed, serialised, sent, parsed — and
then thrown away at the last step. This is the error the follow bug surfaced
as: the API said "Already following this user" and the toast said
"[object Object]".

- lib/api/errorMessage.ts reads the standard envelope, a bare { message }
  (supabase's shape) and a plain string, so it is correct at every call site
  regardless of which vintage of route answered.
- All 100 sites rewritten mechanically; the sites in src/app/api take
  domain-layer `{ success, error }` results whose error is a string, which the
  helper returns unchanged — behaviour-preserving there, corrective elsewhere.
- no-restricted-syntax now rejects `X.error || 'fallback'`, so the class
  cannot come back. Proven by mutation: reintroducing the pattern fails lint.

2667 tests across 284 files pass unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019ns25hxd1ExZsmCJz9nNhe

* fix(social): answering "do I follow X" by paging a list broke past 20 follows

The Follow button's status check searched the viewer's following list. That
list is capped at DEFAULT_PAGE_SIZE (20), so the answer was only correct for
the first 20 people you follow. Follow a 21st and the button reads "Follow"
for someone you already follow and the POST returns 409 — the same bug this
branch just fixed, rearmed with a delay fuse. It has not fired yet only
because the busiest account follows 4 people.

"Do I follow X" is a different question from "list who I follow" and has a
different shape: one lookup on (follower_id, following_id), which is already
the table's unique constraint. GET /api/social/follow-status/[id] answers it
in O(1) and cannot be wrong at any list length.

The gate covers the new endpoint too, so it can only be read through the
shared reader.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019ns25hxd1ExZsmCJz9nNhe

* fix(lint): scope the error-envelope rule to string fallbacks, and fix the site it found

CI caught four sites the codemod missed. Two of them were FALSE POSITIVES in
the new rule: `if (result.error || !result.data)` is a truthiness guard on a
supabase result and is completely correct. The selector matched any
`X.error || Y`, so it flagged those too — and a gate that fires on correct code
gets disabled rather than obeyed, which would have cost more than the bug.

The selector now requires a STRING fallback (literal or template), which is
exactly the bug — defaulting an object to a message — and never a boolean
guard. Verified both directions: silent on the two guards, still fires when the
real pattern is reintroduced.

The third site was real. NewConversationModal hand-rolled this helper as
`data.error || data.details || data.hint || '...'` and got the first link
wrong, so the envelope object won the `||` and the thrown Error read
"[object Object]". It now goes through apiErrorMessage, keeping the endpoint's
extra postgrest detail as the fallback.

Full `eslint src`: 0 errors. type-check clean.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019ns25hxd1ExZsmCJz9nNhe

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-06 21:59:48 +00:00

64 lines
2.6 KiB
TypeScript

/**
* apiErrorMessage — reads a usable string out of any failed API response.
*
* The class this closes: `X.error || 'fallback'` against the standard envelope,
* where `error` is `{ code, message }`. A non-empty object is truthy, so the
* fallback never fired and the object reached new Error() / toast.error() /
* setState() — rendering as the string "[object Object]", or throwing when
* React tried to render it as a child.
*/
import { describe, it, expect } from 'vitest';
import { apiErrorMessage } from '@/lib/api/errorMessage';
describe('apiErrorMessage', () => {
it('reads the standard envelope, which is what broke the follow toast', () => {
const body = {
success: false,
error: { code: 'CONFLICT', message: 'Already following this user' },
metadata: { timestamp: '2026-09-05T16:39:33.480Z' },
};
expect(apiErrorMessage(body, 'Failed to update follow status')).toBe(
'Already following this user'
);
// The regression, stated plainly.
expect(String(new Error(apiErrorMessage(body, 'fallback')).message)).not.toBe(
'[object Object]'
);
});
it('passes through routes that answer with a bare string error', () => {
expect(apiErrorMessage({ success: false, error: 'Upload failed' }, 'fallback')).toBe(
'Upload failed'
);
});
it('reads a bare { message }, which is the supabase error shape', () => {
expect(apiErrorMessage({ message: 'duplicate key value', code: '23505' }, 'fallback')).toBe(
'duplicate key value'
);
});
it('accepts a plain string', () => {
expect(apiErrorMessage('Something specific', 'fallback')).toBe('Something specific');
});
it('falls back when there is no usable message', () => {
expect(apiErrorMessage(null, 'fallback')).toBe('fallback');
expect(apiErrorMessage(undefined, 'fallback')).toBe('fallback');
expect(apiErrorMessage({}, 'fallback')).toBe('fallback');
expect(apiErrorMessage({ success: false }, 'fallback')).toBe('fallback');
expect(apiErrorMessage({ error: {} }, 'fallback')).toBe('fallback');
expect(apiErrorMessage({ error: { code: 'X' } }, 'fallback')).toBe('fallback');
// Whitespace-only is not a message a human can act on.
expect(apiErrorMessage({ error: ' ' }, 'fallback')).toBe('fallback');
expect(apiErrorMessage({ error: { message: ' ' } }, 'fallback')).toBe('fallback');
});
it('always returns a string, so callers can hand it to React or Error', () => {
for (const input of [null, 0, false, [], { error: { message: 42 } }, { error: [] }]) {
expect(typeof apiErrorMessage(input, 'fallback')).toBe('string');
}
});
});