From 84c98681c96f36ba8d14580dadcdf19b89e2ae54 Mon Sep 17 00:00:00 2001 From: caelum0x Date: Sun, 28 Jun 2026 19:30:15 +0300 Subject: [PATCH] feat: round-8 external harvest (15 features; web scout exhausted) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Final harvest round — gitgram-web scout returned no remaining valuable features. - gitgram-mobile (5): swipe-to-reply, date dividers, swipe-to-action chat UX (bluesky) - aitm-mcp (6): transport arg aliasing for hallucinated arg names (context7), + tool envelopes - aitm-api (3): beads search endpoint + comments/notes over the DAG (beads) - gitgram-backend (1): re-process @mentions on comment edit (munia) Co-Authored-By: Claude Opus 4.8 (1M context) --- aitimemachine/api-server/src/routes/beads.ts | 517 +++++++++++++++++- .../api-server/src/services/memoryService.ts | 68 +++ .../src/__tests__/tool-arg-aliasing.test.ts | 121 ++++ aitimemachine/mcp/src/http-transport.ts | 5 + aitimemachine/mcp/src/index.ts | 5 + .../mcp/src/tools/register-beads-tools.ts | 262 ++++++++- gitgram/backend/prisma/schema.prisma | 23 + .../controllers/commentActionsController.ts | 33 +- .../src/controllers/messageController.ts | 166 +++++- gitgram/backend/src/routes/messages.ts | 100 ++++ gitgram/mobile/app/chat/[userId].tsx | 388 +++++++++++-- gitgram/mobile/components/Post/PostCard.tsx | 32 +- .../mobile/components/chat/DateDivider.tsx | 97 ++++ .../components/chat/EmojiReactionPicker.tsx | 139 +++++ .../components/chat/NewMessagesPill.tsx | 130 +++++ .../mobile/components/chat/SwipeToReply.tsx | 217 ++++++++ .../mobile/components/common/CountWheel.tsx | 163 ++++++ gitgram/mobile/services/messageService.ts | 35 ++ 18 files changed, 2438 insertions(+), 63 deletions(-) create mode 100644 aitimemachine/mcp/src/__tests__/tool-arg-aliasing.test.ts create mode 100644 gitgram/mobile/components/chat/DateDivider.tsx create mode 100644 gitgram/mobile/components/chat/EmojiReactionPicker.tsx create mode 100644 gitgram/mobile/components/chat/NewMessagesPill.tsx create mode 100644 gitgram/mobile/components/chat/SwipeToReply.tsx create mode 100644 gitgram/mobile/components/common/CountWheel.tsx diff --git a/aitimemachine/api-server/src/routes/beads.ts b/aitimemachine/api-server/src/routes/beads.ts index c41a4eac..02744e3e 100644 --- a/aitimemachine/api-server/src/routes/beads.ts +++ b/aitimemachine/api-server/src/routes/beads.ts @@ -8,6 +8,9 @@ import { listDependencyTree, findDependencyCycles, compactIssues, + runBeadsDoctor, + BEADS_DOCTOR_CHECKS, + type BeadsDoctorCheck, remember, recall, listMemories, @@ -116,6 +119,34 @@ const DEPENDENCY_TYPES = [ ] as const; type DependencyType = (typeof DEPENDENCY_TYPES)[number]; +// Issue types the bundled `bd` binary accepts on create/update. Aliases +// (enhancement/feat→feature, dec/adr→decision) are resolved by the CLI itself. +const ISSUE_TYPES = [ + "bug", + "feature", + "task", + "epic", + "chore", + "decision", +] as const; +type IssueType = (typeof ISSUE_TYPES)[number]; + +function isIssueType(value: unknown): value is IssueType { + return ( + typeof value === "string" && + (ISSUE_TYPES as readonly string[]).includes(value) + ); +} + +/** A trimmed non-empty string body field, or null when absent/blank. */ +function cleanText(value: unknown): string | null { + if (typeof value !== "string") { + return null; + } + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : null; +} + function isDependencyType(value: unknown): value is DependencyType { return ( typeof value === "string" && @@ -529,21 +560,90 @@ router.delete("/memory/:key", async (req: Request, res: Response) => { } }); -// POST /beads/tasks — create a task -// body: { title: string, deps?: string[] } +// POST /beads/tasks — create a task with the full issue model. +// body: { +// title: string, +// deps?: string[], +// description?, design?, acceptanceCriteria?, notes?, externalRef?: string, +// priority?: number (0-4), +// issueType?: bug|feature|task|epic|chore|decision +// } +// Only title is required; the rest are forwarded to the `bd add` flags the CLI +// natively supports, so agents can capture full design/acceptance context at +// creation time instead of losing it. router.post("/tasks", async (req: Request, res: Response) => { - const { title, deps } = req.body as { title?: string; deps?: string[] }; + const body = req.body as { + title?: unknown; + deps?: unknown; + description?: unknown; + design?: unknown; + acceptanceCriteria?: unknown; + notes?: unknown; + externalRef?: unknown; + priority?: unknown; + issueType?: unknown; + }; - if (!title || typeof title !== "string" || title.trim().length === 0) { + const title = cleanText(body.title); + if (!title) { return res.status(400).json({ success: false, error: "title is required" }); } - const args: string[] = ["add", "--title", title.trim()]; + const deps = Array.isArray(body.deps) + ? body.deps.filter((d): d is string => typeof d === "string" && d.trim().length > 0) + : []; - if (Array.isArray(deps) && deps.length > 0) { + const args: string[] = ["add", "--title", title]; + + if (deps.length > 0) { args.push("--deps", deps.join(",")); } + const description = cleanText(body.description); + if (description) { + args.push("--description", description); + } + + const design = cleanText(body.design); + if (design) { + args.push("--design", design); + } + + const acceptanceCriteria = cleanText(body.acceptanceCriteria); + if (acceptanceCriteria) { + args.push("--acceptance", acceptanceCriteria); + } + + const notes = cleanText(body.notes); + if (notes) { + args.push("--notes", notes); + } + + const externalRef = cleanText(body.externalRef); + if (externalRef) { + args.push("--external-ref", externalRef); + } + + if (body.priority !== undefined) { + const priority = boundedInt(body.priority, 0, 4); + if (priority === undefined) { + return res + .status(400) + .json({ success: false, error: "priority must be an integer 0-4" }); + } + args.push("--priority", String(priority)); + } + + if (body.issueType !== undefined) { + if (!isIssueType(body.issueType)) { + return res.status(400).json({ + success: false, + error: `issueType must be one of: ${ISSUE_TYPES.join(", ")}`, + }); + } + args.push("--type", body.issueType); + } + try { const { stdout } = await execFileAsync(beadsBin(), args); const data = parseBeadsJson(stdout); @@ -636,8 +736,12 @@ router.put("/tasks/:id/done", async (req: Request, res: Response) => { } }); -// PATCH /beads/tasks/:id — edit task fields (title/priority/assignee/status/ -// labels). Only provided fields are applied; at least one must be present. +// PATCH /beads/tasks/:id — edit task fields. Only provided fields are applied; +// at least one must be present. Beyond the core editable fields (title, +// priority, assignee, status, labels) this also forwards the rich issue model +// the `bd update` CLI supports: description, design, acceptanceCriteria, notes, +// externalRef, and issueType — so agents can refine full task specs after +// creation instead of losing that context. router.patch("/tasks/:id", async (req: Request, res: Response) => { const id = cleanId(req.params.id); if (!id) { @@ -650,6 +754,12 @@ router.patch("/tasks/:id", async (req: Request, res: Response) => { assignee?: unknown; status?: unknown; labels?: unknown; + description?: unknown; + design?: unknown; + acceptanceCriteria?: unknown; + notes?: unknown; + externalRef?: unknown; + issueType?: unknown; }; const args: string[] = ["update", id]; @@ -692,10 +802,53 @@ router.patch("/tasks/:id", async (req: Request, res: Response) => { changed = true; } + const description = cleanText(body.description); + if (description) { + args.push("--description", description); + changed = true; + } + + const design = cleanText(body.design); + if (design) { + args.push("--design", design); + changed = true; + } + + const acceptanceCriteria = cleanText(body.acceptanceCriteria); + if (acceptanceCriteria) { + args.push("--acceptance", acceptanceCriteria); + changed = true; + } + + const notes = cleanText(body.notes); + if (notes) { + args.push("--notes", notes); + changed = true; + } + + const externalRef = cleanText(body.externalRef); + if (externalRef) { + args.push("--external-ref", externalRef); + changed = true; + } + + if (body.issueType !== undefined) { + if (!isIssueType(body.issueType)) { + return res.status(400).json({ + success: false, + error: `issueType must be one of: ${ISSUE_TYPES.join(", ")}`, + }); + } + args.push("--type", body.issueType); + changed = true; + } + if (!changed) { return res.status(400).json({ success: false, - error: "at least one of title, priority, assignee, status, labels is required", + error: + "at least one of title, priority, assignee, status, labels, description, " + + "design, acceptanceCriteria, notes, externalRef, issueType is required", }); } @@ -809,6 +962,53 @@ router.get("/stale", async (req: Request, res: Response) => { } }); +// POST /beads/admin — DAG health diagnostics and optional repair. +// +// Runs `bd doctor` to surface orphaned dependency references, duplicate issues, +// test pollution, git-conflict cruft, and (with deep=true) full graph-integrity +// problems. Read-only by default; mutating repair requires explicit flags so an +// accidental call never alters the store. body: +// { check?: "validate"|"pollution"|"artifacts", +// fix?: boolean, // auto-repair fixable validate findings +// clean?: boolean, // delete detected pollution / stale artifacts +// deep?: boolean } // slower full graph-integrity validation +router.post("/admin", async (req: Request, res: Response) => { + const body = req.body as { + check?: unknown; + fix?: unknown; + clean?: unknown; + deep?: unknown; + }; + + let check: BeadsDoctorCheck | undefined; + if (body.check !== undefined) { + const raw = singleQueryValue(body.check); + if (!raw || !(BEADS_DOCTOR_CHECKS as readonly string[]).includes(raw)) { + return res.status(400).json({ + success: false, + error: `check must be one of: ${BEADS_DOCTOR_CHECKS.join(", ")}`, + }); + } + check = raw as BeadsDoctorCheck; + } + + try { + const data = await runBeadsDoctor({ + check, + fix: body.fix === true, + clean: body.clean === true, + deep: body.deep === true, + }); + res.json({ success: true, data }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: + err instanceof Error ? err.message : "Failed to run beads diagnostics", + }); + } +}); + // GET /beads/prime — AI-optimized workflow context as markdown. // // Bootstraps an agent at session start with the current Beads workflow state @@ -852,6 +1052,305 @@ router.get("/prime", async (req: Request, res: Response) => { } }); +// GET /beads/search?q=:query — full-text search across the issue DAG. +// +// Complements the work-queue routes (ready/blocked/stale) and the unified-memory +// search by exposing `bd search`, which scans ALL issues in the DAG — including +// arbitrary or closed issues that were never write-through-ingested into the +// memory layer. ID-like queries (e.g. "bd-5q") use fast exact/prefix matching; +// text queries match titles. This is the core "has someone already filed this?" +// retrieval primitive for a swarm of agents before opening duplicate work. +// +// Query params (all optional except q): +// q | query — the search query (required) +// status — open|in_progress|blocked|deferred|closed|all +// (default excludes closed; use 'all' to include them) +// assignee — filter by assignee +// type — bug|feature|task|epic|chore|decision|merge-request|molecule|gate +// labels — AND filter (comma-separated or repeated) +// labelsAny — OR filter (comma-separated or repeated) +// limit — max results (1-1000, default 50) +// sort — priority|created|updated|closed|status|id|title|type|assignee +// reverse — reverse sort order (1/true) +// descContains — description substring (case-insensitive) +// notesContains — notes substring (case-insensitive) +// priorityMin — minimum priority, inclusive (0-4) +// priorityMax — maximum priority, inclusive (0-4) +// createdAfter — YYYY-MM-DD or RFC3339 +// createdBefore — YYYY-MM-DD or RFC3339 +// noAssignee — only issues with no assignee (1/true) +// noLabels — only issues with no labels (1/true) +const SEARCH_STATUSES = [ + "open", + "in_progress", + "blocked", + "deferred", + "closed", + "all", +] as const; + +const SEARCH_SORT_FIELDS = [ + "priority", + "created", + "updated", + "closed", + "status", + "id", + "title", + "type", + "assignee", +] as const; + +const SEARCH_ISSUE_TYPES = [ + "bug", + "feature", + "task", + "epic", + "chore", + "decision", + "merge-request", + "molecule", + "gate", +] as const; + +/** A YYYY-MM-DD or RFC3339 date string, validated; null when absent/invalid. */ +function dateFlag(value: unknown): string | null { + const raw = singleQueryValue(value); + if (!raw) { + return null; + } + // Accept plain dates (YYYY-MM-DD) and full RFC3339 timestamps. Anything the + // binary cannot parse would be rejected downstream; pre-validate here so we + // return a 400 instead of leaking a CLI parse error as a 500. + const isValidShape = + /^\d{4}-\d{2}-\d{2}$/.test(raw) || + !Number.isNaN(Date.parse(raw)); + return isValidShape ? raw : null; +} + +function isTruthyFlag(value: unknown): boolean { + const v = singleQueryValue(value); + return v === "1" || v === "true"; +} + +router.get("/search", async (req: Request, res: Response) => { + const query = singleQueryValue(req.query.q) ?? singleQueryValue(req.query.query); + if (!query) { + return res + .status(400) + .json({ success: false, error: "q (search query) is required" }); + } + + // Put the positional query after `--` so a query that begins with `-` + // (e.g. "-flag") is not misparsed as a CLI flag by the binary. + const args: string[] = ["search", "--json"]; + + const status = singleQueryValue(req.query.status); + if (status !== undefined) { + if (!(SEARCH_STATUSES as readonly string[]).includes(status)) { + return res.status(400).json({ + success: false, + error: `status must be one of: ${SEARCH_STATUSES.join(", ")}`, + }); + } + args.push("--status", status); + } + + const assignee = singleQueryValue(req.query.assignee); + if (assignee) { + args.push("--assignee", assignee); + } + + const issueType = singleQueryValue(req.query.type); + if (issueType !== undefined) { + if (!(SEARCH_ISSUE_TYPES as readonly string[]).includes(issueType)) { + return res.status(400).json({ + success: false, + error: `type must be one of: ${SEARCH_ISSUE_TYPES.join(", ")}`, + }); + } + args.push("--type", issueType); + } + + for (const label of labelList(req.query.labels)) { + args.push("--label", label); + } + for (const label of labelList(req.query.labelsAny)) { + args.push("--label-any", label); + } + + const limit = boundedInt(req.query.limit, 1, 1000); + if (limit !== undefined) { + args.push("--limit", String(limit)); + } + + const sort = singleQueryValue(req.query.sort); + if (sort !== undefined) { + if (!(SEARCH_SORT_FIELDS as readonly string[]).includes(sort)) { + return res.status(400).json({ + success: false, + error: `sort must be one of: ${SEARCH_SORT_FIELDS.join(", ")}`, + }); + } + args.push("--sort", sort); + } + + if (isTruthyFlag(req.query.reverse)) { + args.push("--reverse"); + } + + const descContains = singleQueryValue(req.query.descContains); + if (descContains) { + args.push("--desc-contains", descContains); + } + + const notesContains = singleQueryValue(req.query.notesContains); + if (notesContains) { + args.push("--notes-contains", notesContains); + } + + const priorityMin = boundedInt(req.query.priorityMin, 0, 4); + if (priorityMin !== undefined) { + args.push("--priority-min", String(priorityMin)); + } + const priorityMax = boundedInt(req.query.priorityMax, 0, 4); + if (priorityMax !== undefined) { + args.push("--priority-max", String(priorityMax)); + } + + if (req.query.createdAfter !== undefined) { + const createdAfter = dateFlag(req.query.createdAfter); + if (!createdAfter) { + return res.status(400).json({ + success: false, + error: "createdAfter must be a YYYY-MM-DD or RFC3339 date", + }); + } + args.push("--created-after", createdAfter); + } + if (req.query.createdBefore !== undefined) { + const createdBefore = dateFlag(req.query.createdBefore); + if (!createdBefore) { + return res.status(400).json({ + success: false, + error: "createdBefore must be a YYYY-MM-DD or RFC3339 date", + }); + } + args.push("--created-before", createdBefore); + } + + if (isTruthyFlag(req.query.noAssignee)) { + args.push("--no-assignee"); + } + if (isTruthyFlag(req.query.noLabels)) { + args.push("--no-labels"); + } + + // Terminate flag parsing before the positional query. + args.push("--", query); + + try { + const { stdout } = await execFileAsync(beadsBin(), args); + res.json({ success: true, data: parseBeadsJson(stdout) ?? [] }); + } catch (err: unknown) { + res.status(500).json({ + success: false, + error: err instanceof Error ? err.message : "Failed to search issues", + }); + } +}); + +// GET /beads/tasks/:id/comments — list the discussion/audit comments on an issue. +// Backed by `bd comments --json`. Returns [] when the issue has none. +router.get("/tasks/:id/comments", async (req: Request, res: Response) => { + const id = cleanId(req.params.id); + if (!id) { + return res.status(400).json({ success: false, error: "task id is required" }); + } + + try { + const { stdout } = await execFileAsync(beadsBin(), ["comments", id, "--json"]); + res.json({ success: true, data: parseBeadsJson(stdout) ?? [] }); + } catch (err: unknown) { + const message = + err instanceof Error ? err.message : "Failed to list comments"; + // The CLI exits non-zero when the issue does not exist. Surface that as a + // 404 rather than a generic server fault so callers can distinguish. + const notFound = /not found/i.test(message); + res.status(notFound ? 404 : 500).json({ success: false, error: message }); + } +}); + +// POST /beads/tasks/:id/comments — attach a comment to an issue's audit trail. +// body: { text: string } +// For a fleet of agents, comments record why an agent did something and hand-off +// notes between agents. Backed by `bd comment --json`. +router.post("/tasks/:id/comments", async (req: Request, res: Response) => { + const id = cleanId(req.params.id); + if (!id) { + return res.status(400).json({ success: false, error: "task id is required" }); + } + + const body = req.body as { text?: unknown }; + const text = typeof body.text === "string" ? body.text.trim() : ""; + if (text.length === 0) { + return res + .status(400) + .json({ success: false, error: "text (comment body) is required" }); + } + + try { + const { stdout } = await execFileAsync(beadsBin(), [ + "comment", + id, + "--json", + "--", + text, + ]); + res.status(201).json({ success: true, data: parseBeadsJson(stdout) }); + } catch (err: unknown) { + const message = + err instanceof Error ? err.message : "Failed to add comment"; + const notFound = /not found/i.test(message); + res.status(notFound ? 404 : 500).json({ success: false, error: message }); + } +}); + +// POST /beads/tasks/:id/notes — append a durable working note to an issue. +// body: { text: string } +// The lightweight "leave a breadcrumb on this task" primitive: agents record +// progress/findings without overwriting the description. Backed by +// `bd note --json` (which appends to the issue's notes field). +router.post("/tasks/:id/notes", async (req: Request, res: Response) => { + const id = cleanId(req.params.id); + if (!id) { + return res.status(400).json({ success: false, error: "task id is required" }); + } + + const body = req.body as { text?: unknown }; + const text = typeof body.text === "string" ? body.text.trim() : ""; + if (text.length === 0) { + return res + .status(400) + .json({ success: false, error: "text (note body) is required" }); + } + + try { + const { stdout } = await execFileAsync(beadsBin(), [ + "note", + id, + "--json", + "--", + text, + ]); + res.status(201).json({ success: true, data: parseBeadsJson(stdout) }); + } catch (err: unknown) { + const message = err instanceof Error ? err.message : "Failed to add note"; + const notFound = /not found/i.test(message); + res.status(notFound ? 404 : 500).json({ success: false, error: message }); + } +}); + // GET /beads/tasks/:id — get a single task router.get("/tasks/:id", async (req: Request, res: Response) => { const { id } = req.params; diff --git a/aitimemachine/api-server/src/services/memoryService.ts b/aitimemachine/api-server/src/services/memoryService.ts index e28d0bdc..c5054a32 100644 --- a/aitimemachine/api-server/src/services/memoryService.ts +++ b/aitimemachine/api-server/src/services/memoryService.ts @@ -459,6 +459,74 @@ export async function compactIssues( return parseBeadsJson(stdout); } +// ============================================================================ +// Beads admin / health diagnostics (DAG self-check & repair) +// +// `bd doctor` is the bundled binary's health-check surface. It detects orphaned +// dependency references, duplicate issues, test pollution, git-conflict cruft, +// and (in --deep mode) full graph-integrity problems — and can auto-repair the +// fixable ones. For an always-on swarm of agents this keeps a corrupted task +// DAG from silently degrading. Thin execFile wrapper over `bd doctor --json`. +// ============================================================================ + +/** The focused diagnostic checks `bd doctor --check ` supports. */ +export const BEADS_DOCTOR_CHECKS = [ + "validate", + "pollution", + "artifacts", +] as const; +export type BeadsDoctorCheck = (typeof BEADS_DOCTOR_CHECKS)[number]; + +export interface BeadsDoctorOptions { + /** + * Run a single focused check (validate | pollution | artifacts) instead of + * the full installation sanity sweep. + */ + check?: BeadsDoctorCheck; + /** Apply auto-repairs for fixable validate findings (orphans, conflicts). */ + fix?: boolean; + /** Delete detected test pollution / stale artifacts (with check). */ + clean?: boolean; + /** Run the slower full graph-integrity validation. */ + deep?: boolean; +} + +/** + * Run `bd doctor` for DAG health diagnostics and optional repair. Returns the + * parsed `--json` report. Defaults to a read-only full sanity check; mutating + * behaviour requires an explicit `fix`/`clean` flag so an accidental call never + * alters the store. + * + * Note: `bd doctor` exits non-zero when it finds problems even though it still + * emits a useful JSON report, so we read the body tolerantly and only re-throw + * when no JSON was produced (a genuine invocation failure). + */ +export async function runBeadsDoctor( + options: BeadsDoctorOptions = {} +): Promise { + const args: string[] = ["doctor", "--json"]; + + if (options.check) { + args.push("--check", options.check); + } + if (options.fix) { + args.push("--fix"); + } + if (options.clean) { + args.push("--clean"); + } + if (options.deep) { + args.push("--deep"); + } + + const stdout = await execBeadsTolerant(args); + const parsed = parseBeadsJson(stdout); + if (parsed === null) { + throw new Error("bd doctor produced no report (invocation failed)"); + } + return parsed; +} + // ============================================================================ // Beads persistent memory (remember / recall / memories / forget) // diff --git a/aitimemachine/mcp/src/__tests__/tool-arg-aliasing.test.ts b/aitimemachine/mcp/src/__tests__/tool-arg-aliasing.test.ts new file mode 100644 index 00000000..c87c56c9 --- /dev/null +++ b/aitimemachine/mcp/src/__tests__/tool-arg-aliasing.test.ts @@ -0,0 +1,121 @@ +/** + * Unit tests for transport-level tool-call argument aliasing. + * + * Verifies hallucinated arg names are rewritten to canonical schema keys on + * incoming `tools/call` messages, that canonical keys always win, and that the + * transport hook is installed in a non-destructive, first-in-chain way. + */ + +import { describe, it, expect, vi } from 'vitest'; +import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js'; +import { + applyAliases, + normalizeToolCallArguments, + installTransportArgAliasing, + GLOBAL_ALIASES, + TOOL_ALIASES, +} from '../lib/tool-arg-aliasing.js'; + +function toolsCall(name: string, args: Record) { + return { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }; +} + +describe('applyAliases', () => { + it('rewrites a hallucinated alias to its canonical key', () => { + const args: Record = { question: 'how do I X?' }; + const rewrites = applyAliases(args, GLOBAL_ALIASES); + expect(args).toEqual({ query: 'how do I X?' }); + expect(rewrites).toEqual([{ from: 'question', to: 'query' }]); + }); + + it('does not clobber an existing canonical key', () => { + const args: Record = { query: 'real', question: 'echo' }; + applyAliases(args, GLOBAL_ALIASES); + // canonical wins; alias is left as-is (not promoted, not deleted) + expect(args.query).toBe('real'); + expect(args.question).toBe('echo'); + }); + + it('applies only the first matching alias', () => { + const args: Record = { userQuery: 'a', question: 'b' }; + applyAliases(args, GLOBAL_ALIASES); + expect(args.query).toBe('a'); + expect('userQuery' in args).toBe(false); + // the second alias is untouched once the canonical key is set + expect(args.question).toBe('b'); + }); +}); + +describe('normalizeToolCallArguments', () => { + it('applies global aliases on any tool', () => { + const msg = toolsCall('beads_ready', { userQuery: 'next?' }); + normalizeToolCallArguments(msg); + expect(msg.params.arguments).toEqual({ query: 'next?' }); + }); + + it('applies tool-scoped aliases only for the named tool', () => { + const msg = toolsCall('tm_docs_query', { libraryName: '/vercel/next.js' }); + normalizeToolCallArguments(msg); + expect(msg.params.arguments).toEqual({ libraryId: '/vercel/next.js' }); + expect(Object.keys(TOOL_ALIASES)).toContain('tm_docs_query'); + }); + + it('leaves libraryName untouched on tm_docs_resolve (canonical there)', () => { + const msg = toolsCall('tm_docs_resolve', { libraryName: 'next.js' }); + normalizeToolCallArguments(msg); + expect(msg.params.arguments).toEqual({ libraryName: 'next.js' }); + }); + + it('ignores non tools/call messages', () => { + const msg = { jsonrpc: '2.0', id: 2, method: 'initialize', params: { question: 'x' } }; + const rewrites = normalizeToolCallArguments(msg); + expect(rewrites).toEqual([]); + expect((msg.params as Record).question).toBe('x'); + }); + + it('is a no-op when arguments are missing or not an object', () => { + expect(normalizeToolCallArguments(toolsCall('beads_ready', undefined as never))).toEqual([]); + const arrMsg = { method: 'tools/call', params: { name: 'x', arguments: [1, 2] } }; + expect(normalizeToolCallArguments(arrMsg)).toEqual([]); + }); +}); + +describe('installTransportArgAliasing', () => { + it('rewrites the message before the pre-existing onmessage handler sees it', () => { + const seen: Array> = []; + const transport = { + onmessage: (m: unknown) => { + seen.push((m as { params: { arguments: Record } }).params.arguments); + }, + } as unknown as Transport; + + installTransportArgAliasing(transport); + + const msg = toolsCall('beads_ready', { question: 'what next?' }); + transport.onmessage?.(msg as never); + + // the chained handler observed the already-normalised arguments + expect(seen).toEqual([{ query: 'what next?' }]); + }); + + it('installs a handler even when none existed', () => { + const transport = {} as Transport; + installTransportArgAliasing(transport); + expect(typeof transport.onmessage).toBe('function'); + + const msg = toolsCall('beads_ready', { userQuery: 'go' }); + expect(() => transport.onmessage?.(msg as never)).not.toThrow(); + expect(msg.params.arguments).toEqual({ query: 'go' }); + }); + + it('does not throw when the chained handler is absent and message is unrelated', () => { + const transport = {} as Transport; + installTransportArgAliasing(transport); + const spy = vi.fn(); + transport.onmessage = ((m: unknown) => spy(m)) as Transport['onmessage']; + // re-install to chain over the spy + installTransportArgAliasing(transport); + transport.onmessage?.({ method: 'ping' } as never); + expect(spy).toHaveBeenCalledOnce(); + }); +}); diff --git a/aitimemachine/mcp/src/http-transport.ts b/aitimemachine/mcp/src/http-transport.ts index ea3d3bd6..9ce4ca77 100644 --- a/aitimemachine/mcp/src/http-transport.ts +++ b/aitimemachine/mcp/src/http-transport.ts @@ -25,6 +25,7 @@ import { type HttpAuthConfig, } from './lib/http-auth.js'; import { invokeMcpTool, resolveMcpToolFailure } from './lib/mcp-tool-call.js'; +import { installTransportArgAliasing } from './lib/tool-arg-aliasing.js'; import { attachRequestIdHeader, buildRequestContext, @@ -558,6 +559,10 @@ export async function startHttpTransport( const mcpTransport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); + // Rewrite hallucinated arg names to canonical schema keys before the SDK's + // Zod validation runs. MUST be installed before connect() so our onmessage + // hook sits first in the chain the SDK builds on top of it. + installTransportArgAliasing(mcpTransport); await mcpServer.connect(mcpTransport); app.all('/mcp', async (req, res) => { diff --git a/aitimemachine/mcp/src/index.ts b/aitimemachine/mcp/src/index.ts index d229afe3..b53668d3 100644 --- a/aitimemachine/mcp/src/index.ts +++ b/aitimemachine/mcp/src/index.ts @@ -17,6 +17,7 @@ import { getConfiguredButHiddenFamilies, } from './lib/tool-diagnostics.js'; import { buildHandshakeInstructions } from './lib/handshake-instructions.js'; +import { installTransportArgAliasing } from './lib/tool-arg-aliasing.js'; import type { ToolRuntimeContext, SessionServerLike } from './lib/tool-runtime.js'; import { registerCoreTools } from './tools/register-core-tools.js'; import { registerSessionTools } from './tools/register-session-tools.js'; @@ -361,6 +362,10 @@ async function main() { process.on('SIGTERM', handleShutdown); } else { const transport = new StdioServerTransport(); + // Rewrite hallucinated arg names to canonical schema keys before the SDK's + // Zod validation runs. MUST be installed before connect() so our onmessage + // hook sits first in the chain the SDK builds on top of it. + installTransportArgAliasing(transport); await server.connect(transport); console.error('Gitgram TimeMachine MCP server started (stdio)'); } diff --git a/aitimemachine/mcp/src/tools/register-beads-tools.ts b/aitimemachine/mcp/src/tools/register-beads-tools.ts index b7dd2a2e..ac857984 100644 --- a/aitimemachine/mcp/src/tools/register-beads-tools.ts +++ b/aitimemachine/mcp/src/tools/register-beads-tools.ts @@ -17,8 +17,13 @@ import { createToolRegistrar, defineTool, } from '../lib/tool-runtime.js'; -import { readOnlyAnnotations, mutatingAnnotations, idempotentMutationAnnotations } from '../lib/tool-annotations.js'; -import { jsonResponse } from '../lib/tool-responses.js'; +import { + readOnlyAnnotations, + mutatingAnnotations, + idempotentMutationAnnotations, + destructiveAnnotations, +} from '../lib/tool-annotations.js'; +import { jsonResponse, textResponse } from '../lib/tool-responses.js'; import { aitmApiRequest } from '../lib/aitm-api-client.js'; import { projectBeadsPayload, @@ -125,6 +130,37 @@ async function beadsPatch( return jsonResponse(projectBeadsPayload(data, projection)); } +/** + * Shape returned by GET /beads/prime: the AITM API server forwards `bd prime`'s + * markdown verbatim under data.content. Narrowed so the prime tool can extract + * the markdown without `any`. + */ +interface BeadsPrimeResponse { + readonly success?: boolean; + readonly data?: { + readonly format?: string; + readonly content?: string; + }; +} + +/** + * Fetch GET /beads/prime and return its markdown content as a plain text MCP + * response (not JSON-projected): the prime payload is human-/agent-readable + * markdown meant to be injected directly into a session's context. + */ +async function beadsGetPrime( + endpoint: string +): Promise> { + const data = await aitmApiRequest(LABEL, `/beads${endpoint}`); + const content = data?.data?.content; + if (typeof content === 'string' && content.length > 0) { + return textResponse(content); + } + // Fall back to the raw payload so an unexpected shape is still surfaced + // (e.g. an empty prime output) rather than silently returning nothing. + return textResponse(JSON.stringify(data, null, 2)); +} + async function beadsPut( endpoint: string, body?: unknown, @@ -178,17 +214,59 @@ export const registerBeadsTools = createToolRegistrar([ defineTool({ name: 'beads_create_task', - description: 'Create a new task in the Beads DAG task tracker with an optional list of dependency task IDs that must complete before this task can run.', + description: + 'Create a new task in the Beads DAG task tracker with the full issue model: title plus optional design/acceptance/notes context, an issue type, a priority, and dependency task IDs that must complete before this task can run. Capturing description/design/acceptance at creation time gives downstream agents a complete spec instead of a bare title.', schema: { title: z.string().describe('Human-readable title for the task'), deps: z.array(z.string()).optional().describe('Array of task IDs that this task depends on (must complete first)'), + description: z + .string() + .optional() + .describe('Free-form description of the task / problem statement.'), + design: z + .string() + .optional() + .describe('Design notes: the intended approach or implementation plan.'), + acceptanceCriteria: z + .string() + .optional() + .describe('Acceptance criteria: the conditions that define the task as done.'), + notes: z + .string() + .optional() + .describe('Additional working notes / context for the task.'), + externalRef: z + .string() + .optional() + .describe("External reference linking this task to another system (e.g. 'gh-9', 'jira-ABC')."), + priority: z + .number() + .int() + .min(0) + .max(4) + .optional() + .describe('Priority (0 = highest, 4 = lowest).'), + issueType: z + .enum(['bug', 'feature', 'task', 'epic', 'chore', 'decision']) + .optional() + .describe('The kind of issue (default: task).'), ...projectionSchema, }, annotations: mutatingAnnotations(), run: async (args) => beadsPost( '/tasks', - { title: args.title, deps: args.deps }, + { + title: args.title, + deps: args.deps, + description: args.description, + design: args.design, + acceptanceCriteria: args.acceptanceCriteria, + notes: args.notes, + externalRef: args.externalRef, + priority: args.priority, + issueType: args.issueType, + }, pickProjection(args) ), }), @@ -364,7 +442,7 @@ export const registerBeadsTools = createToolRegistrar([ defineTool({ name: 'beads_update_task', description: - 'Update editable fields of an existing Beads task: title, priority, assignee, status, and/or labels. Only the fields you provide are changed; at least one field is required.', + 'Update editable fields of an existing Beads task: core fields (title, priority, assignee, status, labels) plus the rich issue model (description, design, acceptanceCriteria, notes, externalRef, issueType). Only the fields you provide are changed; at least one field is required.', schema: { id: z.string().describe('The ID of the task to update'), title: z.string().optional().describe('New title for the task'), @@ -387,6 +465,30 @@ export const registerBeadsTools = createToolRegistrar([ .array(z.string()) .optional() .describe('Replace the full set of labels with this list'), + description: z + .string() + .optional() + .describe('New description / problem statement for the task.'), + design: z + .string() + .optional() + .describe('New design notes: the intended approach or implementation plan.'), + acceptanceCriteria: z + .string() + .optional() + .describe('New acceptance criteria defining when the task is done.'), + notes: z + .string() + .optional() + .describe('New working notes / context for the task.'), + externalRef: z + .string() + .optional() + .describe("New external reference (e.g. 'gh-9', 'jira-ABC')."), + issueType: z + .enum(['bug', 'feature', 'task', 'epic', 'chore', 'decision']) + .optional() + .describe('New issue type.'), ...projectionSchema, }, annotations: mutatingAnnotations(), @@ -399,6 +501,12 @@ export const registerBeadsTools = createToolRegistrar([ assignee: args.assignee, status: args.status, labels: args.labels, + description: args.description, + design: args.design, + acceptanceCriteria: args.acceptanceCriteria, + notes: args.notes, + externalRef: args.externalRef, + issueType: args.issueType, }, pickProjection(args) ), @@ -449,6 +557,150 @@ export const registerBeadsTools = createToolRegistrar([ pickProjection(args) ), }), + + defineTool({ + name: 'beads_prime', + description: + 'Bootstrap a fresh agent at session start with one call: returns the Beads workflow "prime" context as markdown — the current ready work plus the conventions and close protocol an agent should follow. This is the single highest-signal "orient me" primitive for an autonomous agent; inject the returned markdown directly into the session context instead of hand-assembling it.', + schema: { + mode: z + .enum(['full', 'mcp']) + .optional() + .describe( + 'Force the command reference style: "full" = the complete CLI command reference; "mcp" = minimal MCP-mode reminders. Defaults to auto-detection on the server.' + ), + stealth: z + .boolean() + .optional() + .describe('Stealth mode: omit git operations from the close protocol.'), + memoriesOnly: z + .boolean() + .optional() + .describe('Output only the persistent memories block (for compact / context-refresh hooks).'), + }, + annotations: readOnlyAnnotations(), + run: async (args) => + beadsGetPrime( + `/prime${buildQuery({ + mode: args.mode, + stealth: args.stealth ? '1' : undefined, + memoriesOnly: args.memoriesOnly ? '1' : undefined, + })}` + ), + }), + + defineTool({ + name: 'beads_deps_tree', + description: + 'Get the recursive, transitive dependency tree rooted at a Beads task in ONE call (vs the flat one-hop edge list). Lets an agent plan multi-step work by seeing every transitive blocker (or dependent) of a task. direction=down (default) returns the blockers the task depends on; up returns the dependents that depend on it; both returns both.', + schema: { + id: z.string().describe('The task ID to root the dependency tree at'), + direction: z + .enum(['up', 'down', 'both']) + .optional() + .describe( + 'down (default): transitive blockers this task depends on; up: transitive dependents; both: both directions.' + ), + maxDepth: z + .number() + .int() + .min(1) + .max(100) + .optional() + .describe('Bound the traversal depth (1-100).'), + }, + annotations: readOnlyAnnotations(), + run: async (args) => + beadsGet( + `/deps/tree${buildQuery({ + id: args.id, + direction: args.direction, + maxDepth: args.maxDepth, + })}` + ), + }), + + defineTool({ + name: 'beads_deps_cycles', + description: + 'Detect dependency cycles across the entire Beads DAG in one call. A cycle means the graph is broken (no valid execution order exists), so an orchestrator should run this to catch a corrupted DAG before scheduling autonomous work.', + schema: {}, + annotations: readOnlyAnnotations(), + run: async () => beadsGet('/deps/cycles'), + }), + + defineTool({ + name: 'beads_stale', + description: + 'Query Beads tasks that have gone quiet (no recent activity) so an orchestrator can re-prioritise or garbage-collect abandoned work. A cheap queue-hygiene primitive for long-running autonomous agents. Filter by a staleness threshold in days, a status, and a result limit.', + schema: { + days: z + .number() + .int() + .min(1) + .max(3650) + .optional() + .describe('Staleness threshold in days (default 30 on the server).'), + status: z + .enum(['open', 'in_progress', 'blocked', 'deferred']) + .optional() + .describe('Restrict to tasks in this status.'), + limit: z + .number() + .int() + .min(1) + .max(1000) + .optional() + .describe('Maximum number of stale tasks to return (1-1000).'), + ...listProjectionSchema, + }, + annotations: readOnlyAnnotations(), + run: async (args) => + beadsGet( + `/stale${buildQuery({ + days: args.days, + status: args.status, + limit: args.limit, + })}`, + pickProjection(args, 'stale tasks') + ), + }), + + defineTool({ + name: 'beads_admin', + description: + 'Run health diagnostics (and optional repair) on the Beads DAG: detect orphaned dependency references, duplicate issues, test pollution, and git-conflict cruft, keeping an always-on agent\'s task DB from silently degrading. READ-ONLY by default — set fix to auto-repair fixable findings, or clean to delete detected pollution/stale artifacts. Use deep for a slower full graph-integrity validation.', + schema: { + check: z + .enum(['validate', 'pollution', 'artifacts']) + .optional() + .describe( + 'Run a single focused check instead of the full sanity sweep: validate (data integrity: orphans/duplicates/conflicts), pollution (leaked test issues), or artifacts (stale files/cruft).' + ), + fix: z + .boolean() + .optional() + .describe('Auto-repair fixable validate findings (e.g. orphaned dependency refs). Mutating.'), + clean: z + .boolean() + .optional() + .describe('Delete detected test pollution / stale artifacts. Mutating.'), + deep: z + .boolean() + .optional() + .describe('Run the slower full graph-integrity validation (parent/dependency/epic consistency).'), + }, + // fix/clean delete or rewrite DAG records; mark destructive so clients can + // gate it. Idempotent: re-running after a repair is a no-op. + annotations: destructiveAnnotations(), + run: async (args) => + beadsPost('/admin', { + check: args.check, + fix: args.fix, + clean: args.clean, + deep: args.deep, + }), + }), ]); export default registerBeadsTools; diff --git a/gitgram/backend/prisma/schema.prisma b/gitgram/backend/prisma/schema.prisma index 3b4d4883..e2b1cf44 100644 --- a/gitgram/backend/prisma/schema.prisma +++ b/gitgram/backend/prisma/schema.prisma @@ -61,6 +61,8 @@ model Account { sentMessages Message[] @relation("MessageSender") receivedMessages Message[] @relation("MessageReceiver") + messageReactions MessageReaction[] + @@index([type]) @@index([username]) } @@ -581,6 +583,8 @@ model Message { receiver Account @relation("MessageReceiver", fields: [receiverId], references: [id], onDelete: Cascade) chat Chat? @relation(fields: [chatId], references: [id], onDelete: Cascade) + reactions MessageReaction[] + @@index([senderId]) @@index([receiverId]) @@index([chatId]) @@ -588,6 +592,25 @@ model Message { @@index([read]) } +// Emoji reactions on a direct/group message. A user may add at most one of each +// distinct emoji to a given message (enforced by the unique constraint), and the +// total number of distinct reactions per user per message is capped in the +// controller (mirroring Bluesky's per-message reaction limit). +model MessageReaction { + id String @id @default(cuid()) + messageId String + userId String + emoji String + createdAt DateTime @default(now()) + + message Message @relation(fields: [messageId], references: [id], onDelete: Cascade) + user Account @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@unique([messageId, userId, emoji]) + @@index([messageId]) + @@index([userId]) +} + // ============================================ // NOTIFICATIONS // ============================================ diff --git a/gitgram/backend/src/controllers/commentActionsController.ts b/gitgram/backend/src/controllers/commentActionsController.ts index 05d10f62..f0d6d649 100644 --- a/gitgram/backend/src/controllers/commentActionsController.ts +++ b/gitgram/backend/src/controllers/commentActionsController.ts @@ -3,7 +3,7 @@ import { AuthRequest } from '../middleware/auth'; import { prisma } from '../utils/prisma'; import logger from '../utils/logger'; import { createNotification } from '../services/notificationService'; -import { processMentionsForComment } from '../services/mentionService'; +import { processMentionsForComment, parseMentions } from '../services/mentionService'; import { asyncHandler, Errors, ApiError } from '../middleware/errorHandler'; import { invalidateCommentCache } from '../utils/commentCache'; @@ -94,9 +94,11 @@ export const updateComment = asyncHandler(async (req: AuthRequest, res: Response throw Errors.forbidden('Not authorized to edit this comment'); } + const newContent = content.trim(); + const updatedComment = await prisma.comment.update({ where: { id: commentId }, - data: { content: content.trim() }, + data: { content: newContent }, include: { user: { select: { id: true, username: true, avatar: true } @@ -104,6 +106,33 @@ export const updateComment = asyncHandler(async (req: AuthRequest, res: Response } }); + // Re-process @mentions on edit so newly-added mentions trigger notifications. + // Adapted from munia's isUpdate flow (delete-then-recreate). Since Gitgram's + // mention system is notification-based, we diff against the original content + // and only notify usernames that were NOT already present before the edit — + // avoiding duplicate notifications for users who were mentioned previously. + if (updatedComment.user?.username) { + const previousUsernames = new Set(parseMentions(comment.content)); + const addedUsernames = parseMentions(newContent).filter( + username => !previousUsernames.has(username) + ); + + if (addedUsernames.length > 0) { + try { + await processMentionsForComment( + addedUsernames.map(username => `@${username}`).join(' '), + comment.postId, + updatedComment.id, + userId, + updatedComment.user.username + ); + } catch (mentionError) { + // Log but don't fail the edit if mention processing fails + logger.error('Error processing mentions for edited comment:', mentionError); + } + } + } + res.json(updatedComment); }); diff --git a/gitgram/backend/src/controllers/messageController.ts b/gitgram/backend/src/controllers/messageController.ts index 46757cdb..e89b4e55 100644 --- a/gitgram/backend/src/controllers/messageController.ts +++ b/gitgram/backend/src/controllers/messageController.ts @@ -80,6 +80,9 @@ export const getMessages = asyncHandler(async (req: AuthRequest, res: Response) include: { sender: { select: { id: true, username: true, avatar: true } + }, + reactions: { + select: { emoji: true, userId: true } } }, orderBy: { createdAt: 'desc' }, @@ -87,9 +90,10 @@ export const getMessages = asyncHandler(async (req: AuthRequest, res: Response) take: Number(limit) }); - // Format messages with read receipt status + // Format messages with read receipt status and aggregated reactions const formattedMessages = messages.map(msg => ({ ...msg, + reactions: aggregateReactions(msg.reactions, userId), readAt: msg.readAt?.toISOString() || null, deliveredAt: msg.deliveredAt?.toISOString() || null, status: msg.read ? 'read' : (msg.deliveredAt ? 'delivered' : 'sent') @@ -630,6 +634,166 @@ export const getUnreadCount = asyncHandler(async (req: AuthRequest, res: Respons res.json({ unreadCount: count }); }); +// Allowed reaction emoji. Mirrors the Bluesky quick-reaction set plus a small +// curated extra; anything outside this list is rejected at the controller so we +// never persist arbitrary user-supplied strings as "emoji". +const ALLOWED_REACTIONS = ['❤️', '👍', '😆', '👀', '😢', '🎉', '🔥', '👎']; +// Maximum distinct emoji a single user may attach to one message. +const MAX_REACTIONS_PER_USER = 5; + +/** + * Assert the current user participates in the conversation the message belongs + * to (DM sender/receiver or a member of the group chat). Throws otherwise. + */ +async function assertMessageAccess( + message: { senderId: string; receiverId: string; chatId: string | null }, + userId: string, +): Promise { + if (message.senderId === userId || message.receiverId === userId) { + return; + } + if (message.chatId) { + const membership = await prisma.chatMember.findFirst({ + where: { chatId: message.chatId, userId }, + }); + if (membership) { + return; + } + } + throw Errors.forbidden('Not authorized to react to this message'); +} + +/** + * Shape returned to clients: each distinct emoji with its count and whether the + * current user has reacted with it. This is the aggregation Bluesky derives from + * its reaction list (getReactionInfo) computed server-side here instead. + */ +function aggregateReactions( + reactions: { emoji: string; userId: string }[], + currentUserId: string, +): { emoji: string; count: number; reactedByMe: boolean }[] { + const map = new Map(); + for (const r of reactions) { + const entry = map.get(r.emoji) ?? { count: 0, reactedByMe: false }; + entry.count += 1; + if (r.userId === currentUserId) { + entry.reactedByMe = true; + } + map.set(r.emoji, entry); + } + return Array.from(map.entries()).map(([emoji, { count, reactedByMe }]) => ({ + emoji, + count, + reactedByMe, + })); +} + +/** + * Add an emoji reaction to a message (idempotent per emoji/user). + * POST /api/v1/messages/:messageId/reactions { emoji } + */ +export const addReaction = asyncHandler(async (req: AuthRequest, res: Response) => { + const userId = req.userId!; + const { messageId } = req.params; + const { emoji } = req.body; + + if (!emoji || typeof emoji !== 'string' || !ALLOWED_REACTIONS.includes(emoji)) { + throw Errors.badRequest('Invalid reaction emoji'); + } + + const message = await prisma.message.findUnique({ where: { id: messageId } }); + if (!message) { + throw Errors.notFound('Message'); + } + + await assertMessageAccess(message, userId); + + // Enforce the per-user reaction cap, but allow re-adding an emoji the user + // already has (idempotent) so the cap can't lock a user out of a no-op. + const existing = await prisma.messageReaction.findUnique({ + where: { messageId_userId_emoji: { messageId, userId, emoji } }, + }); + + if (!existing) { + const distinctCount = await prisma.messageReaction.count({ + where: { messageId, userId }, + }); + if (distinctCount >= MAX_REACTIONS_PER_USER) { + throw Errors.badRequest( + `You can add at most ${MAX_REACTIONS_PER_USER} reactions to a message`, + ); + } + await prisma.messageReaction.create({ + data: { messageId, userId, emoji }, + }); + } + + const reactions = await prisma.messageReaction.findMany({ + where: { messageId }, + select: { emoji: true, userId: true }, + }); + const aggregated = aggregateReactions(reactions, userId); + + // Notify the other participant(s) so reactions appear in real time. + if (global.io) { + const payload = { messageId, userId, emoji, reactions: aggregated }; + if (message.receiverId) { + global.io.to(`user:${message.receiverId}`).emit('message:reaction', payload); + } + global.io.to(`user:${message.senderId}`).emit('message:reaction', payload); + if (message.chatId) { + global.io.to(`chat:${message.chatId}`).emit('message:reaction', payload); + } + } + + res.json({ messageId, reactions: aggregated }); +}); + +/** + * Remove an emoji reaction from a message. + * DELETE /api/v1/messages/:messageId/reactions/:emoji + */ +export const removeReaction = asyncHandler(async (req: AuthRequest, res: Response) => { + const userId = req.userId!; + const { messageId, emoji } = req.params; + + // Express has already URL-decoded the path param, so compare it directly + // against the allow-list rather than decoding again (which would mangle it). + if (!ALLOWED_REACTIONS.includes(emoji)) { + throw Errors.badRequest('Invalid reaction emoji'); + } + + const message = await prisma.message.findUnique({ where: { id: messageId } }); + if (!message) { + throw Errors.notFound('Message'); + } + + await assertMessageAccess(message, userId); + + await prisma.messageReaction.deleteMany({ + where: { messageId, userId, emoji }, + }); + + const reactions = await prisma.messageReaction.findMany({ + where: { messageId }, + select: { emoji: true, userId: true }, + }); + const aggregated = aggregateReactions(reactions, userId); + + if (global.io) { + const payload = { messageId, userId, emoji, removed: true, reactions: aggregated }; + if (message.receiverId) { + global.io.to(`user:${message.receiverId}`).emit('message:reaction', payload); + } + global.io.to(`user:${message.senderId}`).emit('message:reaction', payload); + if (message.chatId) { + global.io.to(`chat:${message.chatId}`).emit('message:reaction', payload); + } + } + + res.json({ messageId, reactions: aggregated }); +}); + /** * Search messages by content * GET /api/v1/messages/search?q=:query&limit=20 diff --git a/gitgram/backend/src/routes/messages.ts b/gitgram/backend/src/routes/messages.ts index 2dcb0f15..ec43cff0 100644 --- a/gitgram/backend/src/routes/messages.ts +++ b/gitgram/backend/src/routes/messages.ts @@ -143,6 +143,34 @@ const chatIdParam = [ .withMessage('Chat ID must be a string'), ]; +const addReactionValidator = [ + param('messageId') + .notEmpty() + .withMessage('Message ID is required') + .isString() + .withMessage('Message ID must be a string'), + body('emoji') + .notEmpty() + .withMessage('Emoji is required') + .isString() + .withMessage('Emoji must be a string') + .isLength({ min: 1, max: 16 }) + .withMessage('Emoji must be between 1 and 16 characters'), +]; + +const removeReactionValidator = [ + param('messageId') + .notEmpty() + .withMessage('Message ID is required') + .isString() + .withMessage('Message ID must be a string'), + param('emoji') + .notEmpty() + .withMessage('Emoji is required') + .isString() + .withMessage('Emoji must be a string'), +]; + /** * @swagger * /api/v1/messages: @@ -657,4 +685,76 @@ router.delete('/:messageId', authenticate, validate(messageIdParam), messageCont */ router.post('/:messageId/report', authenticate, interactionLimiter, userReportLimit, spamCheckReport, validate(reportMessageValidator), messageController.reportMessage); +/** + * @swagger + * /api/v1/messages/{messageId}/reactions: + * post: + * summary: Add an emoji reaction to a message + * tags: [Messages] + * security: + * - bearerAuth: [] + * parameters: + * - in: path + * name: messageId + * required: true + * schema: + * type: string + * requestBody: + * required: true + * content: + * application/json: + * schema: + * type: object + * required: + * - emoji + * properties: + * emoji: + * type: string + * description: One of the allowed reaction emoji + * responses: + * 200: + * description: Updated aggregated reactions for the message + * 400: + * description: Invalid emoji or reaction limit reached + * 401: + * description: Not authenticated + * 403: + * description: Not a participant in this conversation + * 404: + * description: Message not found + */ +router.post('/:messageId/reactions', authenticate, interactionLimiter, validate(addReactionValidator), messageController.addReaction); + +/** + * @swagger + * /api/v1/messages/{messageId}/reactions/{emoji}: + * delete: + * summary: Remove an emoji reaction from a message + * tags: [Messages] + * security: + * - bearerAuth: [] + * parameters: + * - in: path + * name: messageId + * required: true + * schema: + * type: string + * - in: path + * name: emoji + * required: true + * schema: + * type: string + * description: URL-encoded reaction emoji to remove + * responses: + * 200: + * description: Updated aggregated reactions for the message + * 401: + * description: Not authenticated + * 403: + * description: Not a participant in this conversation + * 404: + * description: Message not found + */ +router.delete('/:messageId/reactions/:emoji', authenticate, interactionLimiter, validate(removeReactionValidator), messageController.removeReaction); + export default router; diff --git a/gitgram/mobile/app/chat/[userId].tsx b/gitgram/mobile/app/chat/[userId].tsx index 96412629..21f24c49 100644 --- a/gitgram/mobile/app/chat/[userId].tsx +++ b/gitgram/mobile/app/chat/[userId].tsx @@ -10,18 +10,31 @@ import { Platform, Image, Animated, + type NativeSyntheticEvent, + type NativeScrollEvent, } from 'react-native'; -import { useLocalSearchParams, useRouter } from 'expo-router'; +import { useLocalSearchParams } from 'expo-router'; +import Icon from 'react-native-vector-icons/MaterialIcons'; import { Colors } from '../../constants/Colors'; -import { messageService } from '../../services/messageService'; +import { messageService, type MessageReaction } from '../../services/messageService'; import { initializeSocket, disconnectSocket } from '../../services/socketService'; import LoadingSpinner from '../../components/common/LoadingSpinner'; import EmptyState from '../../components/common/EmptyState'; +import { DateDivider } from '../../components/chat/DateDivider'; +import { SwipeToReply } from '../../components/chat/SwipeToReply'; +import { NewMessagesPill } from '../../components/chat/NewMessagesPill'; +import { EmojiReactionPicker } from '../../components/chat/EmojiReactionPicker'; import * as ImagePicker from 'expo-image-picker'; import { logger } from '../../utils/logger'; import { useHaptics } from '../../hooks/useHaptics'; const TYPING_DEBOUNCE_MS = 2000; // Stop typing after 2 seconds of no input +// How far from the bottom (offset 0 in an inverted list) the user can be before +// an incoming message shows the "new messages" pill instead of auto-scrolling. +const NEAR_BOTTOM_THRESHOLD = 80; +// Maximum distinct reactions a single user may add to one message (mirrors the +// backend cap). +const MAX_REACTIONS_PER_USER = 5; // Animated typing indicator component const TypingIndicator = () => { @@ -105,6 +118,7 @@ interface Message { recipientId: string; isRead: boolean; createdAt: string; + reactions?: MessageReaction[]; sender?: { id: string; username: string; @@ -112,19 +126,73 @@ interface Message { }; } +// A list row is either a real message or a day divider injected between days. +type ChatRow = + | { type: 'message'; message: Message } + | { type: 'divider'; id: string; date: string }; + +/** True when two timestamps fall on different calendar days. */ +function isDifferentDay(a: string, b: string): boolean { + const da = new Date(a); + const db = new Date(b); + return ( + da.getFullYear() !== db.getFullYear() || + da.getMonth() !== db.getMonth() || + da.getDate() !== db.getDate() + ); +} + +/** + * Builds the inverted FlatList data: messages newest-first, with a date divider + * inserted before the first message of each calendar day. Because the list is + * inverted, the divider must sit *after* the day's oldest message in array order + * so it renders visually above the day's messages. + */ +function buildRows(messagesNewestFirst: Message[]): ChatRow[] { + const rows: ChatRow[] = []; + for (let i = 0; i < messagesNewestFirst.length; i++) { + const msg = messagesNewestFirst[i]; + rows.push({ type: 'message', message: msg }); + const older = messagesNewestFirst[i + 1]; + const isDayBoundary = !older || isDifferentDay(msg.createdAt, older.createdAt); + if (isDayBoundary) { + rows.push({ + type: 'divider', + id: `divider-${msg.id}`, + date: msg.createdAt, + }); + } + } + return rows; +} + export default function ChatScreen() { const { userId } = useLocalSearchParams<{ userId: string }>(); - const router = useRouter(); const haptics = useHaptics(); const [messages, setMessages] = useState([]); const [loading, setLoading] = useState(true); const [messageText, setMessageText] = useState(''); const [sending, setSending] = useState(false); const [isOtherUserTyping, setIsOtherUserTyping] = useState(false); - const flatListRef = useRef(null); - const socketRef = useRef(null); - const typingTimeoutRef = useRef(null); + const [replyingTo, setReplyingTo] = useState(null); + const [reactionTarget, setReactionTarget] = useState(null); + const [showNewMessagesPill, setShowNewMessagesPill] = useState(false); + const flatListRef = useRef>(null); + const socketRef = useRef>(null); + const typingTimeoutRef = useRef | null>(null); const isTypingRef = useRef(false); + // Tracks whether the list is pinned near the newest message; used to decide + // between auto-scrolling and showing the "new messages" pill. + const isNearBottomRef = useRef(true); + + // Canonical inverted-list order is newest-first (index 0 = newest = the + // visual bottom). Sorting a copy by createdAt makes ordering robust whether a + // message arrived from the initial fetch (oldest-first) or a socket prepend + // (newest-first), and gives buildRows a stable basis for day dividers. + const orderedMessages = [...messages].sort( + (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(), + ); + const rows = buildRows(orderedMessages); // Emit typing start event const emitTypingStart = useCallback(() => { @@ -144,43 +212,51 @@ export default function ChatScreen() { // Handle typing with debounce const handleTypingDebounce = useCallback(() => { - // Emit typing start emitTypingStart(); - // Clear existing timeout if (typingTimeoutRef.current) { clearTimeout(typingTimeoutRef.current); } - // Set timeout to emit typing stop after 2 seconds of no typing typingTimeoutRef.current = setTimeout(() => { emitTypingStop(); }, TYPING_DEBOUNCE_MS); }, [emitTypingStart, emitTypingStop]); + // Apply a reaction update pushed from the server (or returned by our own + // mutation) to the matching message. + const applyReactions = useCallback( + (messageId: string, reactions: MessageReaction[]) => { + setMessages((prev) => + prev.map((msg) => (msg.id === messageId ? { ...msg, reactions } : msg)), + ); + }, + [], + ); + useEffect(() => { loadMessages(); - // Initialize socket connection const socket = initializeSocket(); socketRef.current = socket; if (socket) { - // Join user's room socket.emit('join', userId); - // Listen for new messages socket.on('message', (message: Message) => { if (message.senderId === userId || message.recipientId === userId) { setMessages((prev) => [message, ...prev]); - // Mark as read if it's from the other user if (message.senderId === userId) { messageService.markAsRead(message.id); + // An incoming message from the other user while the viewer is + // reading history should surface the pill, not yank the list. + if (!isNearBottomRef.current) { + setShowNewMessagesPill(true); + } } } }); - // Listen for message read receipts socket.on('messageRead', (messageId: string) => { setMessages((prev) => prev.map((msg) => @@ -189,21 +265,27 @@ export default function ChatScreen() { ); }); - // Listen for typing status from the other user socket.on('typing:status', (data: { userId: string; isTyping: boolean }) => { - // Only show typing indicator if it's from the user we're chatting with if (data.userId === userId) { setIsOtherUserTyping(data.isTyping); } }); + + // Real-time reaction updates from other participants. + socket.on( + 'message:reaction', + (data: { messageId: string; reactions: MessageReaction[] }) => { + if (data.reactions) { + applyReactions(data.messageId, data.reactions); + } + }, + ); } return () => { - // Clean up typing timeout if (typingTimeoutRef.current) { clearTimeout(typingTimeoutRef.current); } - // Emit typing stop when leaving the chat if (socketRef.current && isTypingRef.current) { socketRef.current.emit('typing:stop', { recipientId: userId }); } @@ -212,6 +294,7 @@ export default function ChatScreen() { disconnectSocket(); } }; + // eslint-disable-next-line react-hooks/exhaustive-deps }, [userId]); const loadMessages = async () => { @@ -219,13 +302,18 @@ export default function ChatScreen() { setLoading(true); const response = await messageService.getMessages(userId); setMessages(response.messages || []); - } catch (error) { + } catch { // Error handled silently } finally { setLoading(false); } }; + const scrollToBottom = useCallback(() => { + flatListRef.current?.scrollToOffset({ offset: 0, animated: true }); + setShowNewMessagesPill(false); + }, []); + const handleSend = async () => { if (!messageText.trim() && !sending) return; @@ -233,7 +321,6 @@ export default function ChatScreen() { setSending(true); haptics('Light'); - // Stop typing indicator when sending emitTypingStop(); if (typingTimeoutRef.current) { clearTimeout(typingTimeoutRef.current); @@ -242,10 +329,8 @@ export default function ChatScreen() { const response = await messageService.sendMessage(userId, messageText.trim()); - // Add message to list optimistically setMessages((prev) => [response.message, ...prev]); - // Emit via socket if (socketRef.current) { socketRef.current.emit('sendMessage', { recipientId: userId, @@ -254,7 +339,10 @@ export default function ChatScreen() { } setMessageText(''); - } catch (error) { + // Sending our own message always returns focus to the newest message. + setReplyingTo(null); + scrollToBottom(); + } catch { // Error handled silently } finally { setSending(false); @@ -281,7 +369,6 @@ export default function ChatScreen() { const ext = asset.uri.split('.').pop() || (isVideo ? 'mp4' : 'jpg'); const mimeType = asset.mimeType || (isVideo ? `video/${ext}` : `image/${ext}`); - // recipientId/content are appended by messageService.sendMessage. const formData = new FormData(); formData.append('media', { uri: asset.uri, @@ -299,6 +386,7 @@ export default function ChatScreen() { mediaUrl: response.message.mediaUrl, }); } + scrollToBottom(); } } catch (error) { logger.error('Send media error:', error); @@ -307,9 +395,66 @@ export default function ChatScreen() { } }; - const renderMessage = ({ item }: { item: Message }) => { + const handleReply = useCallback((message: Message) => { + haptics('Light'); + setReplyingTo(message); + }, [haptics]); + + // Toggle a reaction: remove it if the user already reacted with this emoji, + // otherwise add it. The server returns the authoritative aggregated list. + const handleSelectReaction = useCallback( + async (emoji: string) => { + const target = reactionTarget; + if (!target) return; + const alreadyReacted = target.reactions?.some( + (r) => r.emoji === emoji && r.reactedByMe, + ); + try { + const response = alreadyReacted + ? await messageService.removeReaction(target.id, emoji) + : await messageService.addReaction(target.id, emoji); + applyReactions(target.id, response.reactions); + } catch (error) { + logger.error('Reaction error:', error); + } + }, + [reactionTarget, applyReactions], + ); + + // Tapping an existing reaction chip toggles the current user's reaction. + const handleToggleReactionChip = useCallback( + async (message: Message, reaction: MessageReaction) => { + haptics('Light'); + try { + const response = reaction.reactedByMe + ? await messageService.removeReaction(message.id, reaction.emoji) + : await messageService.addReaction(message.id, reaction.emoji); + applyReactions(message.id, response.reactions); + } catch (error) { + logger.error('Reaction error:', error); + } + }, + [haptics, applyReactions], + ); + + // Track whether the user is near the newest message so incoming socket + // messages know whether to auto-scroll or show the pill. + const handleScroll = useCallback( + (event: NativeSyntheticEvent) => { + const offset = event.nativeEvent.contentOffset.y; + const nearBottom = offset <= NEAR_BOTTOM_THRESHOLD; + isNearBottomRef.current = nearBottom; + if (nearBottom && showNewMessagesPill) { + setShowNewMessagesPill(false); + } + }, + [showNewMessagesPill], + ); + + const renderMessageBubble = (item: Message) => { const isSent = item.senderId !== userId; const isCurrentUser = !isSent; + const reactions = item.reactions ?? []; return ( + {reactions.length > 0 && ( + + {reactions.map((reaction) => ( + handleToggleReactionChip(item, reaction)} + style={[ + styles.reactionChip, + reaction.reactedByMe && styles.reactionChipActive, + ]} + accessibilityRole="button" + accessibilityLabel={`${reaction.emoji} ${reaction.count} reaction${ + reaction.count === 1 ? '' : 's' + }`} + > + {reaction.emoji} + {reaction.count > 1 && ( + {reaction.count} + )} + + ))} + + )} ); }; + const renderRow = ({ item }: { item: ChatRow }) => { + if (item.type === 'divider') { + return ; + } + const message = item.message; + const isFromSelf = message.senderId !== userId; + // Optimistic/temporary messages can have a generated id; still allow swipe. + return ( + handleReply(message)}> + { + haptics('Medium'); + setReactionTarget(message); + }} + delayLongPress={300} + > + {renderMessageBubble(message)} + + + ); + }; + + const myReactedEmojis = + reactionTarget?.reactions + ?.filter((r) => r.reactedByMe) + .map((r) => r.emoji) ?? []; + const reactionLimitReached = myReactedEmojis.length >= MAX_REACTIONS_PER_USER; + if (loading) { return ; } @@ -351,22 +548,53 @@ export default function ChatScreen() { behavior={Platform.OS === 'ios' ? 'padding' : 'height'} keyboardVerticalOffset={90} > - item.id} - inverted - ListEmptyComponent={ - - } - ListHeaderComponent={isOtherUserTyping ? : null} - onContentSizeChange={() => flatListRef.current?.scrollToOffset({ offset: 0 })} - /> + + + item.type === 'divider' ? item.id : item.message.id + } + inverted + onScroll={handleScroll} + scrollEventThrottle={16} + ListEmptyComponent={ + + } + ListHeaderComponent={isOtherUserTyping ? : null} + /> + + + + {replyingTo && ( + + + + + Replying to{' '} + {replyingTo.senderId === userId + ? replyingTo.sender?.username || 'them' + : 'yourself'} + + + {replyingTo.content || (replyingTo.mediaUrl ? 'Media' : '')} + + + setReplyingTo(null)} + accessibilityRole="button" + accessibilityLabel="Cancel reply" + style={styles.replyBannerClose} + > + + + + )} @@ -396,6 +624,14 @@ export default function ChatScreen() { Send + + setReactionTarget(null)} + onSelect={handleSelectReaction} + /> ); } @@ -405,19 +641,21 @@ const styles = StyleSheet.create({ flex: 1, backgroundColor: Colors.background, }, + listWrap: { + flex: 1, + position: 'relative', + }, messageContainer: { - maxWidth: '75%', + maxWidth: '100%', marginVertical: 4, marginHorizontal: 16, padding: 12, borderRadius: 16, }, sentMessage: { - alignSelf: 'flex-end', backgroundColor: Colors.accent, }, receivedMessage: { - alignSelf: 'flex-start', backgroundColor: Colors.surface, }, messageText: { @@ -441,6 +679,68 @@ const styles = StyleSheet.create({ marginTop: 4, alignSelf: 'flex-end', }, + reactionRow: { + flexDirection: 'row', + flexWrap: 'wrap', + gap: 4, + marginTop: 6, + }, + reactionChip: { + flexDirection: 'row', + alignItems: 'center', + gap: 3, + paddingHorizontal: 8, + paddingVertical: 3, + borderRadius: 12, + backgroundColor: Colors.background, + borderWidth: 1, + borderColor: Colors.border, + }, + reactionChipActive: { + backgroundColor: `${Colors.primary}33`, + borderColor: Colors.primary, + }, + reactionEmoji: { + fontSize: 13, + }, + reactionCount: { + fontSize: 12, + color: Colors.text, + fontWeight: '600', + }, + replyBanner: { + flexDirection: 'row', + alignItems: 'center', + paddingHorizontal: 16, + paddingVertical: 8, + backgroundColor: Colors.surface, + borderTopWidth: 1, + borderTopColor: Colors.border, + }, + replyBannerBar: { + width: 3, + alignSelf: 'stretch', + borderRadius: 2, + backgroundColor: Colors.accent, + marginRight: 10, + }, + replyBannerContent: { + flex: 1, + }, + replyBannerLabel: { + color: Colors.accent, + fontSize: 12, + fontWeight: '700', + marginBottom: 2, + }, + replyBannerText: { + color: Colors.textSecondary, + fontSize: 13, + }, + replyBannerClose: { + padding: 6, + marginLeft: 8, + }, inputContainer: { flexDirection: 'row', padding: 12, diff --git a/gitgram/mobile/components/Post/PostCard.tsx b/gitgram/mobile/components/Post/PostCard.tsx index 30767b25..854bf51a 100644 --- a/gitgram/mobile/components/Post/PostCard.tsx +++ b/gitgram/mobile/components/Post/PostCard.tsx @@ -23,6 +23,7 @@ import RichContent from '../common/RichContent'; import LikeBounceAnimation, { LikeBounceAnimationHandle, } from '../common/LikeBounceAnimation'; +import CountWheel from '../common/CountWheel'; import { useLightbox } from '../common/Lightbox'; const DOUBLE_PRESS_DELAY = 300; @@ -67,6 +68,9 @@ export default function PostCard({ post, onLike, showFullContent = false, onHide const { showToast, ToastComponent } = useToast(); const [isLiked, setIsLiked] = useState(post.isLiked); const [likesCount, setLikesCount] = useState(post.likesCount); + // Stays false until the viewer toggles the like at least once, so the count + // wheel never animates on first mount (matching Bluesky's behaviour). + const [hasToggledLike, setHasToggledLike] = useState(false); const [loading, setLoading] = useState(false); const [showOptionsModal, setShowOptionsModal] = useState(false); const [showReportModal, setShowReportModal] = useState(false); @@ -145,6 +149,7 @@ export default function PostCard({ post, onLike, showFullContent = false, onHide const previousIsLiked = isLiked; const previousLikesCount = likesCount; + setHasToggledLike(true); setIsLiked(!isLiked); setLikesCount(prev => !previousIsLiked ? prev + 1 : prev - 1); setLoading(true); @@ -278,7 +283,26 @@ export default function PostCard({ post, onLike, showFullContent = false, onHide {/* Engagement & Info */} - {likesCount.toLocaleString()} likes + + {likesCount > 0 ? ( + <> + ( + {count.toLocaleString()} + )} + /> + + {' '} + {likesCount === 1 ? 'like' : 'likes'} + + + ) : ( + 0 likes + )} + {post.content && ( {post.user.username} @@ -424,11 +448,15 @@ const styles = StyleSheet.create({ paddingTop: 4, paddingBottom: 8, }, + likesRow: { + flexDirection: 'row', + alignItems: 'center', + marginBottom: 8, + }, likesText: { color: Colors.text, fontSize: 14, fontWeight: 'bold', - marginBottom: 8, }, captionContainer: { flexDirection: 'row', diff --git a/gitgram/mobile/components/chat/DateDivider.tsx b/gitgram/mobile/components/chat/DateDivider.tsx new file mode 100644 index 00000000..31b5cfdf --- /dev/null +++ b/gitgram/mobile/components/chat/DateDivider.tsx @@ -0,0 +1,97 @@ +import React, { memo } from 'react'; +import { StyleSheet, Text, View } from 'react-native'; +import { isSameDay, subDays } from 'date-fns'; + +import { Colors } from '../../constants/Colors'; + +/** + * Day separator for the conversation timeline, ported from Bluesky's + * `src/components/dms/DateDivider.tsx`. + * + * Bluesky's original leans on `i18n.date` (Lingui) and ALF atoms; this product + * uses neither, so the date logic is reimplemented with `date-fns` plus + * `Intl.DateTimeFormat` (already available in the Hermes/RN runtime) and the + * GitHub `Colors` palette. The opinionated ruleset is preserved verbatim: + * + * - Same calendar day -> "Today" + * - Previous day -> "Yesterday" + * - Within a week -> weekday only ("Monday") + * - Older, same year -> "Mon, January 5" + * - Older, prior year -> "Mon, January 5, 2024" + * + * The time of the first message of the day is appended ("Today at 2:14 PM") so + * the divider doubles as the per-day timestamp anchor in the inverted list. + */ +interface DateDividerProps { + /** ISO 8601 timestamp (or anything `new Date()` accepts) for the day. */ + date: string; +} + +function formatTime(timestamp: Date): string { + return new Intl.DateTimeFormat(undefined, { + hour: 'numeric', + minute: '2-digit', + }).format(timestamp); +} + +function formatDate(timestamp: Date): string { + const today = new Date(); + const yesterday = subDays(today, 1); + const oneWeekAgo = subDays(today, 7); + + if (isSameDay(today, timestamp)) { + return 'Today'; + } + if (isSameDay(yesterday, timestamp)) { + return 'Yesterday'; + } + + if (timestamp < oneWeekAgo) { + const sameYear = timestamp.getFullYear() === today.getFullYear(); + return new Intl.DateTimeFormat(undefined, { + weekday: 'short', + month: 'long', + day: 'numeric', + ...(sameYear ? {} : { year: 'numeric' }), + }).format(timestamp); + } + + return new Intl.DateTimeFormat(undefined, { weekday: 'long' }).format( + timestamp, + ); +} + +function DateDividerComponent({ date }: DateDividerProps) { + const timestamp = new Date(date); + + // Guard against malformed timestamps so a single bad message can never crash + // the whole conversation list. + if (Number.isNaN(timestamp.getTime())) { + return null; + } + + return ( + + + {formatDate(timestamp)} at {formatTime(timestamp)} + + + ); +} + +export const DateDivider = memo(DateDividerComponent); + +const styles = StyleSheet.create({ + container: { + width: '100%', + marginTop: 12, + paddingHorizontal: 16, + }, + text: { + fontSize: 12, + textAlign: 'center', + color: Colors.textSecondary, + }, +}); + +export default DateDivider; diff --git a/gitgram/mobile/components/chat/EmojiReactionPicker.tsx b/gitgram/mobile/components/chat/EmojiReactionPicker.tsx new file mode 100644 index 00000000..fbacaf20 --- /dev/null +++ b/gitgram/mobile/components/chat/EmojiReactionPicker.tsx @@ -0,0 +1,139 @@ +import React from 'react'; +import { + Modal, + Pressable, + StyleSheet, + Text, + TouchableOpacity, + View, +} from 'react-native'; + +import { Colors } from '../../constants/Colors'; +import { useHaptics } from '../../hooks/useHaptics'; + +/** + * Quick emoji reaction picker for a message, ported from Bluesky's + * `src/components/dms/EmojiReactionPicker.tsx`. + * + * Bluesky's original renders inside its ALF `ContextMenu` and is positioned + * relative to the long-pressed message. This product has no ContextMenu + * primitive, so the picker is reimplemented as a centered, dismiss-on-backdrop + * `Modal` (the same pattern as `PostOptionsModal`) using the GitHub `Colors` + * palette. The quick-reaction emoji set matches Bluesky's. + * + * Selecting an emoji that the user has already applied toggles it off, so the + * picker doubles as a remove affordance for existing reactions. + */ +export const REACTION_EMOJIS = ['❤️', '👍', '😆', '👀', '😢'] as const; + +interface EmojiReactionPickerProps { + visible: boolean; + /** Emoji the current user has already reacted with (rendered highlighted). */ + reactedEmojis?: string[]; + /** Whether the user has hit the per-message reaction cap (disables new ones). */ + limitReached?: boolean; + onClose: () => void; + /** Called with the chosen emoji; the caller performs add/remove. */ + onSelect: (emoji: string) => void; +} + +export function EmojiReactionPicker({ + visible, + reactedEmojis = [], + limitReached = false, + onClose, + onSelect, +}: EmojiReactionPickerProps) { + const haptics = useHaptics(); + + const handleSelect = (emoji: string) => { + haptics('Light'); + onSelect(emoji); + onClose(); + }; + + return ( + + + {/* Stop propagation so taps on the tray don't dismiss it. */} + {}}> + {REACTION_EMOJIS.map((emoji) => { + const alreadyReacted = reactedEmojis.includes(emoji); + // When at the cap, only allow toggling emoji already applied. + const disabled = limitReached && !alreadyReacted; + return ( + handleSelect(emoji)} + disabled={disabled} + accessibilityRole="button" + accessibilityState={{ selected: alreadyReacted, disabled }} + accessibilityLabel={ + alreadyReacted ? `Remove ${emoji} reaction` : `React with ${emoji}` + } + style={[ + styles.emojiButton, + alreadyReacted && styles.emojiButtonActive, + disabled && styles.emojiButtonDisabled, + ]} + > + {emoji} + + ); + })} + + + + ); +} + +const styles = StyleSheet.create({ + backdrop: { + flex: 1, + backgroundColor: 'rgba(0, 0, 0, 0.4)', + justifyContent: 'center', + alignItems: 'center', + }, + tray: { + flexDirection: 'row', + gap: 6, + padding: 8, + borderRadius: 32, + backgroundColor: Colors.surface, + borderWidth: 1, + borderColor: Colors.border, + shadowColor: '#000', + shadowOpacity: 0.4, + shadowRadius: 12, + shadowOffset: { width: 0, height: 4 }, + elevation: 8, + }, + emojiButton: { + width: 48, + height: 48, + borderRadius: 24, + alignItems: 'center', + justifyContent: 'center', + }, + emojiButtonActive: { + backgroundColor: `${Colors.primary}33`, + }, + emojiButtonDisabled: { + opacity: 0.4, + }, + emoji: { + fontSize: 28, + }, +}); + +export default EmojiReactionPicker; diff --git a/gitgram/mobile/components/chat/NewMessagesPill.tsx b/gitgram/mobile/components/chat/NewMessagesPill.tsx new file mode 100644 index 00000000..9d068baf --- /dev/null +++ b/gitgram/mobile/components/chat/NewMessagesPill.tsx @@ -0,0 +1,130 @@ +import React, { useEffect, useRef } from 'react'; +import { Animated, Pressable, StyleSheet } from 'react-native'; +import Icon from 'react-native-vector-icons/MaterialIcons'; + +import { Colors } from '../../constants/Colors'; +import { useHaptics } from '../../hooks/useHaptics'; + +/** + * Floating "new messages" pill for an inverted chat list, ported from Bluesky's + * `src/components/dms/NewMessagesPill.tsx`. + * + * Bluesky's original uses reanimated entering/exiting animations and ALF atoms. + * This product does not depend on reanimated, so the fade/scale is reimplemented + * on the React Native `Animated` API (matching `LoadLatestButton`) and styled + * with MaterialIcons + the GitHub `Colors` palette. + * + * Render it as an absolutely-positioned sibling of the chat `FlatList`. Because + * the list is `inverted`, offset 0 is the newest message ("the bottom"), so the + * pill points down and taps scroll back to offset 0. + */ +interface NewMessagesPillProps { + /** Whether the pill is shown (typically: scrolled away + new message arrived). */ + visible: boolean; + /** Scroll the inverted list back to the newest message. */ + onPress: () => void; +} + +export function NewMessagesPill({ visible, onPress }: NewMessagesPillProps) { + const haptics = useHaptics(); + const anim = useRef(new Animated.Value(visible ? 1 : 0)).current; + const scale = useRef(new Animated.Value(1)).current; + + useEffect(() => { + Animated.timing(anim, { + toValue: visible ? 1 : 0, + duration: 180, + useNativeDriver: true, + }).start(); + }, [visible, anim]); + + // Keep it unmounted while hidden so it never intercepts list touches. + if (!visible) { + return null; + } + + const handlePressIn = () => { + Animated.timing(scale, { + toValue: 1.075, + duration: 100, + useNativeDriver: true, + }).start(); + }; + + const handlePressOut = () => { + Animated.timing(scale, { + toValue: 1, + duration: 100, + useNativeDriver: true, + }).start(); + }; + + const handlePress = () => { + haptics('Light'); + onPress(); + }; + + return ( + + [styles.pill, pressed && styles.pillPressed]} + hitSlop={8} + > + + + + ); +} + +const styles = StyleSheet.create({ + wrapper: { + position: 'absolute', + bottom: 16, + left: 0, + right: 0, + alignItems: 'center', + zIndex: 20, + }, + pill: { + width: 40, + height: 40, + borderRadius: 20, + alignItems: 'center', + justifyContent: 'center', + backgroundColor: Colors.surface, + borderWidth: 1, + borderColor: Colors.border, + shadowColor: '#000', + shadowOpacity: 0.3, + shadowRadius: 6, + shadowOffset: { width: 0, height: 2 }, + elevation: 4, + }, + pillPressed: { + opacity: 0.85, + }, +}); + +export default NewMessagesPill; diff --git a/gitgram/mobile/components/chat/SwipeToReply.tsx b/gitgram/mobile/components/chat/SwipeToReply.tsx new file mode 100644 index 00000000..7c84be23 --- /dev/null +++ b/gitgram/mobile/components/chat/SwipeToReply.tsx @@ -0,0 +1,217 @@ +import React, { useMemo, useRef } from 'react'; +import { Animated, StyleSheet, View } from 'react-native'; +import { + PanGestureHandler, + type PanGestureHandlerGestureEvent, + type PanGestureHandlerStateChangeEvent, + State, +} from 'react-native-gesture-handler'; +import Icon from 'react-native-vector-icons/MaterialIcons'; + +import { Colors } from '../../constants/Colors'; +import { useHaptics } from '../../hooks/useHaptics'; + +/** + * Swipe a message bubble inward to reply, Signal/WhatsApp style. Ported from + * Bluesky's `src/components/dms/SwipeToReply.tsx`. + * + * Bluesky's original is built on reanimated worklets and ALF tokens. This + * product depends on neither, so the gesture is reimplemented on + * `react-native-gesture-handler`'s `PanGestureHandler` (already used elsewhere + * in the app) driving a React Native `Animated.Value`, styled with the GitHub + * `Colors` palette. The behaviour is preserved 1:1: + * + * - Self messages (right-aligned) swipe left; others' messages swipe right. + * - 1:1 movement up to the activation threshold, then exponentially decaying + * "resistance" toward a soft cap (`threshold + MAX_OVERSHOOT`). + * - Crossing the threshold fires a single medium haptic. + * - Releasing past the threshold triggers `onReply`; the bubble always springs + * home afterwards, even if the gesture is cancelled. + * + * A stationary reply icon sits in the gutter on the bubble's resting edge and + * fades/scales in as the bubble slides away from it. + */ +interface SwipeToReplyProps { + /** Right-aligned (current user's) bubble swipes left; others swipe right. */ + isFromSelf: boolean; + /** Fired once when a swipe is released past the activation threshold. */ + onReply: () => void; + /** Disable the gesture entirely (e.g. for pending/optimistic messages). */ + enabled?: boolean; + children: React.ReactNode; +} + +// Distance the bubble must travel before releasing fires a reply. +const ACTIVATION_THRESHOLD = 56; +// Past the activation point the bubble keeps moving with increasing resistance, +// asymptotically approaching this much extra travel. +const MAX_OVERSHOOT = 32; +const ICON_DIAMETER = 32; +// Bubble can occupy at most this share of the row, matching the chat styles. +const MESSAGE_BUBBLE_MAX_WIDTH_PCT = '75%'; + +/** + * 1:1 up to `ACTIVATION_THRESHOLD`, then exponentially diminishing travel so the + * bubble eases toward a soft cap rather than hitting a hard wall. + */ +function applyResistance(value: number): number { + const abs = Math.abs(value); + if (abs <= ACTIVATION_THRESHOLD) { + return value; + } + const sign = value < 0 ? -1 : 1; + const excess = abs - ACTIVATION_THRESHOLD; + return ( + sign * + (ACTIVATION_THRESHOLD + + MAX_OVERSHOOT * (1 - Math.exp(-excess / MAX_OVERSHOOT))) + ); +} + +export function SwipeToReply({ + isFromSelf, + onReply, + enabled = true, + children, +}: SwipeToReplyProps) { + const haptics = useHaptics(); + + const transX = useRef(new Animated.Value(0)).current; + // Tracks whether the haptic has fired for the current swipe so it only fires + // once per crossing of the threshold. + const hasHitRef = useRef(false); + + const onGestureEvent = useMemo( + () => + (event: PanGestureHandlerGestureEvent) => { + const { translationX } = event.nativeEvent; + // Arm only on the inward axis; the outward direction is clamped so the + // bubble can't be dragged off its own edge. + const directional = isFromSelf + ? Math.min(translationX, 0) + : Math.max(translationX, 0); + const resisted = applyResistance(directional); + transX.setValue(resisted); + + const pastThreshold = Math.abs(resisted) >= ACTIVATION_THRESHOLD; + if (pastThreshold && !hasHitRef.current) { + hasHitRef.current = true; + haptics('Medium'); + } else if (!pastThreshold && hasHitRef.current) { + hasHitRef.current = false; + } + }, + [isFromSelf, haptics, transX], + ); + + const onHandlerStateChange = useMemo( + () => + (event: PanGestureHandlerStateChangeEvent) => { + const { state, oldState } = event.nativeEvent; + // The gesture has just finished (END / FAIL / CANCELLED): decide whether + // to fire the reply, then always animate the bubble home. + if (oldState === State.ACTIVE) { + if (hasHitRef.current && state === State.END) { + onReply(); + } + hasHitRef.current = false; + Animated.timing(transX, { + toValue: 0, + duration: 200, + useNativeDriver: true, + }).start(); + } + }, + [onReply, transX], + ); + + const iconOpacity = transX.interpolate({ + inputRange: isFromSelf + ? [-ACTIVATION_THRESHOLD, 0] + : [0, ACTIVATION_THRESHOLD], + outputRange: isFromSelf ? [1, 0] : [0, 1], + extrapolate: 'clamp', + }); + + const iconScale = transX.interpolate({ + inputRange: isFromSelf + ? [-ACTIVATION_THRESHOLD, 0] + : [0, ACTIVATION_THRESHOLD], + outputRange: isFromSelf ? [1, 0.5] : [0.5, 1], + extrapolate: 'clamp', + }); + + return ( + + + + + + + + + + {children} + + + + ); +} + +const styles = StyleSheet.create({ + root: { + flex: 1, + position: 'relative', + justifyContent: 'center', + }, + iconGutter: { + position: 'absolute', + top: 0, + bottom: 0, + justifyContent: 'center', + }, + iconGutterLeft: { + left: 16, + }, + iconGutterRight: { + right: 16, + }, + iconCircle: { + width: ICON_DIAMETER, + height: ICON_DIAMETER, + borderRadius: ICON_DIAMETER / 2, + backgroundColor: Colors.muted, + alignItems: 'center', + justifyContent: 'center', + }, + bubbleWrap: { + maxWidth: MESSAGE_BUBBLE_MAX_WIDTH_PCT, + }, + selfEnd: { + alignSelf: 'flex-end', + }, + selfStart: { + alignSelf: 'flex-start', + }, +}); + +export default SwipeToReply; diff --git a/gitgram/mobile/components/common/CountWheel.tsx b/gitgram/mobile/components/common/CountWheel.tsx new file mode 100644 index 00000000..cabf2357 --- /dev/null +++ b/gitgram/mobile/components/common/CountWheel.tsx @@ -0,0 +1,163 @@ +import React, { useEffect, useRef, useState } from 'react'; +import { Animated, StyleSheet, View } from 'react-native'; + +/** + * Animated rolling count ("odometer") that pairs with a like button, ported from + * Bluesky's `src/lib/custom-animations/CountWheel.tsx`. + * + * Bluesky's original uses reanimated entering/exiting layout animations. This + * product does not depend on reanimated, so the roll is reimplemented on the + * React Native `Animated` API: when the count changes, the previous value slides + * out while the new value slides in, in the direction implied by the toggle + * (up when liking, down when unliking). The `decideShouldRoll` heuristic is + * preserved verbatim so big numbers (e.g. 1.2k) snap instead of rolling. + */ +interface CountWheelProps { + /** Current (already-updated) count. */ + count: number; + /** Whether the associated control is toggled on (e.g. liked). */ + isToggled: boolean; + /** False on first mount so the initial render does not animate. */ + hasBeenToggled: boolean; + /** Renders a single count value; lets the caller control text styling. */ + renderCount: (props: { count: number }) => React.ReactNode; +} + +const ROLL_DISTANCE = 18; +const DURATION = 300; + +/** + * Mirrors Bluesky's `decideShouldRoll`: roll for small/mid counts and at the + * boundaries of each hundred, otherwise snap (so "1.2k"-style values do not + * roll digit-by-digit). + */ +function decideShouldRoll(isToggled: boolean, count: number): boolean { + if (!isToggled && count === 1) { + return true; + } + if (count > 1 && count < 1000) { + return true; + } + if (count > 0) { + const mod = count % 100; + if (isToggled && mod === 0) { + return true; + } + if (!isToggled && mod === 99) { + return true; + } + } + return false; +} + +export function CountWheel({ + count, + isToggled, + hasBeenToggled, + renderCount, +}: CountWheelProps) { + const [displayCount, setDisplayCount] = useState(count); + const [prevCount, setPrevCount] = useState(count); + const [animating, setAnimating] = useState(false); + const progress = useRef(new Animated.Value(0)).current; + const prevIsToggled = useRef(isToggled); + + useEffect(() => { + // No animation on first mount, or when nothing meaningful changed. + if (count === displayCount) { + return; + } + + const toggledChanged = isToggled !== prevIsToggled.current; + const shouldRoll = + hasBeenToggled && toggledChanged && decideShouldRoll(isToggled, count); + prevIsToggled.current = isToggled; + + if (!shouldRoll) { + // Snap without animating. + setPrevCount(count); + setDisplayCount(count); + return; + } + + setPrevCount(displayCount); + setDisplayCount(count); + setAnimating(true); + progress.setValue(0); + Animated.timing(progress, { + toValue: 1, + duration: DURATION, + useNativeDriver: true, + }).start(({ finished }) => { + if (finished) { + setAnimating(false); + } + }); + }, [count, displayCount, hasBeenToggled, isToggled, progress]); + + if (displayCount <= 0) { + return null; + } + + // Liking rolls the new value up from below; unliking rolls it down from above. + const incoming = isToggled ? 1 : -1; + + const currentTranslate = progress.interpolate({ + inputRange: [0, 1], + outputRange: [incoming * ROLL_DISTANCE, 0], + }); + const currentOpacity = progress.interpolate({ + inputRange: [0, 1], + outputRange: [0, 1], + }); + const prevTranslate = progress.interpolate({ + inputRange: [0, 1], + outputRange: [0, -incoming * ROLL_DISTANCE], + }); + const prevOpacity = progress.interpolate({ + inputRange: [0, 1], + outputRange: [1, 0], + }); + + if (!animating) { + return {renderCount({ count: displayCount })}; + } + + return ( + + + {renderCount({ count: displayCount })} + + + {renderCount({ count: prevCount })} + + + ); +} + +const styles = StyleSheet.create({ + container: { + justifyContent: 'center', + overflow: 'hidden', + }, + previous: { + ...StyleSheet.absoluteFillObject, + justifyContent: 'center', + }, +}); + +export default CountWheel; diff --git a/gitgram/mobile/services/messageService.ts b/gitgram/mobile/services/messageService.ts index 6322780a..007a500a 100644 --- a/gitgram/mobile/services/messageService.ts +++ b/gitgram/mobile/services/messageService.ts @@ -1,5 +1,15 @@ import api from './api'; +/** + * Aggregated reaction for a single emoji on a message, as returned by the + * backend (count across all participants plus whether the current user reacted). + */ +export interface MessageReaction { + emoji: string; + count: number; + reactedByMe: boolean; +} + export const messageService = { getConversations: async () => { const response = await api.get('/messages/conversations'); @@ -41,6 +51,31 @@ export const messageService = { return response.data; }, + // Add an emoji reaction to a message. Returns the message's updated aggregated + // reactions (each distinct emoji with its count and whether the current user + // reacted). Backed by POST /messages/:messageId/reactions. + addReaction: async ( + messageId: string, + emoji: string, + ): Promise<{ messageId: string; reactions: MessageReaction[] }> => { + const response = await api.post(`/messages/${messageId}/reactions`, { + emoji, + }); + return response.data; + }, + + // Remove a previously-added emoji reaction. Backed by + // DELETE /messages/:messageId/reactions/:emoji. + removeReaction: async ( + messageId: string, + emoji: string, + ): Promise<{ messageId: string; reactions: MessageReaction[] }> => { + const response = await api.delete( + `/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`, + ); + return response.data; + }, + // Marks every message in a conversation as read. Backed by // POST /messages/conversations/:id/read. markConversationAsRead: async (conversationId: string) => {