Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/(site)/messages/[id]/Thread.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ export function Thread({ conversationId, me, other, initial }: { conversationId:
<div className="thread" aria-live="polite">
{messages.length === 0 && (
<p className="sub" style={{ textAlign: "center", margin: "30px auto" }}>
say hi to {other.displayName || other.netid} &mdash; ask if it&rsquo;s still available, how it fits, or when to pick up.
say hi to {other.displayName || other.netid} &mdash; write your first message below.
</p>
)}
{messages.map((m, i) => {
Expand Down
6 changes: 3 additions & 3 deletions app/(site)/messages/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@ async function Conversation({ params }: { params: PageProps<"/messages/[id]">["p
<Avatar person={other} size={34} />
<b>{personLabel(other)}</b>
</PersonLink>
<span className="muted">{iAmSeller ? "· buyer" : "· seller"}</span>
{listing && <span className="muted">{iAmSeller ? "· buyer" : "· seller"}</span>}
</span>
<Link className="convo-item" href={`/listings/${listing.id}`}>
{listing && <Link className="convo-item" href={`/listings/${listing.id}`}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={listing.photoUrl} alt="" />
<span>
Expand All @@ -51,7 +51,7 @@ async function Conversation({ params }: { params: PageProps<"/messages/[id]">["p
{listing.status === "sold" ? " · sold" : ""}
</span>
</span>
</Link>
</Link>}
</div>
<Thread conversationId={conversation.id} me={user.netid} other={other} initial={messages} />
</div>
Expand Down
11 changes: 11 additions & 0 deletions app/(site)/messages/new/RecipientButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"use client";
import { useActionState } from "react";
import { newMessageAction } from "./actions";
export function RecipientButton({ netid }: { netid: string }) {
const [state, action, pending] = useActionState(newMessageAction, {});
return <form action={action}>
<input type="hidden" name="recipient" value={netid} />
<button className="btn btn-primary" disabled={pending}>{pending ? "opening…" : "message"}</button>
{state.error && <p className="err" role="alert">{state.error}</p>}
</form>;
}
20 changes: 20 additions & 0 deletions app/(site)/messages/new/actions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { beforeEach, expect, it, vi } from "vitest";
const m = vi.hoisted(() => ({ user: vi.fn(), start: vi.fn(), redirect: vi.fn() }));
vi.mock("@/lib/auth", () => ({requireUser: m.user}));
vi.mock("@/lib/directMessages", () => ({startDirectConversation: m.start}));
vi.mock("next/navigation", () => ({redirect: m.redirect}));
import { newMessageAction } from "./actions";
const form = () => { const f = new FormData(); f.set("recipient","ao5729"); f.set("viewer","fake"); return f; };
beforeEach(() => {vi.resetAllMocks();m.user.mockResolvedValue({netid:"rp4348"});});
it("requires a signed-in user before creating a conversation",async()=>{
m.user.mockRejectedValue(new Error("login"));
await expect(newMessageAction({},form())).rejects.toThrow("login");expect(m.start).not.toHaveBeenCalled();
});
it("uses the session identity and redirects to the selected thread",async()=>{
m.start.mockResolvedValue("thread");await newMessageAction({},form());
expect(m.start).toHaveBeenCalledWith("rp4348","ao5729");expect(m.redirect).toHaveBeenCalledWith("/messages/thread");
});
it("shows recipient errors without redirecting",async()=>{
m.start.mockRejectedValue(new Error("not registered"));
expect(await newMessageAction({},form())).toEqual({error:"not registered"});expect(m.redirect).not.toHaveBeenCalled();
});
15 changes: 15 additions & 0 deletions app/(site)/messages/new/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
"use server";
import { redirect } from "next/navigation";
import { requireUser } from "@/lib/auth";
import { startDirectConversation } from "@/lib/directMessages";

export async function newMessageAction(_: { error?: string }, form: FormData): Promise<{ error?: string }> {
const user = await requireUser("/messages/new");
let id: string;
try {
id = await startDirectConversation(user.netid, String(form.get("recipient") ?? ""));
} catch (e) {
return { error: e instanceof Error ? e.message : "Could not open the conversation." };
}
redirect(`/messages/${id}`);
}
37 changes: 37 additions & 0 deletions app/(site)/messages/new/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import Link from "next/link";
import { Suspense } from "react";
import { requireUser } from "@/lib/auth";
import { searchRecipients } from "@/lib/directMessages";
import { personLabel } from "@/lib/rules";
import { Avatar } from "../../_components/Avatar";
import { RecipientButton } from "./RecipientButton";

type Search = Promise<{ q?: string | string[] }>;
export default function NewMessagePage({ searchParams }: { searchParams: Search }) {
return <div className="wf"><div className="wrap" style={{ paddingTop: 24 }}>
<Link className="crumb-link" href="/messages">← messages</Link>
<h1 className="sec-title" style={{ marginTop: 16 }}>new message</h1>
<p className="sub">find a registered person by name or netid.</p>
<Suspense fallback={<p className="sub">loading…</p>}><Recipients searchParams={searchParams} /></Suspense>
</div></div>;
}
async function Recipients({ searchParams }: { searchParams: Search }) {
const user = await requireUser("/messages/new");
const params = await searchParams;
const q = typeof params.q === "string" ? params.q.slice(0, 80) : "";
const people = await searchRecipients(user.netid, q);
return <>
<form action="/messages/new" style={{ display: "flex", gap: 10, maxWidth: 650, marginBottom: 24 }}>
<input key={q} className="inp" name="q" defaultValue={q} placeholder="name or netid" aria-label="name or netid" maxLength={80} required />
<button className="btn btn-outline">search</button>
</form>
{q.trim() && people.length === 0 && <p className="sub">no registered people found. try their netid.</p>}
<div className="inbox">
{people.map(person => <div className="inbox-row" key={person.netid}>
<Avatar person={person} size={44} />
<div className="inbox-mid"><b>{personLabel(person)}</b><div className="muted">{person.netid}</div></div>
<RecipientButton netid={person.netid} />
</div>)}
</div>
</>;
}
12 changes: 6 additions & 6 deletions app/(site)/messages/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ export default function MessagesPage() {
return (
<div className="wf">
<div className="wrap" style={{ paddingTop: 24 }}>
<h1 className="sec-title">messages</h1>
<div className="sec-head"><h1 className="sec-title">messages</h1><Link className="btn btn-primary" href="/messages/new">+ new message</Link></div>
<p className="sub" style={{ marginTop: 4 }}>
questions and pickup plans, one conversation per item.
message someone directly, or keep talking about an item.
</p>
<Suspense fallback={<p className="sub">loading…</p>}>
<Inbox />
Expand All @@ -33,7 +33,7 @@ async function Inbox() {
if (!rows.length) {
return (
<div className="empty" style={{ marginTop: 18 }}>
no messages yet. open any listing and tap <b>message seller</b> to ask a question.
no messages yet. choose <Link href="/messages/new">new message</Link> to start a conversation.
</div>
);
}
Expand All @@ -45,7 +45,7 @@ async function Inbox() {
<div className="inbox-mid">
<div className="inbox-top">
<b>{personLabel(r.other)}</b>
<span className="muted">· {r.listing.title}</span>
{r.listing && <span className="muted">· {r.listing.title}</span>}
</div>
<div className="inbox-last">
{r.lastFromMe ? "you: " : ""}
Expand All @@ -56,10 +56,10 @@ async function Inbox() {
{r.lastMessageAt && <span className="muted">{ago(r.lastMessageAt, now)}</span>}
{r.unread && <span className="dot" aria-label="unread" />}
</div>
<span className="inbox-thumb">
{r.listing && <span className="inbox-thumb">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={r.listing.photoUrl} alt="" />
</span>
</span>}
</Link>
))}
</div>
Expand Down
7 changes: 7 additions & 0 deletions db/migrations/20261027000000_direct_messages.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-- Direct conversations share the existing participant checks and message storage.
-- Existing item conversations retain their listing foreign key and uniqueness.
alter table conversations alter column listing_id drop not null;
alter table conversations add constraint direct_conversation_order
check (listing_id is not null or buyer_netid collate "C" < seller_netid collate "C");
create unique index conversations_direct_pair on conversations (buyer_netid, seller_netid)
where listing_id is null;
18 changes: 9 additions & 9 deletions lib/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -558,17 +558,17 @@ export interface Message {
}
export interface Conversation extends ConversationState {
id: string;
listingId: string;
listingId: string | null;
}
export interface ConversationView {
conversation: Conversation;
listing: { id: string; title: string; priceCents: number; photoUrl: string; status: ListingStatus };
listing: { id: string; title: string; priceCents: number; photoUrl: string; status: ListingStatus } | null;
other: Person;
messages: Message[];
}
export interface InboxRow {
id: string;
listing: { id: string; title: string; photoUrl: string };
listing: { id: string; title: string; photoUrl: string } | null;
other: Person;
lastMessage: string | null;
lastMessageAt: string | null;
Expand All @@ -578,7 +578,7 @@ export interface InboxRow {

const toConversation = (r: Row): Conversation => ({
id: r.id as string,
listingId: r.listing_id as string,
listingId: r.listing_id as string | null,
buyerNetid: r.buyer_netid as string,
sellerNetid: r.seller_netid as string,
lastMessageAt: r.last_message_at as string | null,
Expand Down Expand Up @@ -634,15 +634,15 @@ export async function conversationFor(id: string, viewer: string): Promise<Conve
}
const otherNetid = c.buyerNetid === viewer ? c.sellerNetid : c.buyerNetid;
const [listing, who, rows] = await Promise.all([
getListing(c.listingId),
c.listingId ? getListing(c.listingId) : Promise.resolve(null),
people([otherNetid]),
step("load messages", () => sql()<Row[]>`select * from messages where conversation_id = ${c.id} order by created_at`),
]);
if (!listing) return null;
if (c.listingId && !listing) return null;
await markRead(c, viewer);
return {
conversation: c,
listing: { id: listing.id, title: listing.title, priceCents: listing.priceCents, photoUrl: listing.photoUrls[0], status: listing.status },
listing: listing ? { id: listing.id, title: listing.title, priceCents: listing.priceCents, photoUrl: listing.photoUrls[0], status: listing.status } : null,
other: who.get(otherNetid) ?? { netid: otherNetid, displayName: null, avatarUrl: null },
messages: rows.map(toMessage),
};
Expand Down Expand Up @@ -676,7 +676,7 @@ export async function messagesSince(conversationId: string, viewer: string, afte
export async function inbox(viewer: string): Promise<InboxRow[]> {
const rows = await step("load inbox", () => sql()<Row[]>`
select c.*, l.title as listing_title, l.photo_paths as listing_photo_paths
from conversations c join listings l on l.id = c.listing_id
from conversations c left join listings l on l.id = c.listing_id
where (c.buyer_netid = ${viewer} or c.seller_netid = ${viewer}) and c.last_message_at is not null
order by c.last_message_at desc`);
const convs = rows.map((r) => ({ c: toConversation(r), l: r }));
Expand All @@ -693,7 +693,7 @@ export async function inbox(viewer: string): Promise<InboxRow[]> {
const lastBody = new Map(lasts.map((r) => [r.conversation_id as string, r.body as string]));
return convs.map(({ c, l }, i) => ({
id: c.id,
listing: { id: c.listingId, title: l.listing_title as string, photoUrl: photoUrl((l.listing_photo_paths as string[])[0]) },
listing: c.listingId ? { id: c.listingId, title: l.listing_title as string, photoUrl: photoUrl((l.listing_photo_paths as string[])[0]) } : null,
other: who.get(others[i]) ?? { netid: others[i], displayName: null, avatarUrl: null },
lastMessage: lastBody.get(c.id) ?? null,
lastMessageAt: c.lastMessageAt,
Expand Down
35 changes: 35 additions & 0 deletions lib/directMessages.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { beforeEach, expect, it, vi } from "vitest";
const {query}=vi.hoisted(()=>({query:vi.fn()}));
vi.mock("server-only",()=>({}));
vi.mock("./db",()=>({sql:()=>query}));
import { startDirectConversation, searchRecipients } from "./directMessages";
beforeEach(()=>vi.resetAllMocks());
it("blocks self and system recipients before querying",async()=>{
for(const id of ["rp4348","listserv","seed-person","e2e-admin",""]) await expect(startDirectConversation("rp4348",id)).rejects.toThrow();
expect(query).not.toHaveBeenCalled();
});
it("rejects unregistered recipients",async()=>{
query.mockResolvedValueOnce([]);
await expect(startDirectConversation("rp4348","missing")).rejects.toThrow("registered");
expect(query).toHaveBeenCalledTimes(1);
});
it("uses the same ordered pair in either direction",async()=>{
query.mockResolvedValue([{id:"thread",netid:"ao5729"}]);
expect(await startDirectConversation("rp4348","ao5729")).toBe("thread");
expect(query.mock.calls[1].slice(1)).toEqual(["ao5729","rp4348"]);
query.mockClear();
await startDirectConversation("ao5729","rp4348");
expect(query.mock.calls[1].slice(1)).toEqual(["ao5729","rp4348"]);
expect(query.mock.calls[1][0].join("?")).toContain("on conflict");
});
it("does not list the user directory without a search",async()=>{
expect(await searchRecipients("rp4348"," ")).toEqual([]);
expect(query).not.toHaveBeenCalled();
});
it("returns only public profile fields and uses literal bounded search",async()=>{
query.mockResolvedValue([{netid:"ao5729",display_name:"Amel",avatar_path:null,phone:"private",payments:[{handle:"private"}]}]);
expect(await searchRecipients("rp4348"," Amel ")).toEqual([{netid:"ao5729",displayName:"Amel",avatarUrl:null}]);
const statement=query.mock.calls[0][0].join("?");
expect(statement).toContain("limit 20");expect(statement).toContain("netid not like 'seed-%'");
expect(query.mock.calls[0].slice(1)).toEqual(["rp4348","amel","amel"]);
});
30 changes: 30 additions & 0 deletions lib/directMessages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import "server-only";
import { sql, type Row } from "./db";
import { isReservedNetid } from "./cas";
import { avatarUrl } from "./storage";
import type { Person } from "./data";

// Callers must supply the viewer from the verified session.
export async function searchRecipients(viewer: string, input: string): Promise<Person[]> {
const term = input.trim().toLowerCase().slice(0, 80);
if (!term) return [];
const rows = await sql()<Row[]>`select netid, display_name, avatar_path from users
where netid <> ${viewer} and netid <> 'listserv' and netid not like 'seed-%' and netid not like 'e2e-%'
and (strpos(lower(netid), ${term}) > 0 or strpos(lower(coalesce(display_name, '')), ${term}) > 0)
order by netid limit 20`;
return rows.map(r => ({ netid: r.netid as string, displayName: r.display_name as string | null, avatarUrl: r.avatar_path ? avatarUrl(r.avatar_path as string) : null }));
}

export async function startDirectConversation(viewer: string, input: string): Promise<string> {
const recipient = input.trim().toLowerCase();
if (!/^[a-z0-9_]+$/.test(recipient) || recipient === viewer || isReservedNetid(recipient)) throw new Error("Choose another registered person.");
const [user] = await sql()`select netid from users where netid = ${recipient}`;
if (!user) throw new Error("That person has not registered yet.");
// Stable ordering plus a unique index handles simultaneous starts from either side.
const [first, second] = [viewer, recipient].sort();
const [row] = await sql()`insert into conversations (listing_id, buyer_netid, seller_netid)
values (null, ${first}, ${second})
on conflict (buyer_netid, seller_netid) where listing_id is null
do update set buyer_netid = excluded.buyer_netid returning id`;
return row.id as string;
}
26 changes: 26 additions & 0 deletions lib/directThreads.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { beforeEach, expect, it, vi } from "vitest";
const { query } = vi.hoisted(() => ({ query: vi.fn() }));
vi.mock("server-only", () => ({}));
vi.mock("./db", () => ({ sql: () => (first: unknown, ...values: unknown[]) => Array.isArray(first) && "raw" in first ? query(first, ...values) : first }));
import { conversationFor, sendMessage, inbox } from "./data";
const id = "10000000-0000-4000-8000-000000000001";
const row = { id, listing_id: null, buyer_netid: "ao5729", seller_netid: "rp4348", last_message_at: "2026-10-21T10:00:00Z", last_sender_netid: "ao5729", buyer_read_at: null, seller_read_at: null };
beforeEach(() => vi.resetAllMocks());
it("opens direct threads without looking up a listing", async () => {
query.mockResolvedValueOnce([row]).mockResolvedValueOnce([{netid: "ao5729", display_name: "Amel", avatar_path: null}]).mockResolvedValueOnce([]).mockResolvedValueOnce([]);
const view = await conversationFor(id, "rp4348");
expect(view?.listing).toBeNull(); expect(view?.other.netid).toBe("ao5729");
expect(query.mock.calls.some(c => c[0].join("").includes("from listings"))).toBe(false);
});
it("rejects outsiders when opening or sending to a direct conversation", async () => {
query.mockResolvedValue([row]);
expect(await conversationFor(id, "outsider")).toBeNull();
await expect(sendMessage(id, "outsider", "hi")).rejects.toThrow("doesn't exist");
expect(query.mock.calls.every(c => c[0].join("").includes("select * from conversations"))).toBe(true);
});
it("includes direct conversations in the inbox without a listing thumbnail", async () => {
query.mockResolvedValueOnce([row]).mockResolvedValueOnce([{netid: "ao5729", display_name: "Amel", avatar_path: null}]).mockResolvedValueOnce([{conversation_id: id,body: "hello"}]);
const rows = await inbox("rp4348");
expect(rows[0]).toMatchObject({id,listing: null,lastMessage: "hello",unread: true});
expect(query.mock.calls[0][0].join("")).toContain("left join listings");
});
Loading