From 2c63256fa2d574059a4f90187c1ca1ca626446a9 Mon Sep 17 00:00:00 2001 From: Tomas Dvorak Date: Tue, 13 Oct 2026 01:04:39 +0200 Subject: [PATCH 1/6] =?UTF-8?q?feat(ops):=20command-center=20intake=20?= =?UTF-8?q?=E2=80=94=20ops=20channels,=20structured=20meta,=20ops=20summar?= =?UTF-8?q?y?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inbound hooks now accept generic monitoring payloads (service/state/ latency_ms/level/env/release/url/fields/at) on any channel with intake_mode "ops". Payload lands in the new messages.meta jsonb column (capped at 8 KiB); tags stay for filtering. - GET /api/conversations/:id/ops: service board (worst-first), dense 30-day worst-state strip, kind counts, last event. Only health-readings (status/uptime/health/probe/heartbeat/monitor or kindless) feed the board — deploy/error/log kinds get cards and counts but never overwrite service state. - Web: OpsBar (board + strip) atop ops channels, OpsCard meta renderer distinct from chat rows, "ops" intake toggle + intake guide wiring. - MCP: meta on message payloads, meta arg on send_message, new ops_summary tool — all still gated by agents_blocked. - OpenAPI + generated client regenerated. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- api/openapi.yaml | 75 +++++- apps/web/src/components/OpsBar.tsx | 156 ++++++++++++ apps/web/src/components/OpsCard.tsx | 225 ++++++++++++++++++ apps/web/src/components/icons.tsx | 17 ++ .../features/conversations/Conversation.tsx | 10 + .../web/src/features/projects/ChannelPage.tsx | 66 ++++- .../web/src/features/projects/IntakeGuide.tsx | 169 +++++++++---- apps/web/src/lib/local.ts | 7 + db/migrations/0053_ops_intake.sql | 23 ++ db/queries/conversations.sql | 27 ++- db/queries/mcp.sql | 8 +- db/queries/saved.sql | 2 +- internal/conversations/conversations.go | 188 ++++++++++++++- internal/conversations/ops_test.go | 99 ++++++++ internal/db/conversations.sql.go | 68 +++++- internal/db/mcp.sql.go | 14 +- internal/db/models.go | 1 + internal/db/saved.sql.go | 4 +- internal/github/autofile.go | 2 +- internal/mcpserver/mcpserver.go | 53 ++++- internal/saved/saved.go | 2 +- internal/server/inbound_e2e_test.go | 97 ++++++++ internal/webhooks/inbound.go | 135 ++++++++++- internal/webhooks/webhooks_test.go | 62 ++++- packages/api-client/src/generated/schema.ts | 110 ++++++++- packages/api-client/src/index.ts | 8 +- 26 files changed, 1519 insertions(+), 109 deletions(-) create mode 100644 apps/web/src/components/OpsBar.tsx create mode 100644 apps/web/src/components/OpsCard.tsx create mode 100644 db/migrations/0053_ops_intake.sql create mode 100644 internal/conversations/ops_test.go diff --git a/api/openapi.yaml b/api/openapi.yaml index 6ba4036..5cce35b 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1633,7 +1633,7 @@ paths: patch: operationId: updateChannel summary: Rename a channel, toggle agent access, or set support-intake mode - description: "agents_blocked=true hides the channel from MCP agents entirely - its messages no longer appear in list_conversations, get_messages, send_message or search. intake_mode marks the channel as a support-intake surface: 'receive' accepts hook posts; 'chat' additionally lets the hook token pull channel messages (live support chat); '' disables intake." + description: "agents_blocked=true hides the channel from MCP agents entirely - its messages no longer appear in list_conversations, get_messages, send_message or search. intake_mode marks the channel as an intake surface: 'receive' accepts hook posts; 'chat' additionally lets the hook token pull channel messages (live support chat); 'ops' is a monitoring/command-center channel whose meta posts feed the ops summary; '' disables intake." tags: [conversations] parameters: - name: channelId @@ -1651,7 +1651,7 @@ paths: agents_blocked: { type: boolean } intake_mode: type: string - enum: ["", receive, chat] + enum: ["", receive, chat, ops] intake: type: boolean deprecated: true @@ -1755,6 +1755,57 @@ paths: items: { $ref: "#/components/schemas/Message" } "403": { $ref: "#/components/responses/Forbidden" } + /api/conversations/{conversationId}/ops: + get: + operationId: opsSummary + summary: Control-center summary over the channel's structured (meta) posts + description: >- + Folds meta-carrying messages into the ops surface: the latest state + per service (worst first), a dense 30-day strip of worst-state-per-day + buckets, per-kind counts over the 35-day window, and the newest event + pointer. Channels with intake_mode="ops" show this as their header; + any member can query it. + tags: [conversations] + parameters: [ { $ref: "#/components/parameters/ConversationId" } ] + responses: + "200": + description: Ops summary + content: + application/json: + schema: + type: object + required: [conversation_id, services, days, kinds] + properties: + conversation_id: { type: string, format: uuid } + services: + type: array + description: "Latest reported state per service, worst state first" + items: + type: object + properties: + service: { type: string } + state: { type: string } + latency_ms: { type: integer, format: int64 } + env: { type: string } + at: { type: string, format: date-time } + message_id: { type: string, format: uuid } + days: + type: array + description: "30 entries oldest→newest; 'worst' is the day's worst reported state ('no_data' when silent)" + items: + type: object + properties: + date: { type: string } + worst: { type: string } + events: { type: integer } + kinds: + type: object + additionalProperties: { type: integer } + description: "meta.kind → event count across the window" + last_event_at: { type: ["string", "null"], format: date-time } + last_message_id: { type: string, format: uuid } + "403": { $ref: "#/components/responses/Forbidden" } + /api/messages/{messageId}/forward: post: operationId: forwardMessage @@ -3770,7 +3821,19 @@ paths: from: { type: string, description: "external sender, e.g. 'Alice '" } subject: { type: string } key: { type: string, description: "Ticket key — first post opens a dedicated sub-chat; same-key posts join it" } - kind: { type: string, maxLength: 40, description: "Report type — free-form ('bug', 'feature', …). Overrides the hook's default kind; lands as a kind: tag and a `kind` label in the header" } + kind: { type: string, maxLength: 40, description: "Report type — free-form ('bug', 'feature', 'status', 'error', …). Overrides the hook's default kind; lands as a kind: tag and a `kind` label in the header" } + service: { type: string, maxLength: 120, description: "Ops: the monitored entity ('api', 'web', 'db'). Latest state per service feeds the ops summary" } + state: { type: string, maxLength: 24, description: "Ops: health state — up|ok|operational, degraded|warn, down|outage|critical, maintenance; unknown values render neutral" } + latency_ms: { type: integer, format: int64, description: "Ops: probe latency in milliseconds" } + level: { type: string, maxLength: 16, description: "Ops: log/error severity — debug|info|warn|error|fatal" } + env: { type: string, maxLength: 60, description: "Ops: environment tag (prod, staging, eu-1…)" } + release: { type: string, maxLength: 120, description: "Ops: version/commit the event belongs to" } + url: { type: string, maxLength: 500, description: "Ops: link back to the source (dashboard, run, trace)" } + fields: + type: object + additionalProperties: true + description: "Ops: arbitrary labelled values rendered on the message card (max 24 entries; values stringified to 200 chars)" + at: { type: string, format: date-time, description: "Ops: event timestamp; defaults to receipt time. Drives service-state ordering and day buckets" } attachments: type: array maxItems: 5 @@ -4626,6 +4689,10 @@ components: type: array description: "Free-form classification tags (frontend, backend, visual, mcp, …); lowercase slug, max 8" items: { type: string, pattern: "^[a-z0-9][a-z0-9-]{0,23}$" } + meta: + type: ["object", "null"] + additionalProperties: true + description: "Structured payload on ops/intake posts — kind, service, state, latency_ms, level, env, release, url, at, fields{} — rendered as a distinct card and aggregated by the ops summary" silent: type: boolean description: "Agent progress update posted without notifications — clients should not toast it" @@ -4756,7 +4823,7 @@ components: description: "True hides the channel from MCP agents entirely" intake_mode: type: string - enum: ["", receive, chat] + enum: ["", receive, chat, ops] description: "Support-intake mode: 'receive' accepts reports; 'chat' also exposes GET /api/hooks/{token}/messages so the platform can pull replies" intake: type: boolean diff --git a/apps/web/src/components/OpsBar.tsx b/apps/web/src/components/OpsBar.tsx new file mode 100644 index 0000000..20d0524 --- /dev/null +++ b/apps/web/src/components/OpsBar.tsx @@ -0,0 +1,156 @@ +import { createResource, createSignal, For, onCleanup, Show } from "solid-js"; +import type { OpsSummary } from "@relay/api-client"; +import { api } from "../lib/api"; +import { subscribe } from "../lib/events"; +import { opsDotCls, opsPillCls, stateTone } from "./OpsCard"; +import { PulseIcon } from "./icons"; + +// OpsBar — the control-center strip atop an intake_mode="ops" channel: +// live service pills (worst first), a 30-day uptime strip, per-kind event +// counts. Refetches when a meta post lands in this channel. + +type Day = { date?: string; worst?: string; events?: number }; +type Service = { + service?: string; + state?: string; + latency_ms?: number; + env?: string; + at?: string; + message_id?: string; +}; + +function dayTone(d: Day): string { + const w = (d.worst ?? "no_data").toLowerCase(); + if (w === "no_data") return "bg-faint/25"; + return `${opsDotCls(stateTone(w))} opacity-80`; +} + +function rel(ts?: string | null): string { + if (!ts) return ""; + const diff = Date.now() - new Date(ts).getTime(); + const m = Math.floor(diff / 60000); + if (m < 1) return "just now"; + if (m < 60) return `${m}m ago`; + const h = Math.floor(m / 60); + if (h < 48) return `${h}h ago`; + return `${Math.floor(h / 24)}d ago`; +} + +export function OpsBar(props: { + conversationId: string; + projectId: string; + onSetup?: () => void; +}) { + const [tick, setTick] = createSignal(0); + const unsub = subscribe((e) => { + if ( + e.type === "message.created" && + e.data?.conversation_id === props.conversationId + ) { + // meta posts shift the board; plain chatter doesn't + const msg = e.data.message as { meta?: unknown } | undefined; + if (msg?.meta) setTick((t) => t + 1); + } + if (e.type === "stream.resync") setTick((t) => t + 1); + }); + onCleanup(unsub); + const [summary] = createResource( + () => [props.conversationId, tick()] as const, + ([id]) => api.opsSummary(id).catch(() => null), + ); + + const data = () => (summary() ?? null) as OpsSummary | null; + const services = () => (data()?.services ?? []) as Service[]; + const days = () => (data()?.days ?? []) as Day[]; + const kinds = () => Object.entries(data()?.kinds ?? {}); + const empty = () => + summary.state === "ready" && services().length === 0 && days().every( + (d) => (d.events ?? 0) === 0, + ); + + return ( +
+
+ + + Ops + + + + last event {rel(data()?.last_event_at)} + + +
+ + {([k, n]) => ( + + {k} {n} + + )} + +
+
+ 0}> +
+ + {(s) => ( + + + {s.service} + + {s.state} + + + + {s.latency_ms}ms + + + + {s.env} + + + )} + +
+
+ 0}> +
+ + {(d) => ( +
+ )} + +
+ + +

+ No signals yet — point an inbound hook at this channel and POST{" "} + + {"{kind, service, state, latency_ms}"} + {" "} + from any monitor.{" "} + +

+
+
+ ); +} diff --git a/apps/web/src/components/OpsCard.tsx b/apps/web/src/components/OpsCard.tsx new file mode 100644 index 0000000..40188c0 --- /dev/null +++ b/apps/web/src/components/OpsCard.tsx @@ -0,0 +1,225 @@ +import { For, Show, type JSX } from "solid-js"; + +// Structured intake/ops payloads — inbound-hook posts can carry +// service/state/level/… (stored on messages.meta) and render as cards +// instead of plain text. The shapes are intentionally open: Relay knows a +// few well-known keys and passes the rest through `fields` untouched. + +export type OpsMeta = { + kind?: string; + service?: string; + state?: string; + latency_ms?: number; + level?: string; + env?: string; + release?: string; + url?: string; + at?: string; + fields?: Record; +}; + +export function opsMetaOf(msg: { meta?: unknown }): OpsMeta | null { + const m = msg.meta; + if (!m || typeof m !== "object" || Array.isArray(m)) return null; + const meta = m as Record; + // a lone kind tag isn't a card — need one real data point + const keys = Object.keys(meta).filter((k) => k !== "kind" && meta[k] != null); + if (keys.length === 0) return null; + return meta as OpsMeta; +} + +type Tone = "ok" | "warn" | "bad" | "idle" | "neutral"; + +export function stateTone(state?: string): Tone { + switch ((state ?? "").toLowerCase()) { + case "up": + case "ok": + case "operational": + case "healthy": + case "resolved": + return "ok"; + case "degraded": + case "warn": + case "warning": + return "warn"; + case "down": + case "outage": + case "critical": + case "crit": + case "fatal": + return "bad"; + case "maintenance": + return "idle"; + default: + return "neutral"; + } +} + +export function levelTone(level?: string): Tone { + switch ((level ?? "").toLowerCase()) { + case "debug": + case "trace": + return "idle"; + case "info": + case "notice": + return "neutral"; + case "warn": + case "warning": + return "warn"; + case "error": + case "fatal": + case "crit": + return "bad"; + default: + return "neutral"; + } +} + +// kind drives the card accent when no explicit state/level exists +function kindTone(kind?: string): Tone { + switch ((kind ?? "").toLowerCase()) { + case "status": + case "uptime": + case "metric": + return "ok"; + case "error": + case "incident": + case "outage": + case "alert": + case "bug": + return "bad"; + case "deploy": + case "ci": + case "release": + return "idle"; + case "log": + return "idle"; + default: + return "neutral"; + } +} + +export function opsTone(meta: OpsMeta): Tone { + if (meta.state) return stateTone(meta.state); + if (meta.level) return levelTone(meta.level); + return kindTone(meta.kind); +} + +const toneClasses: Record = { + ok: { + frame: "border-emerald-500/60 bg-emerald-500/5", + dot: "bg-emerald-500", + pill: "bg-emerald-500/15 text-emerald-600 dark:text-emerald-400", + }, + warn: { + frame: "border-amber-500/60 bg-amber-500/5", + dot: "bg-amber-500", + pill: "bg-amber-500/15 text-amber-600 dark:text-amber-400", + }, + bad: { + frame: "border-red-500/60 bg-red-500/5", + dot: "bg-red-500", + pill: "bg-red-500/15 text-red-600 dark:text-red-400", + }, + idle: { + frame: "border-sky-500/60 bg-sky-500/5", + dot: "bg-sky-500", + pill: "bg-sky-500/15 text-sky-600 dark:text-sky-400", + }, + neutral: { + frame: "border-faint/60 bg-hover/40", + dot: "bg-faint", + pill: "bg-hover text-muted", + }, +}; + +export function opsFrameCls(meta: OpsMeta): string { + return toneClasses[opsTone(meta)].frame; +} +export function opsDotCls(tone: Tone): string { + return toneClasses[tone].dot; +} +export function opsPillCls(tone: Tone): string { + return toneClasses[tone].pill; +} + +// OpsBanner — the structured head of a meta-carrying message: kind label, +// service, state/level pill, latency, env/release chips. The markdown body +// renders under it, unchanged. +export function OpsBanner(props: { meta: OpsMeta }): JSX.Element { + const tone = () => opsTone(props.meta); + const fieldEntries = () => + Object.entries(props.meta.fields ?? {}).slice(0, 8); + return ( +
+
+ + + {props.meta.kind} + + + + + {props.meta.service} + + + + + + {props.meta.state} + + + + + {props.meta.level} + + + + + {props.meta.latency_ms}ms + + + + + {props.meta.env} + + + + + {props.meta.release} + + + + {(u) => ( + + source ↗ + + )} + +
+ 0}> +
+ + {([k, v]) => ( + <> +
{k}
+
+ {v} +
+ + )} +
+
+
+
+ ); +} diff --git a/apps/web/src/components/icons.tsx b/apps/web/src/components/icons.tsx index 83b05cd..2806dc5 100644 --- a/apps/web/src/components/icons.tsx +++ b/apps/web/src/components/icons.tsx @@ -53,6 +53,23 @@ export function InboxIcon(props: IconProps): JSX.Element { ); } +export function PulseIcon(props: IconProps): JSX.Element { + return ( + + ); +} + export function MailIcon(props: IconProps): JSX.Element { return ( + + {(meta) => ( +
+ +
+ )} +
0}> {}); @@ -138,12 +140,16 @@ export default function ChannelPage() { text={ channel()?.intake_mode === "chat" ? "Support intake — live chat" - : "Support intake — receive only" + : channel()?.intake_mode === "ops" + ? "Ops channel — monitoring & alerts" + : "Support intake — receive only" } hint={ channel()?.intake_mode === "chat" ? "The platform posts reports and pulls replies — click for the setup guide" - : "The platform posts reports; replies stay in Relay — click for the setup guide" + : channel()?.intake_mode === "ops" + ? "Monitors, CI and error trackers POST structured events here — click for the setup guide" + : "The platform posts reports; replies stay in Relay — click for the setup guide" } > @@ -223,6 +238,30 @@ export default function ChannelPage() { + + + {(ch: Channel) => ( - +
+ + setGuideOpen(true)} + /> + + +
)}
diff --git a/apps/web/src/features/projects/IntakeGuide.tsx b/apps/web/src/features/projects/IntakeGuide.tsx index 591f1f5..96adc8e 100644 --- a/apps/web/src/features/projects/IntakeGuide.tsx +++ b/apps/web/src/features/projects/IntakeGuide.tsx @@ -139,6 +139,38 @@ channel — e.g. one channel per customer, kinds per report type.`, }; } +// opsSnippet — the structured payload ops channels aggregate. Same +// endpoint, richer shape: kind+service+state drive the status strip. +function opsSnippet(url: string): string { + return `HOOK_URL="${url}" + +# uptime probe (cron every minute) +curl -X POST "$HOOK_URL" \\ + -H "Content-Type: application/json" \\ + -d '{ + "kind": "status", + "service": "api", + "state": "up", // up | degraded | down | maintenance + "latency_ms": 84, + "env": "prod", + "url": "https://grafana.example.com/d/api", + "fields": { "region": "eu-central" } + }' + +# error tracker +curl -X POST "$HOOK_URL" \\ + -H "Content-Type: application/json" \\ + -d '{ + "kind": "error", + "service": "web", + "level": "error", // debug | info | warn | error | fatal + "release": "v0.9.11", + "subject": "TypeError: n.items is undefined", + "message": "stack trace or error detail here", + "key": "err-a91f" // same key -> one ticket thread per bug + }'`; +} + // chatRepliesSnippet — the pull path shown when the channel is in // live-chat mode. function chatRepliesSnippet(url: string): string { @@ -282,7 +314,7 @@ export function IntakeGuide(props: { channel: () => Channel | undefined; open: boolean; onOpenChange: (open: boolean) => void; - onMode: (mode: "" | "receive" | "chat") => void; + onMode: (mode: "" | "receive" | "chat" | "ops") => void; }) { const [hooks, { refetch }] = createResource( () => (props.open ? props.projectId : null), @@ -295,7 +327,9 @@ export function IntakeGuide(props: { const base = () => (net.serverUrl() || window.location.origin) + "/api/hooks/"; const url = () => freshUrl() || base() + ""; - const body = () => snippets(url())[tab()]; + const opsMode = () => props.channel()?.intake_mode === "ops"; + const body = () => + opsMode() && tab() === "curl" ? opsSnippet(url()) : snippets(url())[tab()]; return (
- Support intake — #{props.channel()?.name ?? "channel"} + {props.channel()?.intake_mode === "ops" + ? "Ops intake — " + : "Support intake — "} + #{props.channel()?.name ?? "channel"} - Anything that can POST JSON can file a report into this - channel. The path token is the credential — keep it - server-side.{" "} + {props.channel()?.intake_mode === "ops" + ? "Anything that can POST JSON can feed this board — uptime probes, error trackers, CI, deploy bots. Structured fields land on message.meta and drive the status strip above." + : "Anything that can POST JSON can file a report into this channel. "} + The path token is the credential — keep it server-side.{" "} {props.channel()?.intake_mode === "chat" ? "Live chat is on — the token can also pull replies." - : "Receive-only — replies stay inside Relay."} + : props.channel()?.intake_mode === "ops" + ? "Events flow in only — the board above is the output." + : "Receive-only — replies stay inside Relay."}
@@ -374,6 +414,27 @@ export function IntakeGuide(props: { {"{name, content_type, data: base64}"} + + service · state + + the monitored entity +{" "} + up | degraded | down | maintenance{" "} + — latest per service drives the board + + latency_ms · level + + probe latency · severity debug…fatal + + env · release · url · at + + environment, version, source link, event time + + fields + + {"{label: value}"} — any + key/value pairs, rendered on the card + + @@ -412,47 +473,71 @@ export function IntakeGuide(props: {
-

4 · Replies back to your product

+

+ {opsMode() + ? "4 · Reading the board" + : "4 · Replies back to your product"} +

- This channel is{" "} - receive-only — - replies stay inside Relay. Flip on{" "} - live chat in the - channel header to let the platform pull replies, or create - an outbound message.created{" "} - webhook (project → Webhooks) to push them. -

+ + This channel is{" "} + receive-only{" "} + — replies stay inside Relay. Flip on{" "} + live chat in + the channel header to let the platform pull replies, or + create an outbound{" "} + message.created webhook + (project → Webhooks) to push them. +

+ } + > +

+ Live chat is on.{" "} + Each ticket is a sub-chat under this channel — whatever + the team posts inside it is what the platform pulls. Poll + the same token at{" "} + + GET {""}/messages?key=…&after=… + {" "} + (120 reads/min) or subscribe an outbound webhook to{" "} + message.created for push. + Either way, skip posts tagged{" "} + "webhook" /{" "} + via_hook — forwarding them + back would echo-loop. +

+
+
+ + pull replies + + chatRepliesSnippet(url())} /> +
+
+                        {chatRepliesSnippet(url())}
+                      
+
+
} >

- Live chat is on.{" "} - Each ticket is a sub-chat under this channel — whatever - the team posts inside it is what the platform pulls. Poll - the same token at{" "} - - GET {""}/messages?key=…&after=… - {" "} - (120 reads/min) or subscribe an outbound webhook to{" "} - message.created for push. - Either way, skip posts tagged{" "} - "webhook" /{" "} - via_hook — forwarding them - back would echo-loop. + The strip above the channel is the product:{" "} + service pills track + the latest state per{" "} + service, the{" "} + 30-day bar colors + each day by its worst state, and every post renders as a + card in the feed. Agents can read the same summary via the{" "} + ops_summary MCP tool — or + block them entirely with the lock toggle in the header.{" "} + GET /api/conversations/<id>/ops{" "} + serves the raw aggregation for your own dashboards.

-
-
- - pull replies - - chatRepliesSnippet(url())} /> -
-
-                    {chatRepliesSnippet(url())}
-                  
-
diff --git a/apps/web/src/lib/local.ts b/apps/web/src/lib/local.ts index 8d3241e..0cbbdec 100644 --- a/apps/web/src/lib/local.ts +++ b/apps/web/src/lib/local.ts @@ -575,6 +575,13 @@ const impl = { .sort((a, b) => (b.pinned_at ?? "").localeCompare(a.pinned_at ?? "")) .map((m) => ({ ...m, thread: withReplyCount(threadOf(m.id)) })), }), + opsSummary: async (conversationId: string) => ({ + conversation_id: conversationId, + services: [], + days: [], + kinds: {}, + last_event_at: null, + }), forwardMessage: async (messageId: string, projectId: string) => { const src = findMessage(messageId); if (!src) notFound(); diff --git a/db/migrations/0053_ops_intake.sql b/db/migrations/0053_ops_intake.sql new file mode 100644 index 0000000..24e35a5 --- /dev/null +++ b/db/migrations/0053_ops_intake.sql @@ -0,0 +1,23 @@ +-- +goose Up +-- Ops/command-center intake: inbound-hook payloads can carry structured +-- data (service, state, latency_ms, level, env, fields…) that lands on +-- the message as jsonb `meta`. Null = a normal message; the web UI +-- renders meta-carrying posts as distinct cards and ops channels build +-- their status strip from them. +alter table messages add column meta jsonb; +create index messages_ops_meta_idx on messages (conversation_id, created_at) + where meta is not null; + +-- intake_mode gains 'ops': a receive-only channel whose surface is a +-- control-center view (service pills, uptime strip, alert feed). +alter table conversations drop constraint conversations_intake_mode_check; +alter table conversations add constraint conversations_intake_mode_check + check (intake_mode in ('', 'receive', 'chat', 'ops')); + +-- +goose Down +alter table conversations drop constraint conversations_intake_mode_check; +update conversations set intake_mode = 'receive' where intake_mode = 'ops'; +alter table conversations add constraint conversations_intake_mode_check + check (intake_mode in ('', 'receive', 'chat')); +drop index messages_ops_meta_idx; +alter table messages drop column meta; diff --git a/db/queries/conversations.sql b/db/queries/conversations.sql index 404ebee..32498cf 100644 --- a/db/queries/conversations.sql +++ b/db/queries/conversations.sql @@ -150,7 +150,7 @@ returning *; -- name: ListHookChannelMessages :many -- oldest-first pull for intake chat mode; narg(root) scopes to a ticket -- thread (root + its inline replies), narg(after) is the polling cursor -select m.id, m.conversation_id, m.body, m.tags, m.created_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.tags, m.meta, m.created_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name from messages m @@ -169,6 +169,17 @@ limit sqlc.arg(lim)::int; delete from conversations where id = $1 and kind = 'channel'; +-- name: OpsStatusEvents :many +-- ops-channel control center: every meta-carrying post in the window. +-- Service states, uptime day-buckets and counts derive in Go. +select m.id, m.created_at, m.meta +from messages m +where m.conversation_id = sqlc.arg(conversation_id) + and m.deleted_at is null + and m.meta is not null + and m.created_at > now() - interval '35 days' +order by m.created_at asc; + -- name: GetProjectForUser :one -- project row only when the caller is a member of its workspace select p.id, p.workspace_id, p.key, p.name, p.description, p.icon, p.color, @@ -180,7 +191,7 @@ where p.id = $1 and wm.user_id = $2; -- name: ListMessages :many -- newest-first page; $2 is an optional "older than message id" cursor, -- narg(tag) filters to messages carrying that tag -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -216,7 +227,7 @@ limit sqlc.arg(lim)::int; -- name: ListPinnedMessages :many -- pinned messages in one conversation, most recently pinned first -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -261,8 +272,8 @@ returning id, conversation_id; -- name: CreateMessage :one -- client_msg_id dedupes offline-outbox replays: a second insert with the -- same key no-ops (zero rows) and the caller returns the stored message. -insert into messages (conversation_id, author_user_id, body, parent_id, mentions, forwarded_from, tags, silent, client_msg_id) -values ($1, $2, $3, sqlc.narg(parent_id), coalesce(sqlc.narg(mentions), '[]'::jsonb), sqlc.narg(forwarded_from), coalesce(sqlc.narg(tags), '{}'::text[]), coalesce(sqlc.narg(silent), false), sqlc.narg(client_msg_id)) +insert into messages (conversation_id, author_user_id, body, parent_id, mentions, forwarded_from, tags, silent, client_msg_id, meta) +values ($1, $2, $3, sqlc.narg(parent_id), coalesce(sqlc.narg(mentions), '[]'::jsonb), sqlc.narg(forwarded_from), coalesce(sqlc.narg(tags), '{}'::text[]), coalesce(sqlc.narg(silent), false), sqlc.narg(client_msg_id), sqlc.narg(meta)) on conflict (conversation_id, client_msg_id) where client_msg_id is not null do nothing returning id; @@ -288,7 +299,7 @@ where m.id = sqlc.arg(id) and m.deleted_at is null; -- name: GetMessageByID :one -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -471,7 +482,7 @@ where mr.message_id = any(sqlc.arg(ids)::uuid[]) order by mr.created_at; -- name: RecentProjectMessages :many -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -533,7 +544,7 @@ group by c.id, c.project_id, c.kind, c.issue_id, c.brief_id, -- name: MentionsForUser :many -- messages mentioning the user (@), newest first -select m.id, m.conversation_id, m.body, m.tags, m.silent, m.created_at, m.edited_at, +select m.id, m.conversation_id, m.body, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, diff --git a/db/queries/mcp.sql b/db/queries/mcp.sql index 2e853e2..3358093 100644 --- a/db/queries/mcp.sql +++ b/db/queries/mcp.sql @@ -23,7 +23,7 @@ select * from conversations where project_id = sqlc.arg(project_id) order by created_at; -- name: SearchMessagesInProject :many -select m.id, m.conversation_id, m.body, m.tags, m.silent, m.created_at, m.edited_at, +select m.id, m.conversation_id, m.body, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar @@ -53,8 +53,8 @@ left join users u on u.id = i.assignee_id where i.id = sqlc.arg(id); -- name: CreateAgentMessage :one -insert into messages (conversation_id, author_agent_id, body, parent_id, mentions, forwarded_from, tags, silent) -values (sqlc.arg(conversation_id), sqlc.arg(agent_id), sqlc.arg(body), sqlc.narg(parent_id), coalesce(sqlc.narg(mentions), '[]'::jsonb), sqlc.narg(forwarded_from), coalesce(sqlc.narg(tags), '{}'::text[]), coalesce(sqlc.narg(silent), false)) +insert into messages (conversation_id, author_agent_id, body, parent_id, mentions, forwarded_from, tags, silent, meta) +values (sqlc.arg(conversation_id), sqlc.arg(agent_id), sqlc.arg(body), sqlc.narg(parent_id), coalesce(sqlc.narg(mentions), '[]'::jsonb), sqlc.narg(forwarded_from), coalesce(sqlc.narg(tags), '{}'::text[]), coalesce(sqlc.narg(silent), false), sqlc.narg(meta)) returning id; -- name: PinMessageAgent :one @@ -68,7 +68,7 @@ where id = sqlc.arg(id) and deleted_at is null returning id, conversation_id; -- name: GetMessageFull :one -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, diff --git a/db/queries/saved.sql b/db/queries/saved.sql index d53d72a..2757184 100644 --- a/db/queries/saved.sql +++ b/db/queries/saved.sql @@ -19,7 +19,7 @@ select message_id from saved_messages where user_id = sqlc.arg(user_id); -- name: ListSavedMessages :many -- newest-saved-first; joins mirror GetMessageByID so the client can render -- a normal message plus enough context to deep-link back to it -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, diff --git a/internal/conversations/conversations.go b/internal/conversations/conversations.go index 11c3c12..2c4bde1 100644 --- a/internal/conversations/conversations.go +++ b/internal/conversations/conversations.go @@ -10,6 +10,7 @@ import ( "net/http" "net/mail" "regexp" + "sort" "strconv" "strings" "time" @@ -84,6 +85,7 @@ func (s *Service) RegisterRoutes(g *gin.RouterGroup) { g.PUT("/messages/:id/pin", s.handlePinMessage) g.DELETE("/messages/:id/pin", s.handlePinMessage) g.GET("/conversations/:id/pins", s.memberOnly, s.handleListPins) + g.GET("/conversations/:id/ops", s.memberOnly, s.handleOpsSummary) g.PUT("/messages/:id/reactions", s.handleToggleReaction) g.POST("/messages/:id/read", s.handleMarkRead) g.POST("/conversations/:id/read", s.memberOnly, s.handleMarkConversationRead) @@ -227,7 +229,7 @@ func (s *Service) handleListMessages(c *gin.Context) { readers := readBy[m.ID.String()] msgs = append(msgs, MessageJSON(MessageView{ ID: m.ID, ConversationID: m.ConversationID, ParentID: m.ParentID, - Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, + Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Meta: m.Meta, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, AuthorUserID: m.AuthorUserID, AuthorAgentID: m.AuthorAgentID, AuthorKindSnapshot: m.AuthorKindSnapshot, AuthorName: m.AuthorName, AuthorAvatar: m.AuthorAvatar, @@ -396,7 +398,7 @@ func (s *Service) messageView(ctx context.Context, m db.GetMessageByIDRow) gin.H atts := s.attachmentsFor(ctx, []pgtype.UUID{m.ID}) return MessageJSON(MessageView{ ID: m.ID, ConversationID: m.ConversationID, ParentID: m.ParentID, - Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, + Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Meta: m.Meta, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, AuthorUserID: m.AuthorUserID, AuthorAgentID: m.AuthorAgentID, AuthorKindSnapshot: m.AuthorKindSnapshot, AuthorName: m.AuthorName, AuthorAvatar: m.AuthorAvatar, @@ -509,7 +511,7 @@ func (s *Service) handleEditMessage(c *gin.Context) { } out := MessageJSON(MessageView{ ID: m.ID, ConversationID: m.ConversationID, ParentID: m.ParentID, - Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, + Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Meta: m.Meta, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, AuthorUserID: m.AuthorUserID, AuthorAgentID: m.AuthorAgentID, AuthorKindSnapshot: m.AuthorKindSnapshot, AuthorName: m.AuthorName, AuthorAvatar: m.AuthorAvatar, @@ -616,7 +618,7 @@ func (s *Service) messagePayload(c *gin.Context, id pgtype.UUID) (gin.H, bool) { readers := s.readByFor(c, []pgtype.UUID{m.ID})[m.ID.String()] return MessageJSON(MessageView{ ID: m.ID, ConversationID: m.ConversationID, ParentID: m.ParentID, - Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, + Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Meta: m.Meta, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, AuthorUserID: m.AuthorUserID, AuthorAgentID: m.AuthorAgentID, AuthorKindSnapshot: m.AuthorKindSnapshot, AuthorName: m.AuthorName, AuthorAvatar: m.AuthorAvatar, @@ -704,7 +706,7 @@ func (s *Service) handleListPins(c *gin.Context) { readers := readBy[m.ID.String()] msgs = append(msgs, MessageJSON(MessageView{ ID: m.ID, ConversationID: m.ConversationID, ParentID: m.ParentID, - Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, + Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Meta: m.Meta, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, AuthorUserID: m.AuthorUserID, AuthorAgentID: m.AuthorAgentID, AuthorKindSnapshot: m.AuthorKindSnapshot, AuthorName: m.AuthorName, AuthorAvatar: m.AuthorAvatar, @@ -1191,9 +1193,9 @@ func (s *Service) handleUpdateChannel(c *gin.Context) { } if mode != nil { switch *mode { - case "", "receive", "chat": + case "", "receive", "chat", "ops": default: - httpx.Error(c, http.StatusBadRequest, "bad_request", "intake_mode must be '', 'receive' or 'chat'") + httpx.Error(c, http.StatusBadRequest, "bad_request", "intake_mode must be '', 'receive', 'chat' or 'ops'") return } if _, err := s.q.SetChannelIntakeMode(c.Request.Context(), db.SetChannelIntakeModeParams{ @@ -1286,7 +1288,7 @@ func (s *Service) postThreadNotice(c *gin.Context, parent db.Conversation, threa } out := MessageJSON(MessageView{ ID: m.ID, ConversationID: m.ConversationID, ParentID: m.ParentID, - Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, + Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Meta: m.Meta, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, AuthorUserID: m.AuthorUserID, AuthorAgentID: m.AuthorAgentID, AuthorKindSnapshot: m.AuthorKindSnapshot, AuthorName: m.AuthorName, AuthorAvatar: m.AuthorAvatar, @@ -1653,6 +1655,7 @@ type MessageView struct { Body string Mentions []byte Tags []string + Meta []byte Silent bool CreatedAt, EditedAt pgtype.Timestamptz AuthorUserID, AuthorAgentID pgtype.UUID @@ -1722,6 +1725,10 @@ func MessageJSON(v MessageView) gin.H { if mrefs == nil { mrefs = []any{} } + var meta any + if len(v.Meta) > 0 { + _ = json.Unmarshal(v.Meta, &meta) + } var thread *gin.H if v.ThreadID.Valid { thread = &gin.H{ @@ -1760,6 +1767,7 @@ func MessageJSON(v MessageView) gin.H { "body": v.Body, "mentions": mrefs, "tags": nonEmptyTags(v.Tags), + "meta": meta, "silent": v.Silent, "parent": parent, "thread": thread, @@ -1941,3 +1949,167 @@ func (s *Service) handleMentionables(c *gin.Context) { "users": users, "agents": agents, "issues": issues, "repos": repos, }) } + +// --- ops / command center --- + +// handleOpsSummary serves the control-center view over a channel's +// meta-carrying messages — see OpsSummarize. Member-gated by memberOnly. +func (s *Service) handleOpsSummary(c *gin.Context) { + conv := c.MustGet(ctxConversation).(db.Conversation) + rows, err := s.q.OpsStatusEvents(c.Request.Context(), conv.ID) + if err != nil { + httpx.Error(c, http.StatusInternalServerError, "internal", "internal error") + return + } + out := OpsSummarize(rows, time.Now().UTC()) + out["conversation_id"] = conv.ID.String() + c.JSON(http.StatusOK, out) +} + +// OpsSummarize folds raw meta-carrying messages into the command-center +// shape: latest state per service (worst first), a dense 30-day uptime +// strip, per-kind counts, and the newest event pointer. Pure — the HTTP +// handler and the MCP ops_summary tool both render from it. +func OpsSummarize(rows []db.OpsStatusEventsRow, now time.Time) gin.H { + type svc struct { + service string + state string + latencyMs int64 + env string + at time.Time + msgID string + } + services := map[string]*svc{} + days := map[string]*gin.H{} + kinds := map[string]int64{} + dayStart := now.AddDate(0, 0, -30).Truncate(24 * time.Hour) + var lastEvent time.Time + var lastID string + for _, r := range rows { + var m map[string]any + if json.Unmarshal(r.Meta, &m) != nil { + continue + } + kind, _ := m["kind"].(string) + if kind != "" { + kinds[kind]++ + } + at := r.CreatedAt.Time + if v, ok := m["at"].(string); ok { + if t, err := time.Parse(time.RFC3339, v); err == nil { + at = t + } + } + if r.CreatedAt.Time.After(lastEvent) { + lastEvent = r.CreatedAt.Time + lastID = r.ID.String() + } + service, _ := m["service"].(string) + state, _ := m["state"].(string) + // Only health readings feed the board + strip — a deploy's "ok" or + // an alert's "critical" shouldn't masquerade as a probe result. + if !opsBoardKind(kind) { + continue + } + if service != "" && state != "" { + cur := services[service] + if cur == nil || at.After(cur.at) || at.Equal(cur.at) { + var lat int64 + if v, ok := m["latency_ms"].(float64); ok { + lat = int64(v) + } + env, _ := m["env"].(string) + services[service] = &svc{service: service, state: state, + latencyMs: lat, env: env, at: at, msgID: r.ID.String()} + } + } + if state != "" && !at.Before(dayStart) { + d := at.UTC().Format("2006-01-02") + b := days[d] + if b == nil { + b = &gin.H{"date": d, "worst": state, "events": int64(1)} + days[d] = b + } else { + (*b)["events"] = (*b)["events"].(int64) + 1 + if stateRank(state) > stateRank((*b)["worst"].(string)) { + (*b)["worst"] = state + } + } + } + } + // services sorted: worst state first, then name — the down thing is + // what the eye should land on + svcList := make([]*svc, 0, len(services)) + for _, v := range services { + svcList = append(svcList, v) + } + sort.Slice(svcList, func(i, j int) bool { + ri, rj := stateRank(svcList[i].state), stateRank(svcList[j].state) + if ri != rj { + return ri > rj + } + return svcList[i].service < svcList[j].service + }) + svcOut := make([]gin.H, 0, len(svcList)) + for _, v := range svcList { + svcOut = append(svcOut, gin.H{ + "service": v.service, "state": v.state, + "latency_ms": v.latencyMs, "env": v.env, + "at": v.at.Format(time.RFC3339), "message_id": v.msgID, + }) + } + // dense 30-day strip — days with no events render as 'no_data' + dayOut := make([]gin.H, 0, 30) + for i := 29; i >= 0; i-- { + d := now.AddDate(0, 0, -i).Format("2006-01-02") + if b, ok := days[d]; ok { + dayOut = append(dayOut, *b) + } else { + dayOut = append(dayOut, gin.H{"date": d, "worst": "no_data", "events": int64(0)}) + } + } + var lastAt any + if !lastEvent.IsZero() { + lastAt = lastEvent.Format(time.RFC3339) + } + return gin.H{ + "services": svcOut, + "days": dayOut, + "kinds": kinds, + "last_event_at": lastAt, + "last_message_id": lastID, + } +} + +// opsBoardKind gates which kinds count as health readings: uptime probes, +// heartbeats and explicit status posts. Empty kind counts too — a monitor +// that only sends {service, state} still feeds the board. Errors, alerts, +// deploys and logs render as cards and kind counts but never overwrite a +// service's health state. +func opsBoardKind(kind string) bool { + switch strings.ToLower(kind) { + case "", "status", "uptime", "health", "probe", "heartbeat", "monitor": + return true + } + return false +} + +// stateRank orders health states for "worst of the day" and sort-first. +// Unknown strings sit between known-good and no_data so a tool's custom +// state can't silently look healthy. +func stateRank(s string) int { + switch s { + case "down", "outage", "critical", "crit", "fatal": + return 5 + case "degraded", "warn", "warning", "error": + return 4 + case "maintenance": + return 3 + case "up", "ok", "operational", "healthy", "resolved": + return 1 + case "no_data": + return 0 + default: + return 2 + } +} diff --git a/internal/conversations/ops_test.go b/internal/conversations/ops_test.go new file mode 100644 index 0000000..af6b22f --- /dev/null +++ b/internal/conversations/ops_test.go @@ -0,0 +1,99 @@ +package conversations + +// OpsSummarize — the pure fold behind GET /conversations/:id/ops and the +// MCP ops_summary tool. Covers service-state ordering, day bucketing, and +// per-kind counts; rows here are synthetic (no DB). + +import ( + "testing" + "time" + + "github.com/Dvorinka/relay/internal/db" + "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v5/pgtype" +) + +func metaRow(at time.Time, meta string) db.OpsStatusEventsRow { + return db.OpsStatusEventsRow{ + ID: pgtype.UUID{Bytes: [16]byte{1}, Valid: true}, + CreatedAt: pgtype.Timestamptz{Time: at, Valid: true}, + Meta: []byte(meta), + } +} + +func TestOpsSummarize(t *testing.T) { + now := time.Date(2026, 10, 12, 12, 0, 0, 0, time.UTC) + rows := []db.OpsStatusEventsRow{ + // api went down earlier today, recovered later — latest wins + metaRow(now.Add(-3*time.Hour), + `{"kind":"status","service":"api","state":"down","latency_ms":0}`), + metaRow(now.Add(-time.Hour), + `{"kind":"status","service":"api","state":"up","latency_ms":84,"env":"prod"}`), + // web is down and stays down — sorts first (worst state) + metaRow(now.Add(-2*time.Hour), + `{"kind":"status","service":"web","state":"down","latency_ms":900}`), + // an error post with a level — counts under kinds, not services + metaRow(now.Add(-30*time.Minute), + `{"kind":"error","service":"web","level":"error","release":"v1.2.3"}`), + // a 2-day-old degraded reading for the strip + metaRow(now.Add(-49*time.Hour), + `{"kind":"status","service":"api","state":"degraded"}`), + // garbage meta is skipped, not fatal + metaRow(now.Add(-time.Hour), `not json`), + } + + out := OpsSummarize(rows, now) + + svcs, ok := out["services"].([]gin.H) + if !ok || len(svcs) != 2 { + t.Fatalf("services: %v", out["services"]) + } + if svcs[0]["service"] != "web" || svcs[0]["state"] != "down" { + t.Fatalf("worst service should sort first: %v", svcs[0]) + } + if svcs[0]["latency_ms"] != int64(900) { + t.Fatalf("latency lost: %v", svcs[0]) + } + if svcs[1]["service"] != "api" || svcs[1]["state"] != "up" || + svcs[1]["env"] != "prod" { + t.Fatalf("api should be latest-state up: %v", svcs[1]) + } + + days, ok := out["days"].([]gin.H) + if !ok || len(days) != 30 { + t.Fatalf("days must be a dense 30-entry strip: %v", len(days)) + } + // today is the last entry; it contains up+down+degraded — down wins + if days[29]["worst"] != "down" { + t.Fatalf("today's worst should be down: %v", days[29]) + } + // two days ago saw the api degraded event + if days[27]["worst"] != "degraded" || days[27]["events"] != int64(1) { + t.Fatalf("day-2 bucket wrong: %v", days[27]) + } + // a silent day reports no_data + if days[10]["worst"] != "no_data" || days[10]["events"] != int64(0) { + t.Fatalf("empty day should be no_data: %v", days[10]) + } + + kinds, _ := out["kinds"].(map[string]int64) + if kinds["status"] != 4 || kinds["error"] != 1 { + t.Fatalf("kind counts wrong: %v", kinds) + } + if out["last_event_at"] == nil { + t.Fatalf("last_event_at unset") + } +} + +func TestOpsSummarizeEmpty(t *testing.T) { + out := OpsSummarize(nil, time.Now().UTC()) + if n := len(out["services"].([]gin.H)); n != 0 { + t.Fatalf("empty input should give no services: %v", out["services"]) + } + if len(out["days"].([]gin.H)) != 30 { + t.Fatalf("strip must still render 30 days") + } + if out["last_event_at"] != nil { + t.Fatalf("no events -> nil last_event_at") + } +} diff --git a/internal/db/conversations.sql.go b/internal/db/conversations.sql.go index a1414b2..034cc5b 100644 --- a/internal/db/conversations.sql.go +++ b/internal/db/conversations.sql.go @@ -243,8 +243,8 @@ func (q *Queries) CreateChannel(ctx context.Context, arg CreateChannelParams) (C } const createMessage = `-- name: CreateMessage :one -insert into messages (conversation_id, author_user_id, body, parent_id, mentions, forwarded_from, tags, silent, client_msg_id) -values ($1, $2, $3, $4, coalesce($5, '[]'::jsonb), $6, coalesce($7, '{}'::text[]), coalesce($8, false), $9) +insert into messages (conversation_id, author_user_id, body, parent_id, mentions, forwarded_from, tags, silent, client_msg_id, meta) +values ($1, $2, $3, $4, coalesce($5, '[]'::jsonb), $6, coalesce($7, '{}'::text[]), coalesce($8, false), $9, $10) on conflict (conversation_id, client_msg_id) where client_msg_id is not null do nothing returning id ` @@ -259,6 +259,7 @@ type CreateMessageParams struct { Tags interface{} `json:"tags"` Silent interface{} `json:"silent"` ClientMsgID pgtype.Text `json:"client_msg_id"` + Meta []byte `json:"meta"` } // client_msg_id dedupes offline-outbox replays: a second insert with the @@ -274,6 +275,7 @@ func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (p arg.Tags, arg.Silent, arg.ClientMsgID, + arg.Meta, ) var id pgtype.UUID err := row.Scan(&id) @@ -523,7 +525,7 @@ func (q *Queries) GetConversationForUser(ctx context.Context, arg GetConversatio } const getMessageByID = `-- name: GetMessageByID :one -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -558,6 +560,7 @@ type GetMessageByIDRow struct { Body string `json:"body"` Mentions []byte `json:"mentions"` Tags []string `json:"tags"` + Meta []byte `json:"meta"` Silent bool `json:"silent"` CreatedAt pgtype.Timestamptz `json:"created_at"` EditedAt pgtype.Timestamptz `json:"edited_at"` @@ -590,6 +593,7 @@ func (q *Queries) GetMessageByID(ctx context.Context, id pgtype.UUID) (GetMessag &i.Body, &i.Mentions, &i.Tags, + &i.Meta, &i.Silent, &i.CreatedAt, &i.EditedAt, @@ -874,7 +878,7 @@ func (q *Queries) ListChannels(ctx context.Context, projectID pgtype.UUID) ([]Co } const listHookChannelMessages = `-- name: ListHookChannelMessages :many -select m.id, m.conversation_id, m.body, m.tags, m.created_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.tags, m.meta, m.created_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name from messages m @@ -902,6 +906,7 @@ type ListHookChannelMessagesRow struct { ConversationID pgtype.UUID `json:"conversation_id"` Body string `json:"body"` Tags []string `json:"tags"` + Meta []byte `json:"meta"` CreatedAt pgtype.Timestamptz `json:"created_at"` ParentID pgtype.UUID `json:"parent_id"` AuthorUserID pgtype.UUID `json:"author_user_id"` @@ -931,6 +936,7 @@ func (q *Queries) ListHookChannelMessages(ctx context.Context, arg ListHookChann &i.ConversationID, &i.Body, &i.Tags, + &i.Meta, &i.CreatedAt, &i.ParentID, &i.AuthorUserID, @@ -949,7 +955,7 @@ func (q *Queries) ListHookChannelMessages(ctx context.Context, arg ListHookChann } const listMessages = `-- name: ListMessages :many -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -997,6 +1003,7 @@ type ListMessagesRow struct { Body string `json:"body"` Mentions []byte `json:"mentions"` Tags []string `json:"tags"` + Meta []byte `json:"meta"` Silent bool `json:"silent"` CreatedAt pgtype.Timestamptz `json:"created_at"` EditedAt pgtype.Timestamptz `json:"edited_at"` @@ -1042,6 +1049,7 @@ func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]L &i.Body, &i.Mentions, &i.Tags, + &i.Meta, &i.Silent, &i.CreatedAt, &i.EditedAt, @@ -1075,7 +1083,7 @@ func (q *Queries) ListMessages(ctx context.Context, arg ListMessagesParams) ([]L } const listPinnedMessages = `-- name: ListPinnedMessages :many -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -1113,6 +1121,7 @@ type ListPinnedMessagesRow struct { Body string `json:"body"` Mentions []byte `json:"mentions"` Tags []string `json:"tags"` + Meta []byte `json:"meta"` Silent bool `json:"silent"` CreatedAt pgtype.Timestamptz `json:"created_at"` EditedAt pgtype.Timestamptz `json:"edited_at"` @@ -1152,6 +1161,7 @@ func (q *Queries) ListPinnedMessages(ctx context.Context, conversationID pgtype. &i.Body, &i.Mentions, &i.Tags, + &i.Meta, &i.Silent, &i.CreatedAt, &i.EditedAt, @@ -1342,7 +1352,7 @@ func (q *Queries) MarkMessageRead(ctx context.Context, arg MarkMessageReadParams } const mentionsForUser = `-- name: MentionsForUser :many -select m.id, m.conversation_id, m.body, m.tags, m.silent, m.created_at, m.edited_at, +select m.id, m.conversation_id, m.body, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -1376,6 +1386,7 @@ type MentionsForUserRow struct { ConversationID pgtype.UUID `json:"conversation_id"` Body string `json:"body"` Tags []string `json:"tags"` + Meta []byte `json:"meta"` Silent bool `json:"silent"` CreatedAt pgtype.Timestamptz `json:"created_at"` EditedAt pgtype.Timestamptz `json:"edited_at"` @@ -1407,6 +1418,7 @@ func (q *Queries) MentionsForUser(ctx context.Context, userID pgtype.UUID) ([]Me &i.ConversationID, &i.Body, &i.Tags, + &i.Meta, &i.Silent, &i.CreatedAt, &i.EditedAt, @@ -1471,6 +1483,44 @@ func (q *Queries) MessageReadByAgent(ctx context.Context, messageID pgtype.UUID) return exists, err } +const opsStatusEvents = `-- name: OpsStatusEvents :many +select m.id, m.created_at, m.meta +from messages m +where m.conversation_id = $1 + and m.deleted_at is null + and m.meta is not null + and m.created_at > now() - interval '35 days' +order by m.created_at asc +` + +type OpsStatusEventsRow struct { + ID pgtype.UUID `json:"id"` + CreatedAt pgtype.Timestamptz `json:"created_at"` + Meta []byte `json:"meta"` +} + +// ops-channel control center: every meta-carrying post in the window. +// Service states, uptime day-buckets and counts derive in Go. +func (q *Queries) OpsStatusEvents(ctx context.Context, conversationID pgtype.UUID) ([]OpsStatusEventsRow, error) { + rows, err := q.db.Query(ctx, opsStatusEvents, conversationID) + if err != nil { + return nil, err + } + defer rows.Close() + items := []OpsStatusEventsRow{} + for rows.Next() { + var i OpsStatusEventsRow + if err := rows.Scan(&i.ID, &i.CreatedAt, &i.Meta); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const parentAuthorID = `-- name: ParentAuthorID :one select m2.author_user_id from messages m @@ -1506,7 +1556,7 @@ func (q *Queries) PinMessage(ctx context.Context, id pgtype.UUID) (PinMessageRow } const recentProjectMessages = `-- name: RecentProjectMessages :many -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -1531,6 +1581,7 @@ type RecentProjectMessagesRow struct { Body string `json:"body"` Mentions []byte `json:"mentions"` Tags []string `json:"tags"` + Meta []byte `json:"meta"` Silent bool `json:"silent"` CreatedAt pgtype.Timestamptz `json:"created_at"` EditedAt pgtype.Timestamptz `json:"edited_at"` @@ -1561,6 +1612,7 @@ func (q *Queries) RecentProjectMessages(ctx context.Context, projectID pgtype.UU &i.Body, &i.Mentions, &i.Tags, + &i.Meta, &i.Silent, &i.CreatedAt, &i.EditedAt, diff --git a/internal/db/mcp.sql.go b/internal/db/mcp.sql.go index 29db913..a14b697 100644 --- a/internal/db/mcp.sql.go +++ b/internal/db/mcp.sql.go @@ -145,8 +145,8 @@ func (q *Queries) AgentProjectUnread(ctx context.Context, agentID pgtype.UUID) ( } const createAgentMessage = `-- name: CreateAgentMessage :one -insert into messages (conversation_id, author_agent_id, body, parent_id, mentions, forwarded_from, tags, silent) -values ($1, $2, $3, $4, coalesce($5, '[]'::jsonb), $6, coalesce($7, '{}'::text[]), coalesce($8, false)) +insert into messages (conversation_id, author_agent_id, body, parent_id, mentions, forwarded_from, tags, silent, meta) +values ($1, $2, $3, $4, coalesce($5, '[]'::jsonb), $6, coalesce($7, '{}'::text[]), coalesce($8, false), $9) returning id ` @@ -159,6 +159,7 @@ type CreateAgentMessageParams struct { ForwardedFrom pgtype.UUID `json:"forwarded_from"` Tags interface{} `json:"tags"` Silent interface{} `json:"silent"` + Meta []byte `json:"meta"` } func (q *Queries) CreateAgentMessage(ctx context.Context, arg CreateAgentMessageParams) (pgtype.UUID, error) { @@ -171,6 +172,7 @@ func (q *Queries) CreateAgentMessage(ctx context.Context, arg CreateAgentMessage arg.ForwardedFrom, arg.Tags, arg.Silent, + arg.Meta, ) var id pgtype.UUID err := row.Scan(&id) @@ -310,7 +312,7 @@ func (q *Queries) GetIssueForAgent(ctx context.Context, id pgtype.UUID) (GetIssu } const getMessageFull = `-- name: GetMessageFull :one -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -345,6 +347,7 @@ type GetMessageFullRow struct { Body string `json:"body"` Mentions []byte `json:"mentions"` Tags []string `json:"tags"` + Meta []byte `json:"meta"` Silent bool `json:"silent"` CreatedAt pgtype.Timestamptz `json:"created_at"` EditedAt pgtype.Timestamptz `json:"edited_at"` @@ -377,6 +380,7 @@ func (q *Queries) GetMessageFull(ctx context.Context, id pgtype.UUID) (GetMessag &i.Body, &i.Mentions, &i.Tags, + &i.Meta, &i.Silent, &i.CreatedAt, &i.EditedAt, @@ -693,7 +697,7 @@ func (q *Queries) ResolveMessageProject(ctx context.Context, id pgtype.UUID) (pg } const searchMessagesInProject = `-- name: SearchMessagesInProject :many -select m.id, m.conversation_id, m.body, m.tags, m.silent, m.created_at, m.edited_at, +select m.id, m.conversation_id, m.body, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar @@ -720,6 +724,7 @@ type SearchMessagesInProjectRow struct { ConversationID pgtype.UUID `json:"conversation_id"` Body string `json:"body"` Tags []string `json:"tags"` + Meta []byte `json:"meta"` Silent bool `json:"silent"` CreatedAt pgtype.Timestamptz `json:"created_at"` EditedAt pgtype.Timestamptz `json:"edited_at"` @@ -744,6 +749,7 @@ func (q *Queries) SearchMessagesInProject(ctx context.Context, arg SearchMessage &i.ConversationID, &i.Body, &i.Tags, + &i.Meta, &i.Silent, &i.CreatedAt, &i.EditedAt, diff --git a/internal/db/models.go b/internal/db/models.go index 8d6bd46..5e56825 100644 --- a/internal/db/models.go +++ b/internal/db/models.go @@ -281,6 +281,7 @@ type Message struct { AuthorKindSnapshot string `json:"author_kind_snapshot"` Silent bool `json:"silent"` ClientMsgID pgtype.Text `json:"client_msg_id"` + Meta []byte `json:"meta"` } type MessageAttachment struct { diff --git a/internal/db/saved.sql.go b/internal/db/saved.sql.go index 23b331f..7ee3e45 100644 --- a/internal/db/saved.sql.go +++ b/internal/db/saved.sql.go @@ -55,7 +55,7 @@ func (q *Queries) ListSavedMessageIDs(ctx context.Context, userID pgtype.UUID) ( } const listSavedMessages = `-- name: ListSavedMessages :many -select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, +select m.id, m.conversation_id, m.body, m.mentions, m.tags, m.meta, m.silent, m.created_at, m.edited_at, m.deleted_at, m.parent_id, m.author_user_id, m.author_agent_id, m.author_kind_snapshot, coalesce(u.name, a.name, nullif(m.author_name_snapshot, ''), '') as author_name, coalesce(u.avatar_key, a.avatar_key) as author_avatar, @@ -96,6 +96,7 @@ type ListSavedMessagesRow struct { Body string `json:"body"` Mentions []byte `json:"mentions"` Tags []string `json:"tags"` + Meta []byte `json:"meta"` Silent bool `json:"silent"` CreatedAt pgtype.Timestamptz `json:"created_at"` EditedAt pgtype.Timestamptz `json:"edited_at"` @@ -139,6 +140,7 @@ func (q *Queries) ListSavedMessages(ctx context.Context, userID pgtype.UUID) ([] &i.Body, &i.Mentions, &i.Tags, + &i.Meta, &i.Silent, &i.CreatedAt, &i.EditedAt, diff --git a/internal/github/autofile.go b/internal/github/autofile.go index 5121bf1..b831e9d 100644 --- a/internal/github/autofile.go +++ b/internal/github/autofile.go @@ -325,7 +325,7 @@ func (s *Service) publishMessage(ctx context.Context, conv db.Conversation, msgI func messageJSON(m db.GetMessageByIDRow) gin.H { return conversations.MessageJSON(conversations.MessageView{ ID: m.ID, ConversationID: m.ConversationID, ParentID: m.ParentID, - Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Silent: m.Silent, + Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Meta: m.Meta, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, AuthorUserID: m.AuthorUserID, AuthorAgentID: m.AuthorAgentID, AuthorKindSnapshot: m.AuthorKindSnapshot, diff --git a/internal/mcpserver/mcpserver.go b/internal/mcpserver/mcpserver.go index 4a56c28..ad2463b 100644 --- a/internal/mcpserver/mcpserver.go +++ b/internal/mcpserver/mcpserver.go @@ -258,6 +258,11 @@ func (s *Service) registerTools(srv *server.MCPServer) { mcp.WithString("project_id", mcp.Required()), ), s.listConversations) + srv.AddTool(mcp.NewTool("ops_summary", + mcp.WithDescription("Control-center view over a channel's structured (meta) posts: latest state per service, a 30-day uptime strip, and per-kind counts. Use on ops/monitoring channels; agents_blocked channels refuse."), + mcp.WithString("conversation_id", mcp.Required()), + ), s.opsSummary) + srv.AddTool(mcp.NewTool("get_messages", mcp.WithDescription("List messages in a conversation (newest first). Pass conversation_id, or project_id for the project's main thread."), mcp.WithString("conversation_id"), @@ -311,6 +316,7 @@ func (s *Service) registerTools(srv *server.MCPServer) { mcp.WithString("tags", mcp.Description("Comma-separated tags classifying the message, e.g. frontend,backend,visual,mcp")), mcp.WithBoolean("silent", mcp.Description("true posts without any notification/push — use for routine progress updates inside a work thread. @mentions in a silent message still notify.")), mcp.WithString("attachment_ids", mcp.Description("Comma-separated attachment UUIDs from upload_attachment, max 20")), + mcp.WithString("meta", mcp.Description("Optional JSON object rendered as a structured card — ops channels aggregate it. Recognized keys: kind, service, state (up|degraded|down|maintenance…), latency_ms, level, env, release, url, at, fields{label:value}")), ), s.sendMessage) srv.AddTool(mcp.NewTool("edit_message", @@ -746,12 +752,17 @@ func messageJSON(m db.GetMessageFullRow) gin.H { "author": m.FwdAuthorName, } } + var meta any + if len(m.Meta) > 0 { + _ = json.Unmarshal(m.Meta, &meta) + } return gin.H{ "id": m.ID, "conversation_id": m.ConversationID, "body": m.Body, "mentions": mrefs, "tags": m.Tags, + "meta": meta, "silent": m.Silent, "parent": parent, "thread": thread, @@ -915,6 +926,33 @@ func (s *Service) listConversations(ctx context.Context, req mcp.CallToolRequest return jsonResult(out) } +// opsSummary is the agent-facing control center: same fold as the web +// /channels/:id/ops endpoint, gated by checkAgentConversation so +// agents_blocked channels stay dark. +func (s *Service) opsSummary(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { + cid, err := uuidArg(req, "conversation_id") + if err != nil { + return errResult(err) + } + if err := s.checkAgentConversation(ctx, cid); err != nil { + return mcp.NewToolResultError(err.Error()), nil + } + pid, err := s.q.ResolveConversationProject(ctx, cid) + if err != nil { + return errResult(err) + } + if err := s.scope(ctx, pid, "message:read"); err != nil { + return errResult(err) + } + rows, err := s.q.OpsStatusEvents(ctx, cid) + if err != nil { + return errResult(err) + } + out := conversations.OpsSummarize(rows, time.Now().UTC()) + out["conversation_id"] = cid.String() + return jsonResult(out) +} + // checkAgentConversation refuses channels flagged agents_blocked and // conversations past their expiry — the per-channel agent gate. func (s *Service) checkAgentConversation(ctx context.Context, cid pgtype.UUID) error { @@ -1547,9 +1585,22 @@ func (s *Service) sendMessage(ctx context.Context, req mcp.CallToolRequest) (*mc } refs := s.resolveMentions(ctx, pid, mentions.Extract(body)) mj, _ := json.Marshal(refs) + // Optional structured meta — ops/status cards. Accepts a JSON object; + // must be an object (not array/scalar) and stay under 8KiB. + var meta []byte + if v := strings.TrimSpace(req.GetString("meta", "")); v != "" { + var probe map[string]any + if err := json.Unmarshal([]byte(v), &probe); err != nil || probe == nil { + return mcp.NewToolResultError("meta must be a JSON object"), nil + } + if len(v) > 8<<10 { + return mcp.NewToolResultError("meta too large (8KiB max)"), nil + } + meta = []byte(v) + } id, err := s.q.CreateAgentMessage(ctx, db.CreateAgentMessageParams{ ConversationID: cid, AgentID: agent(ctx).ID, Body: body, ParentID: parent, - Mentions: mj, Tags: tags, Silent: silent, + Mentions: mj, Tags: tags, Silent: silent, Meta: meta, }) if err != nil { return errResult(err) diff --git a/internal/saved/saved.go b/internal/saved/saved.go index c894a44..dd554bd 100644 --- a/internal/saved/saved.go +++ b/internal/saved/saved.go @@ -88,7 +88,7 @@ func (s *Service) handleList(c *gin.Context) { for _, r := range rows { m := conversations.MessageJSON(conversations.MessageView{ ID: r.ID, ConversationID: r.ConversationID, ParentID: r.ParentID, - Body: r.Body, Mentions: r.Mentions, Tags: r.Tags, Silent: r.Silent, + Body: r.Body, Mentions: r.Mentions, Tags: r.Tags, Meta: r.Meta, Silent: r.Silent, CreatedAt: r.CreatedAt, EditedAt: r.EditedAt, AuthorUserID: r.AuthorUserID, AuthorAgentID: r.AuthorAgentID, AuthorKindSnapshot: r.AuthorKindSnapshot, diff --git a/internal/server/inbound_e2e_test.go b/internal/server/inbound_e2e_test.go index 07238a3..e4a7433 100644 --- a/internal/server/inbound_e2e_test.go +++ b/internal/server/inbound_e2e_test.go @@ -326,3 +326,100 @@ func TestInboundIntake(t *testing.T) { t.Fatalf("disabled hook read: %d", code) } } + +// Ops intake — a monitoring channel (intake_mode='ops') plus structured +// payloads that land on messages.meta and feed the ops summary endpoint. +func TestInboundOpsChannel(t *testing.T) { + c, _, _, projID := e2eSetup(t, "ops") + + code, ch := c.call("POST", "/api/projects/"+projID+"/channels", + `{"name":"ops-board"}`) + if code != 200 && code != 201 { + t.Fatalf("channel: %d %v", code, ch) + } + chanID := ch["channel"].(map[string]any)["id"].(string) + + // 'ops' is a legal intake_mode now — bogus still 400s. + code, up := c.call("PATCH", "/api/channels/"+chanID, `{"intake_mode":"ops"}`) + if code != 200 { + t.Fatalf("ops mode patch: %d %v", code, up) + } + if up["channel"].(map[string]any)["intake_mode"] != "ops" { + t.Fatalf("intake_mode not stored: %v", up) + } + + code, hook := c.call("POST", "/api/projects/"+projID+"/hooks", + fmt.Sprintf(`{"name":"probe","conversation_id":%q}`, chanID)) + if code != 201 { + t.Fatalf("hook: %d %v", code, hook) + } + tok, _ := hook["token"].(string) + if tok == "" { + t.Fatalf("no token: %v", hook) + } + post := func(p string) (int, map[string]any) { + return c.call("POST", "/api/hooks/"+tok, p) + } + + // Two probes — api down then up; latest state wins the board. + if code, r := post(`{"kind":"status","service":"api","state":"down","latency_ms":0,"env":"prod","message":"api unreachable"}`); code != 202 { + t.Fatalf("down post: %d %v", code, r) + } + code, r := post(`{"kind":"status","service":"api","state":"up","latency_ms":84,"env":"prod","message":"api recovered","fields":{"region":"eu"}}`) + if code != 202 { + t.Fatalf("up post: %d %v", code, r) + } + // an error event from a tracker + code, re := post(`{"kind":"error","service":"web","level":"error","release":"v1.0.0","subject":"TypeError","message":"n.items undefined"}`) + if code != 202 { + t.Fatalf("error post: %d %v", code, re) + } + msgID := re["message_id"].(string) + + // The message carries meta end to end. + code, lst := c.call("GET", "/api/conversations/"+chanID+"/messages", "") + if code != 200 { + t.Fatalf("messages: %d", code) + } + var found map[string]any + for _, m := range lst["messages"].([]any) { + mm := m.(map[string]any) + if mm["id"] == msgID { + found = mm + } + } + if found == nil { + t.Fatalf("error post missing from channel") + } + meta, _ := found["meta"].(map[string]any) + if meta["kind"] != "error" || meta["service"] != "web" || meta["level"] != "error" { + t.Fatalf("meta not on message: %v", found["meta"]) + } + + // The ops summary folds them: api recovered (up), web has no state so + // no service pill — but kind counts register the error. + code, ops := c.call("GET", "/api/conversations/"+chanID+"/ops", "") + if code != 200 { + t.Fatalf("ops summary: %d %v", code, ops) + } + svcs, _ := ops["services"].([]any) + if len(svcs) != 1 { + t.Fatalf("expected 1 service (only api reported state): %v", svcs) + } + svc := svcs[0].(map[string]any) + if svc["service"] != "api" || svc["state"] != "up" { + t.Fatalf("api should read up after recovery: %v", svc) + } + kinds, _ := ops["kinds"].(map[string]any) + if kinds["status"] != float64(2) || kinds["error"] != float64(1) { + t.Fatalf("kind counts wrong: %v", kinds) + } + days, _ := ops["days"].([]any) + if len(days) != 30 { + t.Fatalf("ops strip must hold 30 days: %v", len(days)) + } + today := days[29].(map[string]any) + if today["worst"] != "down" { + t.Fatalf("today saw a down probe — worst should be down: %v", today) + } +} diff --git a/internal/webhooks/inbound.go b/internal/webhooks/inbound.go index d25c3b2..dfde130 100644 --- a/internal/webhooks/inbound.go +++ b/internal/webhooks/inbound.go @@ -11,6 +11,8 @@ import ( "crypto/sha256" "encoding/base64" "encoding/hex" + "encoding/json" + "fmt" "net/http" "path" "strconv" @@ -269,13 +271,22 @@ func (s *Service) handleInbound(c *gin.Context) { } c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, s.bodyCap()) var req struct { - Message string `json:"message"` - Text string `json:"text"` - Body string `json:"body"` - From string `json:"from"` - Subject string `json:"subject"` - Key string `json:"key"` - Kind string `json:"kind"` + Message string `json:"message"` + Text string `json:"text"` + Body string `json:"body"` + From string `json:"from"` + Subject string `json:"subject"` + Key string `json:"key"` + Kind string `json:"kind"` + Service string `json:"service"` + State string `json:"state"` + LatencyMs *int64 `json:"latency_ms"` + Level string `json:"level"` + Env string `json:"env"` + Release string `json:"release"` + URL string `json:"url"` + Fields map[string]any `json:"fields"` + At string `json:"at"` Attachments []struct { Name string `json:"name"` ContentType string `json:"content_type"` @@ -296,12 +307,25 @@ func (s *Service) handleInbound(c *gin.Context) { from := oneLine(req.From, 200) subject := oneLine(req.Subject, 200) key := oneLine(req.Key, 200) - // kind = the platform's own report type (bug, feature, …) — free-form. - // Payload wins over the hook's default. + // kind = the platform's own report type (bug, feature, status, error, …) + // — free-form. Payload wins over the hook's default. kind := oneLine(req.Kind, 40) if kind == "" { kind = hook.Kind } + // Structured ops payload — monitoring state, error level, arbitrary + // labelled fields. Lands on messages.meta; ops channels aggregate it. + meta := buildOpsMeta(kind, opsFields{ + Service: oneLine(req.Service, 120), + State: strings.ToLower(oneLine(req.State, 24)), + LatencyMs: req.LatencyMs, + Level: strings.ToLower(oneLine(req.Level, 16)), + Env: oneLine(req.Env, 60), + Release: oneLine(req.Release, 120), + URL: oneLine(req.URL, 500), + Fields: req.Fields, + At: oneLine(req.At, 60), + }) body = strings.TrimSpace(body) if body == "" { body = subject @@ -383,6 +407,7 @@ func (s *Service) handleInbound(c *gin.Context) { ParentID: msgParent, Body: body, Tags: tags, + Meta: meta, }) if err != nil { httpx.Error(c, http.StatusInternalServerError, "internal", "internal error") @@ -443,7 +468,7 @@ func (s *Service) handleInbound(c *gin.Context) { if m, err := s.q.GetMessageByID(c.Request.Context(), mid); err == nil { out := conversations.MessageJSON(conversations.MessageView{ ID: m.ID, ConversationID: m.ConversationID, ParentID: m.ParentID, - Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Silent: m.Silent, + Body: m.Body, Mentions: m.Mentions, Tags: m.Tags, Meta: m.Meta, Silent: m.Silent, CreatedAt: m.CreatedAt, EditedAt: m.EditedAt, AuthorUserID: m.AuthorUserID, AuthorAgentID: m.AuthorAgentID, AuthorKindSnapshot: m.AuthorKindSnapshot, @@ -586,6 +611,12 @@ func (s *Service) handleInboundMessages(c *gin.Context) { "via_hook": viaHook, "created_at": m.CreatedAt, } + if len(m.Meta) > 0 { + var meta any + if json.Unmarshal(m.Meta, &meta) == nil { + msg["meta"] = meta + } + } // Lift intake metadata out of the tag list for convenience. for _, t := range m.Tags { switch { @@ -632,6 +663,90 @@ func renderHookHead(tpl, from, subject, kind, key string) string { return strings.TrimSpace(r.Replace(tpl)) } +// opsFields is the structured part of an inbound payload. Any monitoring, +// CI, error-tracking or homegrown tool can POST these; Relay stores them +// verbatim (validated + size-capped) so ops channels and cards can render +// them without Relay knowing the sender's schema. +type opsFields struct { + Service string + State string + LatencyMs *int64 + Level string + Env string + Release string + URL string + Fields map[string]any + At string +} + +const opsMetaCap = 8 << 10 // 8KiB — stacks belong in body, meta stays lean + +// buildOpsMeta assembles the jsonb meta blob. Nil when the post carries no +// structured data at all (kind alone doesn't make a message "ops"). +func buildOpsMeta(kind string, f opsFields) []byte { + m := map[string]any{} + if kind != "" { + m["kind"] = kind + } + if f.Service != "" { + m["service"] = f.Service + } + if f.State != "" { + m["state"] = f.State + } + if f.LatencyMs != nil { + v := *f.LatencyMs + if v < 0 { + v = 0 + } + if v > 86400000 { // a day in ms — beyond that it's a bug upstream + v = 86400000 + } + m["latency_ms"] = v + } + if f.Level != "" { + m["level"] = f.Level + } + if f.Env != "" { + m["env"] = f.Env + } + if f.Release != "" { + m["release"] = f.Release + } + if f.URL != "" { + m["url"] = f.URL + } + if f.At != "" { + if ts, err := time.Parse(time.RFC3339, f.At); err == nil { + m["at"] = ts.UTC().Format(time.RFC3339) + } + } + if len(f.Fields) > 0 { + fl := map[string]string{} + for k, v := range f.Fields { + if len(fl) >= 24 { + break + } + k = oneLine(k, 40) + if k == "" { + continue + } + fl[k] = oneLine(fmt.Sprintf("%v", v), 200) + } + if len(fl) > 0 { + m["fields"] = fl + } + } + if len(m) == 0 || (len(m) == 1 && kind != "") { + return nil + } + b, err := json.Marshal(m) + if err != nil || len(b) > opsMetaCap { + return nil + } + return b +} + // oneLine squashes metadata fields (from/subject/key) to a single trimmed // line — they land in tags and the rendered header, so newlines are out. func oneLine(v string, max int) string { diff --git a/internal/webhooks/webhooks_test.go b/internal/webhooks/webhooks_test.go index 19437cf..a70828d 100644 --- a/internal/webhooks/webhooks_test.go +++ b/internal/webhooks/webhooks_test.go @@ -1,6 +1,10 @@ package webhooks -import "testing" +import ( + "encoding/json" + "fmt" + "testing" +) func TestMatchEvent(t *testing.T) { cases := []struct { @@ -65,3 +69,59 @@ func TestValidEvents(t *testing.T) { } } } + +func TestBuildOpsMeta(t *testing.T) { + lat := int64(84) + // structured fields land; kind-only posts stay untagged (kind lives + // in tags already — meta exists for data) + m := buildOpsMeta("status", opsFields{ + Service: "api", State: "up", LatencyMs: &lat, Env: "prod", + URL: "https://grafana/d/api", Fields: map[string]any{"region": "eu"}, + At: "2026-10-12T08:00:00Z", + }) + var got map[string]any + if err := json.Unmarshal(m, &got); err != nil { + t.Fatalf("meta not json: %v", err) + } + if got["service"] != "api" || got["state"] != "up" || + got["latency_ms"] != float64(84) || got["env"] != "prod" { + t.Fatalf("meta missing fields: %v", got) + } + if fl, _ := got["fields"].(map[string]any); fl["region"] != "eu" { + t.Fatalf("fields not carried: %v", got["fields"]) + } + if got["at"] != "2026-10-12T08:00:00Z" { + t.Fatalf("at not normalized: %v", got["at"]) + } + + // nothing structured -> nil (kind alone doesn't make an ops post) + if m := buildOpsMeta("bug", opsFields{}); m != nil { + t.Fatalf("kind-only meta should be nil, got %s", m) + } + // invalid at is dropped, not fatal + m = buildOpsMeta("status", opsFields{Service: "api", State: "down", At: "not-a-time"}) + if !json.Valid(m) { + t.Fatalf("bad at produced invalid meta") + } + var g2 map[string]any + _ = json.Unmarshal(m, &g2) + if _, ok := g2["at"]; ok { + t.Fatalf("invalid at should be dropped: %v", g2) + } + // negative/garbage latency clamps instead of flowing through + neg := int64(-5) + m = buildOpsMeta("status", opsFields{Service: "api", State: "up", LatencyMs: &neg}) + var g3 map[string]any + _ = json.Unmarshal(m, &g3) + if g3["latency_ms"] != float64(0) { + t.Fatalf("negative latency not clamped: %v", g3) + } + // fields over the cap die with the meta rather than bloating the row + big := map[string]any{} + for i := 0; i < 40; i++ { + big[fmt.Sprintf("k%02d", i)] = string(make([]byte, 400)) + } + if buildOpsMeta("status", opsFields{Service: "api", State: "up", Fields: big}) != nil { + t.Fatalf("oversized meta should return nil") + } +} diff --git a/packages/api-client/src/generated/schema.ts b/packages/api-client/src/generated/schema.ts index 3a7786d..4acecbc 100644 --- a/packages/api-client/src/generated/schema.ts +++ b/packages/api-client/src/generated/schema.ts @@ -964,7 +964,7 @@ export interface paths { head?: never; /** * Rename a channel, toggle agent access, or set support-intake mode - * @description agents_blocked=true hides the channel from MCP agents entirely - its messages no longer appear in list_conversations, get_messages, send_message or search. intake_mode marks the channel as a support-intake surface: 'receive' accepts hook posts; 'chat' additionally lets the hook token pull channel messages (live support chat); '' disables intake. + * @description agents_blocked=true hides the channel from MCP agents entirely - its messages no longer appear in list_conversations, get_messages, send_message or search. intake_mode marks the channel as an intake surface: 'receive' accepts hook posts; 'chat' additionally lets the hook token pull channel messages (live support chat); 'ops' is a monitoring/command-center channel whose meta posts feed the ops summary; '' disables intake. */ patch: operations["updateChannel"]; trace?: never; @@ -1022,6 +1022,26 @@ export interface paths { patch?: never; trace?: never; }; + "/api/conversations/{conversationId}/ops": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Control-center summary over the channel's structured (meta) posts + * @description Folds meta-carrying messages into the ops surface: the latest state per service (worst first), a dense 30-day strip of worst-state-per-day buckets, per-kind counts over the 35-day window, and the newest event pointer. Channels with intake_mode="ops" show this as their header; any member can query it. + */ + get: operations["opsSummary"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/messages/{messageId}/forward": { parameters: { query?: never; @@ -2914,6 +2934,10 @@ export interface components { body: string; /** @description Free-form classification tags (frontend, backend, visual, mcp, …); lowercase slug, max 8 */ tags?: string[]; + /** @description Structured payload on ops/intake posts — kind, service, state, latency_ms, level, env, release, url, at, fields{} — rendered as a distinct card and aggregated by the ops summary */ + meta?: { + [key: string]: unknown; + } | null; /** @description Agent progress update posted without notifications — clients should not toast it */ silent?: boolean; /** @description Structured entity references extracted from the body */ @@ -3041,7 +3065,7 @@ export interface components { * @description Support-intake mode: 'receive' accepts reports; 'chat' also exposes GET /api/hooks/{token}/messages so the platform can pull replies * @enum {string} */ - intake_mode?: "" | "receive" | "chat"; + intake_mode?: "" | "receive" | "chat" | "ops"; /** * @deprecated * @description True when intake_mode is set — kept for client compatibility @@ -5584,7 +5608,7 @@ export interface operations { name?: string; agents_blocked?: boolean; /** @enum {string} */ - intake_mode?: "" | "receive" | "chat"; + intake_mode?: "" | "receive" | "chat" | "ops"; /** * @deprecated * @description Deprecated alias: true maps to intake_mode=receive, false to '' @@ -5729,6 +5753,58 @@ export interface operations { 403: components["responses"]["Forbidden"]; }; }; + opsSummary: { + parameters: { + query?: never; + header?: never; + path: { + conversationId: components["parameters"]["ConversationId"]; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Ops summary */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + /** Format: uuid */ + conversation_id: string; + /** @description Latest reported state per service, worst state first */ + services: { + service?: string; + state?: string; + /** Format: int64 */ + latency_ms?: number; + env?: string; + /** Format: date-time */ + at?: string; + /** Format: uuid */ + message_id?: string; + }[]; + /** @description 30 entries oldest→newest; 'worst' is the day's worst reported state ('no_data' when silent) */ + days: { + date?: string; + worst?: string; + events?: number; + }[]; + /** @description meta.kind → event count across the window */ + kinds: { + [key: string]: number; + }; + /** Format: date-time */ + last_event_at?: string | null; + /** Format: uuid */ + last_message_id?: string; + }; + }; + }; + 403: components["responses"]["Forbidden"]; + }; + }; forwardMessage: { parameters: { query?: never; @@ -8551,8 +8627,34 @@ export interface operations { subject?: string; /** @description Ticket key — first post opens a dedicated sub-chat; same-key posts join it */ key?: string; - /** @description Report type — free-form ('bug', 'feature', …). Overrides the hook's default kind; lands as a kind: tag and a `kind` label in the header */ + /** @description Report type — free-form ('bug', 'feature', 'status', 'error', …). Overrides the hook's default kind; lands as a kind: tag and a `kind` label in the header */ kind?: string; + /** @description Ops: the monitored entity ('api', 'web', 'db'). Latest state per service feeds the ops summary */ + service?: string; + /** @description Ops: health state — up|ok|operational, degraded|warn, down|outage|critical, maintenance; unknown values render neutral */ + state?: string; + /** + * Format: int64 + * @description Ops: probe latency in milliseconds + */ + latency_ms?: number; + /** @description Ops: log/error severity — debug|info|warn|error|fatal */ + level?: string; + /** @description Ops: environment tag (prod, staging, eu-1…) */ + env?: string; + /** @description Ops: version/commit the event belongs to */ + release?: string; + /** @description Ops: link back to the source (dashboard, run, trace) */ + url?: string; + /** @description Ops: arbitrary labelled values rendered on the message card (max 24 entries; values stringified to 200 chars) */ + fields?: { + [key: string]: unknown; + }; + /** + * Format: date-time + * @description Ops: event timestamp; defaults to receipt time. Drives service-state ordering and day buckets + */ + at?: string; attachments?: { name?: string; content_type?: string; diff --git a/packages/api-client/src/index.ts b/packages/api-client/src/index.ts index 06640ec..d60fb3d 100644 --- a/packages/api-client/src/index.ts +++ b/packages/api-client/src/index.ts @@ -1,4 +1,4 @@ -import type { components, paths } from "./generated/schema"; +import type { components, operations, paths } from "./generated/schema"; export type { components, paths }; @@ -16,6 +16,8 @@ export type CreateProjectRequest = components["schemas"]["CreateProjectRequest"] export type ProjectOverview = components["schemas"]["ProjectOverview"]; export type Conversation = components["schemas"]["Conversation"]; export type Message = components["schemas"]["Message"]; +export type OpsSummary = + operations["opsSummary"]["responses"]["200"]["content"]["application/json"]; export type MessageAuthor = components["schemas"]["MessageAuthor"]; export type MessageParent = components["schemas"]["MessageParent"]; export type MentionRef = components["schemas"]["MentionRef"]; @@ -633,7 +635,7 @@ export function createClient( input: { name?: string; agents_blocked?: boolean; - intake_mode?: "" | "receive" | "chat"; + intake_mode?: "" | "receive" | "chat" | "ops"; email_alerts?: string[]; }, ) => patch<{ channel: Channel }>(`/api/channels/${channelId}`, input), @@ -647,6 +649,8 @@ export function createClient( request<{ messages: Message[] }>( `/api/conversations/${conversationId}/pins`, ), + opsSummary: (conversationId: string) => + request(`/api/conversations/${conversationId}/ops`), saveMessage: (messageId: string, saved: boolean) => request(`/api/messages/${messageId}/save`, { method: saved ? "PUT" : "DELETE", From 8b9e4925bb8650f9feac593911754f54fa87a15f Mon Sep 17 00:00:00 2001 From: Tomas Dvorak Date: Tue, 13 Oct 2026 01:05:55 +0200 Subject: [PATCH 2/6] ci: retarget runners to self-hosted lxc-901 (hosted billing exhausted) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- .github/workflows/ci.yml | 12 ++++++------ .github/workflows/release.yml | 6 +++--- .github/workflows/tag-release.yml | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c75d0db..0dab370 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,7 +8,7 @@ on: jobs: backend: - runs-on: ubuntu-latest + runs-on: lxc-901 services: postgres: image: postgres:17 @@ -38,7 +38,7 @@ jobs: RELAY_TEST_DATABASE_URL: postgres://relay:relay@127.0.0.1:5432/relay_e2e?sslmode=disable web: - runs-on: ubuntu-latest + runs-on: lxc-901 steps: - uses: actions/checkout@v7 - uses: actions/setup-node@v7 @@ -52,7 +52,7 @@ jobs: - run: npm run build --prefix apps/web openapi: - runs-on: ubuntu-latest + runs-on: lxc-901 steps: - uses: actions/checkout@v7 - uses: actions/setup-node@v7 @@ -66,7 +66,7 @@ jobs: diff -u packages/api-client/src/generated/schema.ts /tmp/schema.ts docker: - runs-on: ubuntu-latest + runs-on: lxc-901 permissions: packages: write contents: read @@ -93,7 +93,7 @@ jobs: docker push ghcr.io/dvorinka/relay:sha-${GITHUB_SHA:0:7} desktop: - runs-on: ubuntu-latest + runs-on: lxc-901 steps: - uses: actions/checkout@v7 - uses: actions/setup-go@v7 @@ -137,7 +137,7 @@ jobs: path: apps/desktop/build/bin/relay-desktop security: - runs-on: ubuntu-latest + runs-on: lxc-901 steps: - uses: actions/checkout@v7 - uses: aquasecurity/trivy-action@master diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e833e1b..f0a422f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,7 +11,7 @@ permissions: jobs: build: - runs-on: ubuntu-latest + runs-on: lxc-901 steps: - uses: actions/checkout@v7 - uses: actions/setup-go@v7 @@ -146,7 +146,7 @@ jobs: # always set the secrets). apk: needs: build - runs-on: ubuntu-latest + runs-on: lxc-901 env: ANDROID_KEYSTORE_B64: ${{ secrets.ANDROID_KEYSTORE_B64 }} steps: @@ -194,7 +194,7 @@ jobs: # Publish the runtime image to GHCR: ghcr.io/dvorinka/relay: + :latest image: - runs-on: ubuntu-latest + runs-on: lxc-901 steps: - uses: actions/checkout@v7 - uses: docker/setup-buildx-action@v4 diff --git a/.github/workflows/tag-release.yml b/.github/workflows/tag-release.yml index af4738e..21d1594 100644 --- a/.github/workflows/tag-release.yml +++ b/.github/workflows/tag-release.yml @@ -19,7 +19,7 @@ concurrency: jobs: tag: - runs-on: ubuntu-latest + runs-on: lxc-901 steps: - uses: actions/checkout@v7 with: From 6e31b539a199d7ae134663a9d0e96d2e9c7138df Mon Sep 17 00:00:00 2001 From: Tomas Dvorak Date: Tue, 13 Oct 2026 01:07:47 +0200 Subject: [PATCH 3/6] Revert "ci: retarget runners to self-hosted lxc-901 (hosted billing exhausted)" This reverts commit 8b9e4925bb8650f9feac593911754f54fa87a15f. --- .github/workflows/ci.yml | 12 ++++++------ .github/workflows/release.yml | 6 +++--- .github/workflows/tag-release.yml | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0dab370..c75d0db 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,7 +8,7 @@ on: jobs: backend: - runs-on: lxc-901 + runs-on: ubuntu-latest services: postgres: image: postgres:17 @@ -38,7 +38,7 @@ jobs: RELAY_TEST_DATABASE_URL: postgres://relay:relay@127.0.0.1:5432/relay_e2e?sslmode=disable web: - runs-on: lxc-901 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-node@v7 @@ -52,7 +52,7 @@ jobs: - run: npm run build --prefix apps/web openapi: - runs-on: lxc-901 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-node@v7 @@ -66,7 +66,7 @@ jobs: diff -u packages/api-client/src/generated/schema.ts /tmp/schema.ts docker: - runs-on: lxc-901 + runs-on: ubuntu-latest permissions: packages: write contents: read @@ -93,7 +93,7 @@ jobs: docker push ghcr.io/dvorinka/relay:sha-${GITHUB_SHA:0:7} desktop: - runs-on: lxc-901 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-go@v7 @@ -137,7 +137,7 @@ jobs: path: apps/desktop/build/bin/relay-desktop security: - runs-on: lxc-901 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: aquasecurity/trivy-action@master diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f0a422f..e833e1b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,7 +11,7 @@ permissions: jobs: build: - runs-on: lxc-901 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: actions/setup-go@v7 @@ -146,7 +146,7 @@ jobs: # always set the secrets). apk: needs: build - runs-on: lxc-901 + runs-on: ubuntu-latest env: ANDROID_KEYSTORE_B64: ${{ secrets.ANDROID_KEYSTORE_B64 }} steps: @@ -194,7 +194,7 @@ jobs: # Publish the runtime image to GHCR: ghcr.io/dvorinka/relay: + :latest image: - runs-on: lxc-901 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: docker/setup-buildx-action@v4 diff --git a/.github/workflows/tag-release.yml b/.github/workflows/tag-release.yml index 21d1594..af4738e 100644 --- a/.github/workflows/tag-release.yml +++ b/.github/workflows/tag-release.yml @@ -19,7 +19,7 @@ concurrency: jobs: tag: - runs-on: lxc-901 + runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: From d36b6a1e689ea0bc0f1fd5e03c7347a3458ae134 Mon Sep 17 00:00:00 2001 From: Tomas Dvorak Date: Thu, 15 Oct 2026 22:07:58 +0200 Subject: [PATCH 4/6] fix(web): stop SSE retry storm when unauthenticated + root module memos MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /api/events retried with exponential backoff forever on the login screen — a 401 is permanent until the session changes, so the loop only produced noise. Now, when no token is present, a failed stream triggers one probe of /api/auth/session: 401 blocks further reconnects until the next subscribe (post-login remount), while a probe failure keeps the normal backoff for genuine network blips. Watchdog and visibility handlers skip the blocked state. stores/unread: two module-scope createMemo + one createEffect had no owner, so dev mode warned "computations created outside createRoot". Wrapped in detached roots — the store is app-lifetime by design. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- apps/web/src/lib/events.ts | 39 +++++++++++++++++++++++++++++++---- apps/web/src/stores/unread.ts | 30 ++++++++++++++++----------- 2 files changed, 53 insertions(+), 16 deletions(-) diff --git a/apps/web/src/lib/events.ts b/apps/web/src/lib/events.ts index 94c010e..d2eff8f 100644 --- a/apps/web/src/lib/events.ts +++ b/apps/web/src/lib/events.ts @@ -27,6 +27,10 @@ let bridged = false; const HEARTBEAT_MISS_MS = 75_000; let lastFrame = Date.now(); let everConnected = false; +// A 401 is permanent until the session changes — retrying it just spams +// the network tab on the login screen. Probed once per failure burst. +let authBlocked = false; +let authProbe: Promise | undefined; let watchdog: ReturnType | undefined; let visBound = false; let upBound = false; @@ -58,7 +62,7 @@ function resyncSoon() { function startWatchdog() { if (!watchdog) { watchdog = setInterval(() => { - if (net.isLocal()) return; + if (net.isLocal() || authBlocked) return; if (Date.now() - lastFrame > HEARTBEAT_MISS_MS) connect(); }, 15_000); } @@ -68,6 +72,7 @@ function startWatchdog() { if ( document.visibilityState === "visible" && !net.isLocal() && + !authBlocked && Date.now() - lastFrame > HEARTBEAT_MISS_MS ) { connect(); @@ -112,6 +117,7 @@ function connectBridge(token: string): boolean { function connect() { const wasConnected = everConnected; + authBlocked = false; source?.close(); bridged = false; if (retry) { @@ -147,12 +153,37 @@ function connect() { }; es.onerror = () => { es.close(); - // backoff: 1s, 2s, 4s … capped at 30s - const delay = Math.min(30000, 1000 * 2 ** attempts++); - retry = setTimeout(connect, delay); + if (source === es) source = undefined; + // No token means auth is cookie-only or absent — one cheap probe + // distinguishes "session expired/absent" (stop) from a network blip + // (back off and retry). + if (!token) { + authProbe ??= fetch(`${base}/api/auth/session`) + .then((r) => r.ok) + .catch(() => true) // probe unreachable: treat as blip, keep retrying + .finally(() => { + authProbe = undefined; + }); + void authProbe.then((authed) => { + if (!authed) { + authBlocked = true; + return; + } + scheduleRetry(); + }); + return; + } + scheduleRetry(); }; } +// backoff: 1s, 2s, 4s … capped at 30s +function scheduleRetry() { + if (authBlocked) return; + const delay = Math.min(30000, 1000 * 2 ** attempts++); + retry = setTimeout(connect, delay); +} + // emitLocal feeds a synthetic event to subscribers. Local mode has no SSE; // the adapter uses this for updates a live view needs (e.g. a thread's // reply count on the parent message). diff --git a/apps/web/src/stores/unread.ts b/apps/web/src/stores/unread.ts index 2e4930a..66fe185 100644 --- a/apps/web/src/stores/unread.ts +++ b/apps/web/src/stores/unread.ts @@ -1,4 +1,4 @@ -import { createEffect, createMemo, createSignal } from "solid-js"; +import { createEffect, createMemo, createRoot, createSignal } from "solid-js"; import type { UnreadConversation } from "@relay/api-client"; import { api } from "../lib/api"; import { desktopSetUnread } from "../lib/desktop"; @@ -21,14 +21,18 @@ export function useUnreadConversations() { return { unreadConversations }; } -// issue_id -> unread count, for marking issue rows. -const unreadByIssueMap = createMemo(() => { - const m = new Map(); - for (const c of unreadConversations()) { - if (c.kind === "issue" && c.issue_id) m.set(c.issue_id, c.unread); - } - return m; -}); +// issue_id -> unread count, for marking issue rows. Module-scope memos and +// effects need an owner or Solid warns they can never be disposed — this +// store is app-lifetime by design, so a detached root is correct. +const unreadByIssueMap = createRoot(() => + createMemo(() => { + const m = new Map(); + for (const c of unreadConversations()) { + if (c.kind === "issue" && c.issue_id) m.set(c.issue_id, c.unread); + } + return m; + }), +); export function useUnreadByIssue() { return unreadByIssueMap; @@ -36,10 +40,12 @@ export function useUnreadByIssue() { // Total unread across conversations — bridged to the desktop shell's // window title and tray badge. The effect is a no-op in a plain browser. -const unreadTotal = createMemo(() => - unreadConversations().reduce((sum, c) => sum + c.unread, 0), +const unreadTotal = createRoot(() => + createMemo(() => + unreadConversations().reduce((sum, c) => sum + c.unread, 0), + ), ); -createEffect(() => desktopSetUnread(unreadTotal())); +createRoot(() => createEffect(() => desktopSetUnread(unreadTotal()))); export function usePendingReviews() { return { pendingReviews }; From d9557b28033b74cce2206be5db98743ad4e59768 Mon Sep 17 00:00:00 2001 From: Tomas Dvorak Date: Thu, 29 Oct 2026 10:13:02 +0100 Subject: [PATCH 5/6] fix(web): keep navigation on phones and make local channels real The left rail hid itself inside channels and threads, and light mode on a phone was near-white. Phones now keep a 56px icon rail on every project, channel, and thread; the full list opens as a drawer. Threads cover only the conversation column. Swipe right replies, swipe left opens a thread, and swipe right on the thread closes it. Phone light mode uses a warm gray. Local mode listed a new project twice and threw when the rail asked for channels. Creating a project replaces by id, channels can be created and deleted offline, and unknown local calls say they need a server instead of throwing. CLI --help no longer prints a live token. Authored By: TDvorak --- apps/web/src/components/Rail.tsx | 41 ++-- .../features/conversations/Conversation.tsx | 112 ++++++++-- .../web/src/features/projects/ChannelPage.tsx | 9 + apps/web/src/index.css | 19 ++ apps/web/src/lib/local.test.ts | 24 ++- apps/web/src/lib/local.ts | 201 +++++++++++++++++- apps/web/src/lib/swipe.test.ts | 15 ++ apps/web/src/lib/swipe.ts | 16 ++ apps/web/src/pages/Home.tsx | 8 +- apps/web/src/stores/nav.ts | 20 +- apps/web/src/stores/projects.tsx | 7 +- cmd/relay-cli/main.go | 14 +- 12 files changed, 437 insertions(+), 49 deletions(-) create mode 100644 apps/web/src/lib/swipe.test.ts create mode 100644 apps/web/src/lib/swipe.ts diff --git a/apps/web/src/components/Rail.tsx b/apps/web/src/components/Rail.tsx index a0fb412..03413c1 100644 --- a/apps/web/src/components/Rail.tsx +++ b/apps/web/src/components/Rail.tsx @@ -25,7 +25,7 @@ import { } from "../lib/updates"; import { subscribe } from "../lib/events"; import { deriveKey, initials } from "../lib/text"; -import { useNav } from "../stores/nav"; +import { useNarrow, useNav } from "../stores/nav"; import { setProjectOrder, setProjectSort, @@ -120,7 +120,7 @@ function ProjectRow(props: { aria-label={expanded() ? "Hide channels" : "Show channels"} aria-expanded={expanded()} onClick={() => setManual(!expanded())} - class="hidden shrink-0 rounded p-0.5 text-faint transition-colors hover:text-fg sm:block" + class="shrink-0 rounded p-0.5 text-faint transition-colors hover:text-fg" > void }) { export function Rail() { const session = useSession(); const projects = useProjects(); - const { navOpen, closeNav } = useNav(); + const { navOpen, openNav, closeNav } = useNav(); + const narrow = useNarrow(); + // On a phone the aside is either the icon rail or the overlay drawer. + // Desktop keeps the resizable column. The drawer sits above thread panels. + const drawer = () => narrow() && navOpen(); const [creating, setCreating] = createSignal(false); onMount(refreshUnread); const unsub = subscribe((e) => { @@ -842,27 +846,32 @@ export function Rail() { return ( <> - + +

+ Swipe right to reply · swipe left for the thread +

{ fileEl = el; @@ -4987,6 +5022,7 @@ function ThreadPanel(props: { thread: ThreadSummary; onClose: () => void; }) { + const narrow = useNarrow(); const [width, setWidth] = createSignal(threadWidth()); const [full, setFull] = createSignal(false); const [idCopied, setIdCopied] = createSignal(false); @@ -4994,9 +5030,22 @@ function ThreadPanel(props: { const [expiresAt, setExpiresAt] = createSignal( undefined, ); + // reply_count arrives as a snapshot in ThreadSummary; the panel is open + // while replies land, so it tracks thread.updated frames itself. + const [replyCount, setReplyCount] = createSignal(props.thread.reply_count); let expiryWrapEl: HTMLDivElement | undefined; let dragging = false; + onMount(() => + onCleanup( + subscribe((e) => { + if (e.type !== "thread.updated" && e.type !== "thread.created") return; + const t = e.data?.thread as Thread | undefined; + if (t?.id === props.thread.id) setReplyCount(t.reply_count); + }), + ), + ); + createEffect(() => { if (!expiryOpen()) return; // read current expiry once per open — the index endpoint already lists it @@ -5063,14 +5112,42 @@ function ThreadPanel(props: { onMount(() => window.addEventListener("keydown", onKey)); onCleanup(() => window.removeEventListener("keydown", onKey)); + // Swipe right closes the thread. The gesture ignores fields so a + // composer drag does not dismiss the panel. + let swipeStart: { x: number; y: number } | null = null; + const onSwipeStart = (e: TouchEvent) => { + const t = e.touches[0]; + const el = e.target as HTMLElement | null; + if (!t || el?.closest("textarea, input, button, a")) { + swipeStart = null; + return; + } + swipeStart = { x: t.clientX, y: t.clientY }; + }; + const onSwipeEnd = (e: TouchEvent) => { + const start = swipeStart; + swipeStart = null; + const t = e.changedTouches[0]; + if (!start || !t) return; + if (horizontalSwipe(t.clientX - start.x, t.clientY - start.y, 72) === "right") { + props.onClose(); + } + }; + + // Cover the conversation column, never the app rail or the top bar. + // Fullscreen and phones overlay the chat; sm+ sits beside it. + const overlay = () => full() || narrow(); + return (

- {props.thread.reply_count}{" "} - {props.thread.reply_count === 1 ? "reply" : "replies"} + {replyCount()} {replyCount() === 1 ? "reply" : "replies"}

(expiryWrapEl = el)}> @@ -5245,7 +5321,7 @@ export function Conversation(props: { } > {(c) => ( -
+
+ # {}, clear: () => {}, }); -const { dumpLocal, importRemoteSnapshot, remoteOriginOf } = await import( +const { dumpLocal, importRemoteSnapshot, local, remoteOriginOf } = await import( "./local" ); @@ -155,3 +155,25 @@ describe("importRemoteSnapshot", () => { expect(remoteOriginOf("pX")).toBeUndefined(); }); }); + +describe("local channels", () => { + it("lists one row per project and keeps channels off the main chat", async () => { + const p = await local.createProject({ name: "Phone Nav Test" }); + dumpLocal().projects.push({ ...p }); + const listed = await local.listProjects(); + expect(listed.projects.filter((x) => x.id === p.id)).toHaveLength(1); + + const main = await local.projectConversation(p.id); + const { channel } = await local.createChannel(p.id, " ops "); + expect(channel.name).toBe("ops"); + expect((await local.projectConversation(p.id)).id).toBe(main.id); + expect((await local.listChannels(p.id)).channels.map((c) => c.name)).toEqual([ + "ops", + ]); + await expect(local.createChannel(p.id, "OPS")).rejects.toThrow( + /already exists/, + ); + await local.deleteChannel(channel.id); + expect((await local.listChannels(p.id)).channels).toHaveLength(0); + }); +}); diff --git a/apps/web/src/lib/local.ts b/apps/web/src/lib/local.ts index 0cbbdec..bfcf976 100644 --- a/apps/web/src/lib/local.ts +++ b/apps/web/src/lib/local.ts @@ -31,6 +31,7 @@ import { type Project, type Reaction, type SearchResults, + type Channel, type Thread, type Todo, type User, @@ -49,9 +50,19 @@ interface LocalThread { parent_message_id: string; parent_conversation: string; title: string | null; + expires_at?: string | null; created_at: string; } +// Channel name and flags ride on the conversation row. The wire Conversation +// type has no name; these fields round-trip through the JSON doc. +type ChannelConv = Conversation & { + name?: string | null; + agents_blocked?: boolean; + intake_mode?: "" | "receive" | "chat" | "ops"; + email_alerts?: string[]; +}; + interface LocalDB { user: User; workspace: WorkspaceWithRole; @@ -126,6 +137,13 @@ export const localReady: Promise = (async () => { const saved = await localStore.get("doc"); if (saved) { db = { ...emptyDB(), ...saved }; + // A create that appended onto the live list used to persist the same + // project twice. Drop the extras once so the rail stays a single row. + const projects = uniqueById(db.projects); + if (projects.length !== db.projects.length) { + db.projects = projects; + save(); + } await rehydrateUrls(); return; } @@ -236,10 +254,22 @@ const me = () => ({ const findMessage = (id: string) => db.messages.find((m) => m.id === id); const findIssue = (id: string) => db.issues.find((i) => i.id === id); +function uniqueById(list: T[] | undefined): T[] { + const seen = new Set(); + const out: T[] = []; + for (const item of list ?? []) { + if (!item?.id || seen.has(item.id)) continue; + seen.add(item.id); + out.push(item); + } + return out; +} + const convOf = (projectId: string, issueId?: string) => db.conversations.find( (c) => c.kind !== "thread" && + c.kind !== "channel" && c.project_id === projectId && (c.issue_id ?? null) === (issueId ?? null), ); @@ -320,10 +350,45 @@ function threadOut(t: LocalThread): Thread { ? { author: parent.author.name, preview: parent.body.slice(0, 160) } : { author: "Deleted", preview: "Original message was deleted" }, last_reply_at: replies.at(-1)?.created_at ?? null, + expires_at: t.expires_at ?? null, created_at: t.created_at, }; } +function threadLive(t: LocalThread): boolean { + if (!t.expires_at) return true; + const at = Date.parse(t.expires_at); + return Number.isNaN(at) || at > Date.now(); +} + +function channelName(raw: string): string { + const s = raw.trim().replace(/\s+/g, " "); + if ([...s].length < 1 || [...s].length > 60) return ""; + return s; +} + +function asChannel(c: Conversation): Channel { + const x = c as ChannelConv; + const mode = x.intake_mode ?? ""; + return { + id: c.id, + project_id: c.project_id, + kind: "channel", + name: x.name ?? null, + agents_blocked: !!x.agents_blocked, + intake_mode: mode, + intake: mode !== "", + email_alerts: x.email_alerts ?? [], + created_at: c.created_at, + }; +} + +function findChannel(channelId: string): ChannelConv { + const c = db.conversations.find((x) => x.id === channelId); + if (!c || c.kind !== "channel") notFound(); + return c as ChannelConv; +} + // --- the adapter surface (subset of the server client) --- const impl = { @@ -340,7 +405,7 @@ const impl = { members: [{ user: db.user, role: "owner" }], }), - listProjects: async () => ({ projects: db.projects }), + listProjects: async () => ({ projects: uniqueById(db.projects) }), createProject: async (input: { name: string; key?: string; @@ -442,6 +507,7 @@ const impl = { }, listThreads: async (projectId: string) => ({ threads: db.threads + .filter(threadLive) .filter( (t) => db.conversations.find((c) => c.id === t.parent_conversation) @@ -455,6 +521,126 @@ const impl = { ) .map(threadOut), }), + setThreadExpiry: async (conversationId: string, expiresAt: string | null) => { + const t = db.threads.find((x) => x.id === conversationId); + if (!t) notFound(); + t.expires_at = expiresAt; + save(); + const live = threadLive(t); + emitLocal({ + type: live ? "thread.updated" : "thread.deleted", + project_id: + db.conversations.find((c) => c.id === t.parent_conversation) + ?.project_id ?? "", + data: { thread: threadOut(t) }, + }); + return { thread: live ? threadOut(t) : null, deleted: !live }; + }, + listChannels: async (projectId: string) => ({ + channels: db.conversations + .filter((c) => c.kind === "channel" && c.project_id === projectId) + .sort((a, b) => a.created_at.localeCompare(b.created_at)) + .map(asChannel), + }), + createChannel: async (projectId: string, name: string) => { + if (!db.projects.some((p) => p.id === projectId)) notFound(); + const n = channelName(name); + if (!n) { + throw new ApiClientError(400, "channel name must be 1-60 characters"); + } + const taken = db.conversations.some( + (c) => + c.kind === "channel" && + c.project_id === projectId && + (c as ChannelConv).name?.toLowerCase() === n.toLowerCase(), + ); + if (taken) { + throw new ApiClientError(409, "a channel with that name already exists"); + } + const conv: ChannelConv = { + id: uuid(), + project_id: projectId, + kind: "channel", + issue_id: null, + name: n, + agents_blocked: false, + intake_mode: "", + email_alerts: [], + created_at: now(), + }; + db.conversations.push(conv); + save(); + const channel = asChannel(conv); + emitLocal({ + type: "channel.created", + project_id: projectId, + data: { channel }, + }); + return { channel }; + }, + updateChannel: async ( + channelId: string, + input: { + name?: string; + agents_blocked?: boolean; + intake_mode?: "" | "receive" | "chat" | "ops"; + email_alerts?: string[]; + }, + ) => { + const c = findChannel(channelId); + if (input.name != null) { + const n = channelName(input.name); + if (!n) { + throw new ApiClientError(400, "channel name must be 1-60 characters"); + } + const taken = db.conversations.some( + (x) => + x.id !== c.id && + x.kind === "channel" && + x.project_id === c.project_id && + (x as ChannelConv).name?.toLowerCase() === n.toLowerCase(), + ); + if (taken) { + throw new ApiClientError( + 409, + "a channel with that name already exists", + ); + } + c.name = n; + } + if (input.agents_blocked != null) c.agents_blocked = input.agents_blocked; + if (input.intake_mode != null) c.intake_mode = input.intake_mode; + if (input.email_alerts != null) c.email_alerts = input.email_alerts; + save(); + const channel = asChannel(c); + emitLocal({ + type: "channel.updated", + project_id: c.project_id, + data: { channel }, + }); + return { channel }; + }, + deleteChannel: async (channelId: string) => { + const c = findChannel(channelId); + const threadIds = new Set( + db.threads + .filter((t) => t.parent_conversation === channelId) + .map((t) => t.id), + ); + db.threads = db.threads.filter((t) => !threadIds.has(t.id)); + db.conversations = db.conversations.filter( + (x) => x.id !== channelId && !threadIds.has(x.id), + ); + db.messages = db.messages.filter( + (m) => m.conversation_id !== channelId && !threadIds.has(m.conversation_id), + ); + save(); + emitLocal({ + type: "channel.deleted", + project_id: c.project_id, + data: { channel_id: channelId }, + }); + }, listMessages: async ( conversationId: string, @@ -637,6 +823,8 @@ const impl = { }, markMessageRead: async () => undefined, markConversationRead: async () => undefined, + sendTyping: async () => undefined, + listScheduledMessages: async () => ({ scheduled: [] }), listIssues: async ( projectId: string, @@ -1270,12 +1458,15 @@ const impl = { // object URL for an already-loaded attachment (img src can't await). const SYNC_READS = new Set(["attachmentURL"]); export const local = new Proxy(impl, { - get(t, k: string) { + get(t, k: string | symbol) { + if (typeof k !== "string") return undefined; if (SYNC_READS.has(k)) return t[k as keyof typeof t]; + const fn = t[k as keyof typeof t]; + // Unknown methods stay undefined so api.ts can say the call needs a + // server, instead of throwing "t[k] is not a function". + if (typeof fn !== "function") return undefined; return (...args: unknown[]) => - localReady.then(() => - (t[k as keyof typeof t] as (...a: unknown[]) => unknown)(...args), - ); + localReady.then(() => (fn as (...a: unknown[]) => unknown)(...args)); }, }) as typeof impl; diff --git a/apps/web/src/lib/swipe.test.ts b/apps/web/src/lib/swipe.test.ts new file mode 100644 index 0000000..98282b4 --- /dev/null +++ b/apps/web/src/lib/swipe.test.ts @@ -0,0 +1,15 @@ +import { describe, expect, it } from "vitest"; +import { horizontalSwipe } from "./swipe"; + +describe("horizontalSwipe", () => { + it("ignores vertical scrolls", () => { + expect(horizontalSwipe(20, 80)).toBeNull(); + expect(horizontalSwipe(-40, 40)).toBeNull(); + }); + + it("requires the threshold", () => { + expect(horizontalSwipe(55, 0)).toBeNull(); + expect(horizontalSwipe(56, 10)).toBe("right"); + expect(horizontalSwipe(-56, 4)).toBe("left"); + }); +}); diff --git a/apps/web/src/lib/swipe.ts b/apps/web/src/lib/swipe.ts new file mode 100644 index 0000000..65ad740 --- /dev/null +++ b/apps/web/src/lib/swipe.ts @@ -0,0 +1,16 @@ +// Horizontal gesture decision shared by message rows, the thread panel, +// and the nav edge swipe. Vertical movement wins so a scroll never +// becomes a reply or a back. + +export type HSwipe = "left" | "right" | null; + +export function horizontalSwipe( + dx: number, + dy: number, + threshold = 56, +): HSwipe { + if (Math.abs(dy) >= Math.abs(dx)) return null; + if (dx >= threshold) return "right"; + if (dx <= -threshold) return "left"; + return null; +} diff --git a/apps/web/src/pages/Home.tsx b/apps/web/src/pages/Home.tsx index 8399e6f..e88e05f 100644 --- a/apps/web/src/pages/Home.tsx +++ b/apps/web/src/pages/Home.tsx @@ -180,15 +180,17 @@ export default function Home() { - {totals().issues} open issues + {totals().issues} open{" "} + {totals().issues === 1 ? "issue" : "issues"} - {totals().prs} open PRs + {totals().prs} open{" "} + {totals().prs === 1 ? "PR" : "PRs"} 0}> {totals().reviews}{" "} - reviews pending + {totals().reviews === 1 ? "review" : "reviews"} pending
diff --git a/apps/web/src/stores/nav.ts b/apps/web/src/stores/nav.ts index d013489..5a36112 100644 --- a/apps/web/src/stores/nav.ts +++ b/apps/web/src/stores/nav.ts @@ -8,10 +8,24 @@ export function useNav() { return { navOpen, toggleNav: () => setNavOpen((v) => !v), + openNav: () => setNavOpen(true), closeNav: () => setNavOpen(false), }; } +// Phones and narrow windows keep a permanent icon rail. The full project +// list is the drawer. md (768px) is where the rail becomes the desktop column. +const narrowQuery = + typeof window !== "undefined" + ? window.matchMedia("(max-width: 767.98px)") + : null; +const [narrow, setNarrow] = createSignal(narrowQuery?.matches ?? false); +narrowQuery?.addEventListener("change", (e) => setNarrow(e.matches)); + +export function useNarrow() { + return narrow; +} + // Phone gesture: swipe in from the left edge opens the drawer, a leftward // fling while it's open closes it — the same convention every mobile app // with a side drawer uses. Vertical scrolls are ignored by the axis check. @@ -25,9 +39,9 @@ export function initNavSwipe() { (e) => { const t = e.touches[0]; if (!t) return; - // opening requires starting at the screen edge; closing works anywhere - // (when open, the drawer + backdrop cover the content anyway) - tracking = (!navOpen() && t.clientX <= 28) || navOpen(); + // Opening starts on the icon rail (3.5rem). Closing works anywhere — + // the drawer and its backdrop cover the content. + tracking = (!navOpen() && t.clientX <= 56) || navOpen(); x0 = t.clientX; y0 = t.clientY; }, diff --git a/apps/web/src/stores/projects.tsx b/apps/web/src/stores/projects.tsx index 9ad3595..d98aaef 100644 --- a/apps/web/src/stores/projects.tsx +++ b/apps/web/src/stores/projects.tsx @@ -86,7 +86,12 @@ export function ProjectsProvider(props: ParentProps) { sorted, create: async (input) => { const project = await api.createProject(input); - mutate((list) => [...(list ?? []), project]); + // Local mode's list is the same array createProject just pushed + // onto. Appending again paints the new project twice. + mutate((list) => [ + ...(list ?? []).filter((p) => p.id !== project.id), + project, + ]); return project; }, refresh: async () => { diff --git a/cmd/relay-cli/main.go b/cmd/relay-cli/main.go index 94ed097..73ba36a 100644 --- a/cmd/relay-cli/main.go +++ b/cmd/relay-cli/main.go @@ -58,8 +58,10 @@ import ( ) var ( - flagURL = flag.String("url", envOr("RELAY_URL", "http://localhost:8080"), "Relay base URL") - flagToken = flag.String("token", os.Getenv("RELAY_TOKEN"), "rly_ agent token") + flagURL = flag.String("url", envOr("RELAY_URL", "http://localhost:8080"), "Relay base URL") + // Empty default on purpose: flag.PrintDefaults echoes defaults into + // --help, and a live rly_ token must never land in that output. + flagToken = flag.String("token", "", "rly_ agent token (default: $RELAY_TOKEN)") flagJSON = flag.Bool("json", false, "raw JSON output") flagOut = flag.String("out", "", "attachment output file") flagLimit = flag.Int("limit", 30, "message/issue list size") @@ -201,11 +203,15 @@ func (s *session) tool(name string, args map[string]any) (json.RawMessage, error } func connect() *session { - if *flagToken == "" { + token := *flagToken + if token == "" { + token = os.Getenv("RELAY_TOKEN") + } + if token == "" { fail("RELAY_TOKEN unset — mint one in the app (agent settings) or run:", " relay-cli redeem --name my-agent") } - s := &session{hc: &http.Client{Timeout: 90 * time.Second}, relays: strings.TrimRight(*flagURL, "/"), token: *flagToken} + s := &session{hc: &http.Client{Timeout: 90 * time.Second}, relays: strings.TrimRight(*flagURL, "/"), token: token} _, err := s.call("initialize", map[string]any{ "protocolVersion": "2025-06-18", "capabilities": map[string]any{}, From 93d9c72e10fa578e4a34d897966724d32342edf5 Mon Sep 17 00:00:00 2001 From: Tomas Dvorak Date: Thu, 29 Oct 2026 10:24:18 +0100 Subject: [PATCH 6/6] fix(deps): patch Echo and DOMPurify advisories Desktop was on labstack/echo v4.15.3, which Trivy flags as a critical WebSocket upgrade bypass fixed in v4.16.1. The web app locked DOMPurify 3.4.16; 3.4.17 closes the template-bypass advisory. Main's security job is already red on both, so this pull request would not go green without the bumps. Authored By: TDvorak --- apps/desktop/go.mod | 4 ++-- apps/desktop/go.sum | 8 ++++---- apps/web/package.json | 2 +- package-lock.json | 8 ++++---- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/apps/desktop/go.mod b/apps/desktop/go.mod index 9fcf213..d3458de 100644 --- a/apps/desktop/go.mod +++ b/apps/desktop/go.mod @@ -18,13 +18,13 @@ require ( github.com/google/uuid v1.6.0 // indirect github.com/gorilla/websocket v1.5.3 // indirect github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect - github.com/labstack/echo/v4 v4.15.3 // indirect + github.com/labstack/echo/v4 v4.16.1 // indirect github.com/labstack/gommon v0.5.0 // indirect github.com/leaanthony/go-ansi-parser v1.6.1 // indirect github.com/leaanthony/gosod v1.0.4 // indirect github.com/leaanthony/slicer v1.6.0 // indirect github.com/leaanthony/u v1.1.1 // indirect - github.com/mattn/go-colorable v0.1.14 // indirect + github.com/mattn/go-colorable v0.1.15 // indirect github.com/mattn/go-isatty v0.0.22 // indirect github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect github.com/pkg/errors v0.9.1 // indirect diff --git a/apps/desktop/go.sum b/apps/desktop/go.sum index 1e16a79..f4c4dae 100644 --- a/apps/desktop/go.sum +++ b/apps/desktop/go.sum @@ -16,8 +16,8 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck= github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs= -github.com/labstack/echo/v4 v4.15.3 h1:lIdG4kK5RdMyhwCwSc4AmSQsLBb3AVwok6S8PX/9kwQ= -github.com/labstack/echo/v4 v4.15.3/go.mod h1:Xzp1Ns1RA2c9fY7nSgUJkpkUZGNbEIVHZbtbOMPktBI= +github.com/labstack/echo/v4 v4.16.1 h1:h05NuF1GvNu6jSAZxOv++AdjD/NJK+mZdGy0thiiuns= +github.com/labstack/echo/v4 v4.16.1/go.mod h1:V/EQaTVHYJH92QhbQe7kFQ4mjgcjxLQQUQtAN87zZdw= github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c= github.com/labstack/gommon v0.5.0/go.mod h1:Rzlg7HHy1maLfzBYGg9NZcVuz1sA68HHhLjhcEllYE0= github.com/leaanthony/debme v1.2.1 h1:9Tgwf+kjcrbMQ4WnPcEIUcQuIZYqdWftzZkBr+i/oOc= @@ -33,8 +33,8 @@ github.com/leaanthony/u v1.1.1/go.mod h1:9+o6hejoRljvZ3BzdYlVL0JYCwtnAsVuN9pVTQc github.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= github.com/matryer/is v1.4.1 h1:55ehd8zaGABKLXQUe2awZ99BD/PTc2ls+KV/dXphgEQ= github.com/matryer/is v1.4.1/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU= -github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= -github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= +github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4= github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= diff --git a/apps/web/package.json b/apps/web/package.json index 0593367..a38d76b 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -17,7 +17,7 @@ "@excalidraw/excalidraw": "0.18.1", "@relay/api-client": "0.0.0", "@solidjs/router": "1.0.0", - "dompurify": "^3.4.16", + "dompurify": "^3.4.17", "marked": "^18.0.13", "react": "19.3.0", "react-dom": "19.3.0", diff --git a/package-lock.json b/package-lock.json index 67efb94..8a95ad3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -27,7 +27,7 @@ "@excalidraw/excalidraw": "0.18.1", "@relay/api-client": "0.0.0", "@solidjs/router": "1.0.0", - "dompurify": "^3.4.16", + "dompurify": "^3.4.17", "marked": "^18.0.13", "react": "19.3.0", "react-dom": "19.3.0", @@ -5203,9 +5203,9 @@ "license": "MIT" }, "node_modules/dompurify": { - "version": "3.4.16", - "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.16.tgz", - "integrity": "sha512-sqo+pNp3qRhCIpbgRi1y8Tgk27Bo2Ry7w0dC1NBeNTdZChWjz9Xb/KOoZbRP/R6pQZ80Qw8YhXw13hWWBbMRnQ==", + "version": "3.4.17", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz", + "integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==", "license": "(MPL-2.0 OR Apache-2.0)", "optionalDependencies": { "@types/trusted-types": "^2.0.7"