Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,60 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@hivegrid/db/audit-events.server", () => ({ createAuditEvent: vi.fn() }));
vi.mock("@hivegrid/db/admin-sso.server", () => ({ appendPreauthAdminSsoAuditEvent: vi.fn() }));
vi.mock("@hivegrid/db/rls-context.server", () => ({ getRlsExecutionContext: vi.fn() }));
vi.mock("~/utils/server/IpUtils", () => ({ getTrustedClientIpOrNull: vi.fn(() => "192.0.2.1") }));
import { appendPreauthAdminSsoAuditEvent } from "@hivegrid/db/admin-sso.server";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { writeAdminSsoAuditEvent } from "./audit.server";
describe("Admin SSO audit RLS boundary", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(getRlsExecutionContext).mockReturnValue(null);
});
it("uses the narrow platform append capability before an operator identity exists", async () => {
await writeAdminSsoAuditEvent({
action: "admin.login.sso.failure",
request: new Request("https://admin.example.test/auth/admin/callback", { headers: { "user-agent": "test-agent" } }),
meta: { stage: "claims" },
});
expect(appendPreauthAdminSsoAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
action: "admin.login.sso.failure",
actorType: "admin",
sourceModule: "admin-sso",
outcome: "failure",
})
);
expect(createAuditEvent).not.toHaveBeenCalled();
});
it("uses the regular operator-scoped chain once app.user_id is bound", async () => {
vi.mocked(getRlsExecutionContext).mockReturnValue({ userId: "admin_1" });
await writeAdminSsoAuditEvent({
action: "admin.login.sso.success",
actorAdminUserId: "admin_1",
});
expect(createAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
action: "admin.login.sso.success",
actorId: "admin_1",
outcome: "success",
})
);
expect(appendPreauthAdminSsoAuditEvent).not.toHaveBeenCalled();
});
it("keeps audit failures non-blocking for the login flow", async () => {
vi.mocked(appendPreauthAdminSsoAuditEvent).mockRejectedValueOnce(new Error("database unavailable"));
await expect(writeAdminSsoAuditEvent({ action: "admin.login.sso.failure" })).resolves.toBeUndefined();
});
});
@@ -6,7 +6,10 @@
* `@hivegrid/db/audit-events.server` which already handles redaction.
*/
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { appendPreauthAdminSsoAuditEvent } from "@hivegrid/db/admin-sso.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import { getTrustedClientIpOrNull } from "~/utils/server/IpUtils";
export type AdminSsoAuditAction =
| "admin.login.sso.success"
@@ -27,8 +30,7 @@ export type AdminSsoAuditInput = {
function clientMeta(request: Request | undefined): { ip: string | null; userAgent: string | null } {
if (!request) return { ip: null, userAgent: null };
const fwd = request.headers.get("x-forwarded-for") ?? "";
const ip = fwd.split(",")[0]?.trim() || request.headers.get("x-real-ip") || null;
const ip = getTrustedClientIpOrNull(request);
const userAgent = request.headers.get("user-agent") || null;
return { ip, userAgent };
}
@@ -36,17 +38,25 @@ function clientMeta(request: Request | undefined): { ip: string | null; userAgen
export async function writeAdminSsoAuditEvent(input: AdminSsoAuditInput): Promise<void> {
const { ip, userAgent } = clientMeta(input.request);
try {
await createAuditEvent({
const auditInput = {
action: input.action,
actorType: "admin",
actorId: input.actorAdminUserId ?? null,
sourceModule: "admin-sso",
outcome: input.action.endsWith(".failure") ? "failure" : "success",
dataSensitivity: "internal",
metadata: {
ssoSubjectId: input.ssoSubjectId ?? null,
ip,
userAgent,
...input.meta,
} as unknown as Prisma.InputJsonValue,
});
} as const;
if (getRlsExecutionContext()?.userId) {
await createAuditEvent(auditInput);
} else {
await appendPreauthAdminSsoAuditEvent(auditInput);
}
} catch {
// Audit failures must never block the auth flow. The DB-level error
// already lands in Sentry via the audit-events boundary.
@@ -1,32 +1,5 @@
import { describe, expect, it } from "vitest";
import { extractAdminSsoClaims, hasAllowedAdminGroup, isAllowedAdminGroup, mapGroupsToRole } from "./claims.server";
describe("mapGroupsToRole", () => {
it("maps hivegrid-admin to super_admin", () => {
expect(mapGroupsToRole(["hivegrid-admin"])).toBe("super_admin");
});
it("maps hivegrid-staff to staff", () => {
expect(mapGroupsToRole(["hivegrid-staff"])).toBe("staff");
});
it("prefers super_admin when both groups are present", () => {
expect(mapGroupsToRole(["hivegrid-staff", "hivegrid-admin"])).toBe("super_admin");
});
it("returns null for an unknown group", () => {
expect(mapGroupsToRole(["random-group"])).toBeNull();
});
it("returns null for an empty list", () => {
expect(mapGroupsToRole([])).toBeNull();
});
it("returns null for null/undefined input", () => {
expect(mapGroupsToRole(undefined)).toBeNull();
expect(mapGroupsToRole(null)).toBeNull();
});
});
import { extractAdminSsoClaims, hasAllowedAdminGroup, isAllowedAdminGroup } from "./claims.server";
describe("isAllowedAdminGroup / hasAllowedAdminGroup", () => {
it("recognizes the two allowlisted groups", () => {
@@ -44,6 +17,12 @@ describe("isAllowedAdminGroup / hasAllowedAdminGroup", () => {
it("returns true when at least one allowed group is present", () => {
expect(hasAllowedAdminGroup(["other", "hivegrid-staff"])).toBe(true);
});
it("treats both allowed groups identically as access gates", () => {
expect(hasAllowedAdminGroup(["hivegrid-admin"])).toBe(true);
expect(hasAllowedAdminGroup(["hivegrid-staff"])).toBe(true);
expect(hasAllowedAdminGroup(["hivegrid-staff", "hivegrid-admin"])).toBe(true);
});
});
describe("extractAdminSsoClaims", () => {
@@ -53,6 +32,7 @@ describe("extractAdminSsoClaims", () => {
email_verified: true,
name: "Admin Person",
groups: ["hivegrid-admin"],
amr: ["pwd", "mfa"],
};
it("extracts and normalizes a valid claim set", () => {
@@ -64,6 +44,7 @@ describe("extractAdminSsoClaims", () => {
expect(result.claims.name).toBe("Admin Person");
expect(result.claims.groups).toEqual(["hivegrid-admin"]);
expect(result.claims.emailVerified).toBe(true);
expect(result.claims.authenticationMethods).toEqual(["pwd", "mfa"]);
}
});
@@ -97,11 +78,18 @@ describe("extractAdminSsoClaims", () => {
if (!result.ok) expect(result.reason).toBe("email-not-verified");
});
it("treats missing email_verified as true (Authentik does not always emit it)", () => {
it("rejects a missing email_verified claim", () => {
const claims = { ...validClaims } as Record<string, unknown>;
delete claims.email_verified;
const result = extractAdminSsoClaims(claims);
expect(result.ok).toBe(true);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("email-not-verified");
});
it("rejects malformed truthy email_verified claims", () => {
const result = extractAdminSsoClaims({ ...validClaims, email_verified: "true" });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("email-not-verified");
});
it("filters non-string entries from groups", () => {
@@ -110,6 +98,28 @@ describe("extractAdminSsoClaims", () => {
if (result.ok) expect(result.claims.groups).toEqual(["hivegrid-admin", "ok"]);
});
it("canonicalizes duplicate groups emitted by overlapping Authentik scope mappings", () => {
const result = extractAdminSsoClaims({
...validClaims,
groups: ["authentik Admins", "sogo-users", "hivegrid-admin", "authentik Admins", "sogo-users", "hivegrid-admin"],
});
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.claims.groups).toEqual(["authentik Admins", "sogo-users", "hivegrid-admin"]);
}
});
it("extracts only string authentication methods and defaults missing amr to an empty list", () => {
const filtered = extractAdminSsoClaims({ ...validClaims, amr: ["pwd", null, 7, "mfa"] });
expect(filtered.ok).toBe(true);
if (filtered.ok) expect(filtered.claims.authenticationMethods).toEqual(["pwd", "mfa"]);
const missing = extractAdminSsoClaims({ ...validClaims, amr: undefined });
expect(missing.ok).toBe(true);
if (missing.ok) expect(missing.claims.authenticationMethods).toEqual([]);
});
it("returns missing-sub for null claims", () => {
const result = extractAdminSsoClaims(null);
expect(result.ok).toBe(false);
@@ -1,39 +1,23 @@
/**
* Phase 09 Task #82 — OIDC ID-token claim extraction + group→role mapping.
*
* The "role" returned here is the *current* AdminUser identity layer in the
* HiveGrid boilerplate. Today the only durable AdminUser concept is "exists
* or not"; the spec adds two granular roles (`super_admin`, `staff`) that
* we persist as `ssoGroups` snapshots while we wait for the permissions
* matrix to grow first-class role columns. Callers should treat the role
* as advisory + future-proof.
* OIDC ID-token claim extraction and the narrow Authentik access gate.
* Authentik groups never map to HiveGrid roles. They only decide whether an
* already prepared AdminUser may enter the subject-binding flow.
*/
export type AuthentikGroup = "hivegrid-admin" | "hivegrid-staff";
export type AdminSsoRole = "super_admin" | "staff";
export const ADMIN_GROUP: AuthentikGroup = "hivegrid-admin";
export const STAFF_GROUP: AuthentikGroup = "hivegrid-staff";
export const ALLOWED_ADMIN_GROUPS: readonly AuthentikGroup[] = [ADMIN_GROUP, STAFF_GROUP];
/**
* Highest-priority-wins mapping. If a user is in BOTH groups they get
* super_admin (admins are a strict superset of staff for our purposes).
*/
export function mapGroupsToRole(groups: readonly string[] | undefined | null): AdminSsoRole | null {
if (!groups || groups.length === 0) return null;
if (groups.includes(ADMIN_GROUP)) return "super_admin";
if (groups.includes(STAFF_GROUP)) return "staff";
return null;
}
export type AdminSsoClaims = {
readonly subject: string;
readonly email: string;
readonly emailVerified: boolean;
readonly name: string;
readonly groups: readonly string[];
readonly authenticationMethods: readonly string[];
};
export type ClaimExtractionResult =
@@ -58,18 +42,18 @@ export function extractAdminSsoClaims(idTokenClaims: Record<string, unknown> | n
if (!email) {
return { ok: false, reason: "missing-email" };
}
// Spec security note: "email_verified=true prüfen". If the claim is
// absent we treat it as `true` only when the IdP is the trusted
// Authentik provider (which mints `email_verified` for SSO accounts);
// if it is present and false, reject.
const emailVerifiedClaim = idTokenClaims.email_verified;
const emailVerified = emailVerifiedClaim === undefined ? true : emailVerifiedClaim === true;
// The IdP must assert verification explicitly. Missing, malformed, and
// false claims all fail closed so a claim-mapping regression cannot bind
// an unverified operator identity.
const emailVerified = idTokenClaims.email_verified === true;
if (!emailVerified) {
return { ok: false, reason: "email-not-verified" };
}
const rawGroups = idTokenClaims.groups;
const groups: string[] = Array.isArray(rawGroups)
? rawGroups.filter((g): g is string => typeof g === "string" && g.length > 0)
const groups: string[] = Array.isArray(rawGroups) ? [...new Set(rawGroups.filter((g): g is string => typeof g === "string" && g.length > 0))] : [];
const rawAuthenticationMethods = idTokenClaims.amr;
const authenticationMethods: string[] = Array.isArray(rawAuthenticationMethods)
? rawAuthenticationMethods.filter((method): method is string => typeof method === "string" && method.length > 0)
: [];
const nameFromClaim = typeof idTokenClaims.name === "string" ? idTokenClaims.name.trim() : "";
const preferredName = typeof idTokenClaims.preferred_username === "string" ? idTokenClaims.preferred_username.trim() : "";
@@ -82,14 +66,13 @@ export function extractAdminSsoClaims(idTokenClaims: Record<string, unknown> | n
emailVerified,
name,
groups,
authenticationMethods,
},
};
}
/**
* Convenience guard: pass-through that throws (or returns a Response) when
* the user has no allowed group. Kept here so the JIT-provisioning logic
* stays focused on the DB upsert.
* Convenience guard for Authentik's coarse admin-login allowlist.
*/
export function isAllowedAdminGroup(group: string): group is AuthentikGroup {
return ALLOWED_ADMIN_GROUPS.includes(group as AuthentikGroup);
@@ -6,6 +6,7 @@ describe("readAdminSsoEnv", () => {
AUTHENTIK_ISSUER_URL: "https://auth.example.test/application/o/hivegrid-admin-panel/",
AUTHENTIK_ADMIN_CLIENT_ID: "hivegrid-admin-panel",
AUTHENTIK_ADMIN_CLIENT_SECRET: "shh",
AUTHENTIK_ADMIN_JIT_DATABASE_URL: "postgresql://hivegrid_authentik_jit:secret@db.example.test:5432/hivegrid",
AUTHENTIK_ADMIN_REDIRECT_URI: "https://admin.example.test/auth/admin/callback",
};
@@ -30,9 +31,53 @@ describe("readAdminSsoEnv", () => {
expect(message).toContain("AUTHENTIK_ISSUER_URL");
expect(message).toContain("AUTHENTIK_ADMIN_CLIENT_ID");
expect(message).toContain("AUTHENTIK_ADMIN_CLIENT_SECRET");
expect(message).toContain("AUTHENTIK_ADMIN_JIT_DATABASE_URL");
expect(message).toContain("AUTHENTIK_ADMIN_REDIRECT_URI");
}
});
it("rejects non-TLS remote endpoints and URL credentials", () => {
expect(() => readAdminSsoEnv({ ...baseEnv, AUTHENTIK_ISSUER_URL: "http://auth.example.test/issuer" })).toThrowError(
/must use HTTPS/,
);
expect(() => readAdminSsoEnv({ ...baseEnv, AUTHENTIK_ISSUER_URL: "https://user:password@auth.example.test/issuer" })).toThrowError(
/must not contain URL credentials/,
);
});
it("requires the exact callback path and a same-origin logout redirect", () => {
expect(() => readAdminSsoEnv({ ...baseEnv, AUTHENTIK_ADMIN_REDIRECT_URI: "https://admin.example.test/wrong" })).toThrowError(
/exact \/auth\/admin\/callback path/,
);
expect(() =>
readAdminSsoEnv({
...baseEnv,
AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI: "https://evil.example.test/login?logged_out=1",
}),
).toThrowError(/must use the admin callback origin/);
});
it("requires the prepared-admin binding capability to use its dedicated login role", () => {
expect(() =>
readAdminSsoEnv({
...baseEnv,
AUTHENTIK_ADMIN_JIT_DATABASE_URL: "postgresql://hivegrid_app:secret@db.example.test:5432/hivegrid",
}),
).toThrowError(/must authenticate as hivegrid_authentik_jit/);
});
it("permits HTTP only for loopback development", () => {
expect(
readAdminSsoEnv({
...baseEnv,
AUTHENTIK_ISSUER_URL: "http://127.0.0.1:9000/application/o/hivegrid-admin-panel/",
AUTHENTIK_ADMIN_REDIRECT_URI: "http://localhost:3000/auth/admin/callback",
}),
).toMatchObject({
issuerUrl: "http://127.0.0.1:9000/application/o/hivegrid-admin-panel/",
redirectUri: "http://localhost:3000/auth/admin/callback",
});
});
});
describe("isAdminSsoConfigured", () => {
@@ -42,6 +87,7 @@ describe("isAdminSsoConfigured", () => {
AUTHENTIK_ISSUER_URL: "https://auth.example.test/",
AUTHENTIK_ADMIN_CLIENT_ID: "id",
AUTHENTIK_ADMIN_CLIENT_SECRET: "secret",
AUTHENTIK_ADMIN_JIT_DATABASE_URL: "postgresql://hivegrid_authentik_jit:secret@db.example.test:5432/hivegrid",
AUTHENTIK_ADMIN_REDIRECT_URI: "https://admin.example.test/auth/admin/callback",
})
).toBe(true);
@@ -11,17 +11,19 @@
* page rather than a 500.
*/
import { Issuer, type Client } from "openid-client";
import { createHash } from "node:crypto";
export type AdminSsoEnv = {
readonly issuerUrl: string;
readonly clientId: string;
readonly clientSecret: string;
readonly bindingDatabaseUrl: string;
readonly redirectUri: string;
readonly postLogoutRedirectUri?: string;
};
export class AdminSsoConfigError extends Error {
readonly code: "missing-env" | "discovery-failed" | "client-init-failed";
readonly code: "missing-env" | "invalid-env" | "discovery-failed" | "client-init-failed";
constructor(code: AdminSsoConfigError["code"], message: string, options?: { cause?: unknown }) {
super(message, options);
@@ -39,6 +41,9 @@ export function readAdminSsoEnv(env: Record<string, string | undefined> = proces
const issuerUrl = env.AUTHENTIK_ISSUER_URL?.trim();
const clientId = env.AUTHENTIK_ADMIN_CLIENT_ID?.trim();
const clientSecret = env.AUTHENTIK_ADMIN_CLIENT_SECRET?.trim();
// The env key and database role retain their deployed legacy names. The
// capability itself binds prepared identities and never creates AdminUsers.
const bindingDatabaseUrl = env.AUTHENTIK_ADMIN_JIT_DATABASE_URL?.trim();
const redirectUri = env.AUTHENTIK_ADMIN_REDIRECT_URI?.trim();
const postLogoutRedirectUri = env.AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI?.trim();
@@ -46,21 +51,74 @@ export function readAdminSsoEnv(env: Record<string, string | undefined> = proces
if (!issuerUrl) missing.push("AUTHENTIK_ISSUER_URL");
if (!clientId) missing.push("AUTHENTIK_ADMIN_CLIENT_ID");
if (!clientSecret) missing.push("AUTHENTIK_ADMIN_CLIENT_SECRET");
if (!bindingDatabaseUrl) missing.push("AUTHENTIK_ADMIN_JIT_DATABASE_URL");
if (!redirectUri) missing.push("AUTHENTIK_ADMIN_REDIRECT_URI");
if (missing.length > 0) {
throw new AdminSsoConfigError("missing-env", `Admin SSO env is incomplete: missing ${missing.join(", ")}`);
}
const issuer = validateAdminSsoUrl("AUTHENTIK_ISSUER_URL", issuerUrl as string);
const redirect = validateAdminSsoUrl("AUTHENTIK_ADMIN_REDIRECT_URI", redirectUri as string);
validateAuthentikBindingDatabaseUrl(bindingDatabaseUrl as string);
if (issuer.search || issuer.hash) {
throw new AdminSsoConfigError("invalid-env", "AUTHENTIK_ISSUER_URL must not include query parameters or a fragment.");
}
if (redirect.pathname !== "/auth/admin/callback" || redirect.search || redirect.hash) {
throw new AdminSsoConfigError("invalid-env", "AUTHENTIK_ADMIN_REDIRECT_URI must target the exact /auth/admin/callback path.");
}
if (postLogoutRedirectUri) {
const postLogout = validateAdminSsoUrl("AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI", postLogoutRedirectUri);
if (postLogout.origin !== redirect.origin || postLogout.hash) {
throw new AdminSsoConfigError(
"invalid-env",
"AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI must use the admin callback origin and must not include a fragment.",
);
}
}
return {
issuerUrl: issuerUrl as string,
clientId: clientId as string,
clientSecret: clientSecret as string,
bindingDatabaseUrl: bindingDatabaseUrl as string,
redirectUri: redirectUri as string,
postLogoutRedirectUri: postLogoutRedirectUri || undefined,
};
}
function validateAuthentikBindingDatabaseUrl(value: string): void {
let url: URL;
try {
url = new URL(value);
} catch {
throw new AdminSsoConfigError("invalid-env", "AUTHENTIK_ADMIN_JIT_DATABASE_URL must be a valid PostgreSQL URL.");
}
if (!new Set(["postgres:", "postgresql:"]).has(url.protocol) || url.username !== "hivegrid_authentik_jit" || !url.password || url.pathname === "/") {
throw new AdminSsoConfigError(
"invalid-env",
"AUTHENTIK_ADMIN_JIT_DATABASE_URL must authenticate as hivegrid_authentik_jit and select a database.",
);
}
}
function validateAdminSsoUrl(name: string, value: string): URL {
let url: URL;
try {
url = new URL(value);
} catch {
throw new AdminSsoConfigError("invalid-env", `${name} must be an absolute URL.`);
}
const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
throw new AdminSsoConfigError("invalid-env", `${name} must use HTTPS outside loopback development.`);
}
if (url.username || url.password) {
throw new AdminSsoConfigError("invalid-env", `${name} must not contain URL credentials.`);
}
return url;
}
/**
* Returns true iff SSO is configured (i.e. all required env vars are set).
* Used by the login UI to decide whether to render the SSO button.
@@ -81,7 +139,9 @@ function envFingerprint(env: AdminSsoEnv): string {
// Fingerprint identifies whether we need to re-init when env changes
// (mostly relevant for tests; in production env is static for the
// lifetime of the process).
return `${env.issuerUrl}|${env.clientId}|${env.redirectUri}`;
const secretFingerprint = createHash("sha256").update(env.clientSecret).digest("base64url");
const bindingFingerprint = createHash("sha256").update(env.bindingDatabaseUrl).digest("base64url");
return `${env.issuerUrl}|${env.clientId}|${env.redirectUri}|${secretFingerprint}|${bindingFingerprint}`;
}
/**
@@ -8,6 +8,7 @@ export { AdminSsoConfigError, getAdminSsoClient, isAdminSsoConfigured, readAdmin
export {
ADMIN_SSO_CHALLENGE_COOKIE,
ADMIN_SSO_CHALLENGE_TTL_MS,
LOCAL_ADMIN_SSO_CHALLENGE_COOKIE,
clearAdminSsoChallengeCookie,
consumeAdminSsoChallenge,
createAdminSsoChallenge,
@@ -20,18 +21,7 @@ export {
extractAdminSsoClaims,
hasAllowedAdminGroup,
isAllowedAdminGroup,
mapGroupsToRole,
type AdminSsoClaims,
type AdminSsoRole,
type AuthentikGroup,
type ClaimExtractionResult,
} from "./claims.server";
export {
ADMIN_SSO_PROVIDER,
JitProvisioningError,
jitProvisionAdmin,
type JitProvisionedAdmin,
type JitProvisioningDbClient,
type JitProvisioningInput,
type JitProvisioningResult,
} from "./jit-provisioning.server";
@@ -1,201 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AdminSsoClaims } from "./claims.server";
import { ADMIN_SSO_PROVIDER, jitProvisionAdmin, type JitProvisioningDbClient } from "./jit-provisioning.server";
type AdminRecord = {
userId: string;
ssoProvider: string | null;
ssoSubjectId: string | null;
ssoGroups: string[];
lastSsoLoginAt: Date | null;
};
type UserRecord = { id: string; email: string; firstName: string; lastName: string };
function buildFakeDb() {
const adminRows = new Map<string, AdminRecord>();
const userRows = new Map<string, UserRecord>();
let userCounter = 0;
const db: JitProvisioningDbClient = {
adminUser: {
findUnique: vi.fn(async (args) => {
const { ssoProvider, ssoSubjectId } = args.where.ssoProvider_ssoSubjectId;
for (const row of adminRows.values()) {
if (row.ssoProvider === ssoProvider && row.ssoSubjectId === ssoSubjectId) {
return { userId: row.userId, ssoProvider: row.ssoProvider, ssoSubjectId: row.ssoSubjectId, ssoGroups: row.ssoGroups, lastSsoLoginAt: row.lastSsoLoginAt };
}
}
return null;
}),
update: vi.fn(async (args) => {
const existing = adminRows.get(args.where.userId);
if (!existing) {
const err = new Error("record not found") as Error & { code?: string };
err.code = "P2025";
throw err;
}
const updated: AdminRecord = {
...existing,
ssoProvider: args.data.ssoProvider ?? existing.ssoProvider,
ssoSubjectId: args.data.ssoSubjectId ?? existing.ssoSubjectId,
ssoGroups: args.data.ssoGroups ?? existing.ssoGroups,
lastSsoLoginAt: args.data.lastSsoLoginAt ?? existing.lastSsoLoginAt,
};
adminRows.set(args.where.userId, updated);
return updated;
}),
create: vi.fn(async (args) => {
const row: AdminRecord = {
userId: args.data.userId,
ssoProvider: args.data.ssoProvider,
ssoSubjectId: args.data.ssoSubjectId,
ssoGroups: [...args.data.ssoGroups],
lastSsoLoginAt: args.data.lastSsoLoginAt,
};
adminRows.set(row.userId, row);
return row;
}),
},
user: {
findUnique: vi.fn(async (args) => {
for (const u of userRows.values()) {
if (u.email === args.where.email) return { id: u.id, email: u.email };
}
return null;
}),
update: vi.fn(async (args) => {
const existing = userRows.get(args.where.id);
if (!existing) throw new Error(`user ${args.where.id} missing`);
const updated: UserRecord = {
...existing,
firstName: args.data.firstName ?? existing.firstName,
lastName: args.data.lastName ?? existing.lastName,
};
userRows.set(args.where.id, updated);
return updated;
}),
create: vi.fn(async (args) => {
userCounter += 1;
const id = `user_${userCounter}`;
const row: UserRecord = {
id,
email: args.data.email,
firstName: args.data.firstName,
lastName: args.data.lastName,
};
userRows.set(id, row);
return { id: row.id, email: row.email };
}),
},
};
return { db, adminRows, userRows };
}
function buildClaims(overrides: Partial<AdminSsoClaims> = {}): AdminSsoClaims {
return {
subject: "authentik-sub-1",
email: "admin@example.test",
emailVerified: true,
name: "Admin Person",
groups: ["hivegrid-admin"],
...overrides,
};
}
describe("jitProvisionAdmin", () => {
let env: ReturnType<typeof buildFakeDb>;
beforeEach(() => {
env = buildFakeDb();
});
it("creates User+AdminUser for a brand new hivegrid-admin claim and returns super_admin", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims() }, env.db);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.admin.role).toBe("super_admin");
expect(result.admin.created).toBe(true);
expect(result.admin.email).toBe("admin@example.test");
}
expect(env.adminRows.size).toBe(1);
expect(env.userRows.size).toBe(1);
const admin = [...env.adminRows.values()][0]!;
expect(admin.ssoProvider).toBe(ADMIN_SSO_PROVIDER);
expect(admin.ssoSubjectId).toBe("authentik-sub-1");
expect(admin.ssoGroups).toEqual(["hivegrid-admin"]);
});
it("maps hivegrid-staff to staff role", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: ["hivegrid-staff"] }) }, env.db);
expect(result.ok).toBe(true);
if (result.ok) expect(result.admin.role).toBe("staff");
});
it("rejects an unknown-group claim with forbidden-group", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: ["random"] }) }, env.db);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.reason).toBe("forbidden-group");
expect(env.adminRows.size).toBe(0);
expect(env.userRows.size).toBe(0);
});
it("rejects an empty-group claim with forbidden-group", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: [] }) }, env.db);
expect(result.ok).toBe(false);
});
it("updates the existing SSO admin and refreshes groups + lastSsoLoginAt", async () => {
// Seed: first login creates the admin.
const t0 = new Date("2026-01-01T00:00:00Z");
await jitProvisionAdmin({ claims: buildClaims(), now: t0 }, env.db);
const admin = [...env.adminRows.values()][0]!;
expect(admin.lastSsoLoginAt).toEqual(t0);
// Second login with same sub but new groups + later timestamp.
const t1 = new Date("2026-02-01T00:00:00Z");
const result = await jitProvisionAdmin(
{ claims: buildClaims({ groups: ["hivegrid-staff"] }), now: t1 },
env.db,
);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.admin.created).toBe(false);
// Role re-syncs from current group membership (Authentik = source of truth).
expect(result.admin.role).toBe("staff");
}
const refreshed = [...env.adminRows.values()][0]!;
expect(refreshed.ssoGroups).toEqual(["hivegrid-staff"]);
expect(refreshed.lastSsoLoginAt).toEqual(t1);
// No new user row.
expect(env.userRows.size).toBe(1);
});
it("links an existing email-matched legacy admin by attaching SSO fields", async () => {
// Seed legacy admin (no SSO fields).
env.userRows.set("legacy_1", { id: "legacy_1", email: "admin@example.test", firstName: "Old", lastName: "Admin" });
env.adminRows.set("legacy_1", { userId: "legacy_1", ssoProvider: null, ssoSubjectId: null, ssoGroups: [], lastSsoLoginAt: null });
const result = await jitProvisionAdmin({ claims: buildClaims() }, env.db);
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.admin.userId).toBe("legacy_1");
expect(result.admin.linkedExisting).toBe(true);
expect(result.admin.created).toBe(false);
}
const admin = env.adminRows.get("legacy_1")!;
expect(admin.ssoProvider).toBe(ADMIN_SSO_PROVIDER);
expect(admin.ssoSubjectId).toBe("authentik-sub-1");
expect(env.userRows.size).toBe(1); // no duplicate user
});
it("creates an AdminUser when a legacy User exists but has no AdminUser row", async () => {
env.userRows.set("legacy_2", { id: "legacy_2", email: "admin@example.test", firstName: "X", lastName: "Y" });
// Note: no AdminUser row pre-existing.
const result = await jitProvisionAdmin({ claims: buildClaims() }, env.db);
expect(result.ok).toBe(true);
expect(env.adminRows.size).toBe(1);
expect(env.adminRows.get("legacy_2")?.ssoSubjectId).toBe("authentik-sub-1");
});
});
@@ -1,225 +0,0 @@
/**
* Phase 09 Task #82 — JIT-provisioning for Admin SSO.
*
* Lookup order:
* 1. AdminUser by (ssoProvider, ssoSubjectId)
* 2. AdminUser by linked User.email (case-insensitive) — legacy linking
* 3. New User + AdminUser if at least one allowed group is in claims
*
* Idempotent under concurrent logins thanks to the unique
* (ssoProvider, ssoSubjectId) constraint added in migration
* 20260517161240_09_admin_user_sso_fields.
*/
import { randomBytes } from "node:crypto";
import type { AdminSsoClaims, AdminSsoRole } from "./claims.server";
import { hasAllowedAdminGroup, mapGroupsToRole } from "./claims.server";
export const ADMIN_SSO_PROVIDER = "authentik";
export type JitProvisioningInput = {
readonly claims: AdminSsoClaims;
readonly now?: Date;
};
export type JitProvisionedAdmin = {
readonly userId: string;
readonly email: string;
readonly role: AdminSsoRole;
readonly created: boolean;
readonly linkedExisting: boolean;
};
export type JitProvisioningResult =
| { readonly ok: true; readonly admin: JitProvisionedAdmin }
| { readonly ok: false; readonly reason: "forbidden-group" };
export class JitProvisioningError extends Error {
readonly reason: "forbidden-group";
constructor(reason: "forbidden-group", message: string) {
super(message);
this.name = "JitProvisioningError";
this.reason = reason;
}
}
/**
* Narrow Prisma-shaped surface used by jitProvisionAdmin. Defining it as a
* structural type rather than importing PrismaClient keeps this module
* unit-testable with a hand-rolled fake.
*/
export type JitProvisioningDbClient = {
adminUser: {
findUnique: (args: { where: { ssoProvider_ssoSubjectId: { ssoProvider: string; ssoSubjectId: string } } }) =>
| Promise<({ userId: string } & AdminSsoUserRecord) | null>;
update: (args: {
where: { userId: string };
data: {
ssoProvider?: string;
ssoSubjectId?: string;
ssoGroups?: string[];
lastSsoLoginAt?: Date;
};
}) => Promise<{ userId: string } & AdminSsoUserRecord>;
create: (args: {
data: {
userId: string;
ssoProvider: string;
ssoSubjectId: string;
ssoGroups: string[];
lastSsoLoginAt: Date;
};
}) => Promise<{ userId: string } & AdminSsoUserRecord>;
};
user: {
findUnique: (args: { where: { email: string } }) => Promise<{ id: string; email: string } | null>;
update: (args: { where: { id: string }; data: { firstName?: string; lastName?: string } }) => Promise<unknown>;
create: (args: {
data: {
email: string;
passwordHash: string;
firstName: string;
lastName: string;
active: boolean;
};
}) => Promise<{ id: string; email: string }>;
};
};
type AdminSsoUserRecord = {
ssoProvider: string | null;
ssoSubjectId: string | null;
ssoGroups: string[];
lastSsoLoginAt: Date | null;
};
function splitName(fullName: string): { firstName: string; lastName: string } {
const cleaned = fullName.trim();
if (!cleaned) return { firstName: "", lastName: "" };
const parts = cleaned.split(/\s+/);
if (parts.length === 1) return { firstName: parts[0]!, lastName: "" };
return { firstName: parts[0]!, lastName: parts.slice(1).join(" ") };
}
/**
* Random throw-away password hash — placeholder so the User row can satisfy
* the existing non-null `passwordHash` constraint. SSO-only users never use
* it; they always authenticate through Authentik. Stored as an opaque
* 32-byte token prefixed to make the source obvious in audits.
*/
function generateSsoOnlyPasswordHash(): string {
return `sso-only!${randomBytes(32).toString("hex")}`;
}
/**
* JIT-provision (or refresh) an AdminUser based on a verified Authentik
* claim bundle.
*/
export async function jitProvisionAdmin(
input: JitProvisioningInput,
db: JitProvisioningDbClient
): Promise<JitProvisioningResult> {
const { claims } = input;
const role = mapGroupsToRole(claims.groups);
if (!role || !hasAllowedAdminGroup(claims.groups)) {
return { ok: false, reason: "forbidden-group" };
}
const now = input.now ?? new Date();
const email = claims.email.toLowerCase();
// (1) Existing SSO-linked admin?
const existingBySso = await db.adminUser.findUnique({
where: { ssoProvider_ssoSubjectId: { ssoProvider: ADMIN_SSO_PROVIDER, ssoSubjectId: claims.subject } },
});
if (existingBySso) {
await db.adminUser.update({
where: { userId: existingBySso.userId },
data: {
ssoGroups: [...claims.groups],
lastSsoLoginAt: now,
},
});
const { firstName, lastName } = splitName(claims.name);
if (firstName || lastName) {
await db.user.update({ where: { id: existingBySso.userId }, data: { firstName, lastName } });
}
return {
ok: true,
admin: {
userId: existingBySso.userId,
email,
role,
created: false,
linkedExisting: false,
},
};
}
// (2) Legacy admin matched by email — attach SSO fields.
const existingUserByEmail = await db.user.findUnique({ where: { email } });
if (existingUserByEmail) {
const updated = await db.adminUser.update({
where: { userId: existingUserByEmail.id },
data: {
ssoProvider: ADMIN_SSO_PROVIDER,
ssoSubjectId: claims.subject,
ssoGroups: [...claims.groups],
lastSsoLoginAt: now,
},
}).catch(async (err) => {
// If the user exists but has no AdminUser row, create one.
// Prisma's `update` throws P2025 for record-not-found.
const code = (err as { code?: string }).code;
if (code !== "P2025") throw err;
return db.adminUser.create({
data: {
userId: existingUserByEmail.id,
ssoProvider: ADMIN_SSO_PROVIDER,
ssoSubjectId: claims.subject,
ssoGroups: [...claims.groups],
lastSsoLoginAt: now,
},
});
});
return {
ok: true,
admin: {
userId: updated.userId,
email,
role,
created: false,
linkedExisting: true,
},
};
}
// (3) Brand-new user + admin from SSO.
const { firstName, lastName } = splitName(claims.name);
const newUser = await db.user.create({
data: {
email,
passwordHash: generateSsoOnlyPasswordHash(),
firstName: firstName || "Admin",
lastName: lastName || "User",
active: true,
},
});
await db.adminUser.create({
data: {
userId: newUser.id,
ssoProvider: ADMIN_SSO_PROVIDER,
ssoSubjectId: claims.subject,
ssoGroups: [...claims.groups],
lastSsoLoginAt: now,
},
});
return {
ok: true,
admin: {
userId: newUser.id,
email,
role,
created: true,
linkedExisting: false,
},
};
}
@@ -0,0 +1,111 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const { testWebConfig } = vi.hoisted(() => ({
testWebConfig: {
nodeEnv: "test" as string,
cryptoSecret: "test-crypto-secret-do-not-use-in-prod",
sessionSecret: "test-session-secret-do-not-use-in-prod",
routing: {
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
protocol: "https" as "http" | "https",
},
},
}));
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return {
...actual,
loadRequiredWebConfig: () => testWebConfig,
};
});
import {
ADMIN_SSO_ID_TOKEN_COOKIE,
clearIdTokenCookie,
LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE,
readIdTokenFromRequest,
serializeIdTokenCookie,
} from "./logout.server";
const SECRET = "test-secret-do-not-use-in-prod";
function requestWithCookie(pair: string): Request {
return new Request("https://admin.example.test/auth/admin/logout", { headers: { cookie: pair } });
}
beforeEach(() => {
testWebConfig.nodeEnv = "test";
testWebConfig.routing.protocol = "https";
testWebConfig.routing.appBaseDomain = "example.test";
});
describe("admin SSO id-token cookie", () => {
it("uses a host-prefixed HTTPS cookie without a Domain attribute", () => {
const cookie = serializeIdTokenCookie("id-token-value", { secret: SECRET });
expect(cookie).toContain(`${ADMIN_SSO_ID_TOKEN_COOKIE}=`);
expect(cookie).toContain("Path=/");
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("SameSite=Lax");
expect(cookie).toContain("Secure");
expect(cookie).not.toContain("Domain=");
});
it("round-trips a valid signed id token", () => {
const pair = serializeIdTokenCookie("id-token-value", { secret: SECRET }).split(";")[0] ?? "";
expect(readIdTokenFromRequest(requestWithCookie(pair), { secret: SECRET })).toBe("id-token-value");
});
it("rejects tampering", () => {
const pair = serializeIdTokenCookie("id-token-value", { secret: SECRET }).split(";")[0] ?? "";
expect(readIdTokenFromRequest(requestWithCookie(`${pair}tampered`), { secret: SECRET })).toBeNull();
});
it("ignores a legacy parent-domain cookie on HTTPS", () => {
const pair = serializeIdTokenCookie("id-token-value", { secret: SECRET })
.split(";")[0]
?.replace(ADMIN_SSO_ID_TOKEN_COOKIE, LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE);
expect(readIdTokenFromRequest(requestWithCookie(pair ?? ""), { secret: SECRET })).toBeNull();
});
it("does not let a legacy cookie shadow the host-prefixed id token", () => {
const securePair = serializeIdTokenCookie("id-token-value", { secret: SECRET }).split(";")[0] ?? "";
const request = requestWithCookie(`${LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE}=attacker; ${securePair}`);
expect(readIdTokenFromRequest(request, { secret: SECRET })).toBe("id-token-value");
});
it("clears the exact secure cookie scope", () => {
const cookie = clearIdTokenCookie();
expect(cookie).toContain(`${ADMIN_SSO_ID_TOKEN_COOKIE}=`);
expect(cookie).toContain("Path=/");
expect(cookie).toContain("Max-Age=0");
expect(cookie).toContain("Secure");
expect(cookie).not.toContain("Domain=");
});
it("uses a distinct localhost-compatible fallback on local HTTP", () => {
testWebConfig.nodeEnv = "development";
testWebConfig.routing.protocol = "http";
testWebConfig.routing.appBaseDomain = "localhost:3000";
const cookie = serializeIdTokenCookie("id-token-value", { secret: SECRET });
const pair = cookie.split(";")[0] ?? "";
expect(cookie).toContain(`${LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE}=`);
expect(cookie).not.toContain(ADMIN_SSO_ID_TOKEN_COOKIE);
expect(cookie).not.toContain("Secure");
expect(cookie).not.toContain("Domain=");
expect(readIdTokenFromRequest(new Request("http://localhost:3000/auth/admin/logout", { headers: { cookie: pair } }), { secret: SECRET })).toBe(
"id-token-value"
);
});
});
@@ -2,16 +2,16 @@
* Phase 09 Task #82 — Admin-SSO logout helpers.
*
* Stores the raw OIDC `id_token` in a separate HMAC-signed HttpOnly
* cookie (scoped to /auth/admin) so that /auth/admin/logout can supply
* cookie (scoped to the dedicated admin host) so that /auth/admin/logout can supply
* `id_token_hint` for RP-initiated logout without bloating the main
* session cookie or persisting tokens in the DB.
*/
import { createHmac, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
export const ADMIN_SSO_ID_TOKEN_COOKIE = "hivegrid_admin_sso_id_token";
export const ADMIN_SSO_ID_TOKEN_TTL_MS = 12 * 60 * 60 * 1000; // mirror app-session lifetime
const COOKIE_PATH = "/auth/admin";
export const ADMIN_SSO_ID_TOKEN_COOKIE = "__Host-hivegrid_admin_sso_id_token";
export const LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE = "hivegrid_admin_sso_id_token";
export const ADMIN_SSO_ID_TOKEN_TTL_MS = 15 * 60 * 1000; // bounded to the absolute AdminUser session lifetime
function getSigningSecret(override?: string): string {
if (override) return override;
@@ -27,19 +27,33 @@ function sign(payload: string, secret: string): string {
return createHmac("sha256", secret).update(payload).digest("base64url");
}
function getCookiePolicy() {
const webConfig = loadRequiredWebConfig();
// `__Host-` requires Path=/. The dedicated admin hostname is the narrowest
// safe scope that preserves the browser-enforced no-Domain guarantee.
return resolveHostOnlyCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
secureName: ADMIN_SSO_ID_TOKEN_COOKIE,
localName: LOCAL_ADMIN_SSO_ID_TOKEN_COOKIE,
maxAge: Math.ceil(ADMIN_SSO_ID_TOKEN_TTL_MS / 1000),
});
}
export function serializeIdTokenCookie(idToken: string, opts: { secret?: string } = {}): string {
const secret = getSigningSecret(opts.secret);
const sig = sign(idToken, secret);
const value = `${Buffer.from(idToken, "utf8").toString("base64url")}.${sig}`;
const maxAge = Math.ceil(ADMIN_SSO_ID_TOKEN_TTL_MS / 1000);
const attrs = [`${ADMIN_SSO_ID_TOKEN_COOKIE}=${value}`, `Path=${COOKIE_PATH}`, "HttpOnly", "SameSite=Lax", `Max-Age=${maxAge}`];
if (process.env.NODE_ENV !== "test") attrs.push("Secure");
const policy = getCookiePolicy();
const attrs = [`${policy.name}=${value}`, `Path=${policy.path}`, "HttpOnly", "SameSite=Lax", `Max-Age=${policy.maxAge}`];
if (policy.secure) attrs.push("Secure");
return attrs.join("; ");
}
export function clearIdTokenCookie(): string {
const attrs = [`${ADMIN_SSO_ID_TOKEN_COOKIE}=`, `Path=${COOKIE_PATH}`, "HttpOnly", "SameSite=Lax", "Max-Age=0"];
if (process.env.NODE_ENV !== "test") attrs.push("Secure");
const policy = getCookiePolicy();
const attrs = [`${policy.name}=`, `Path=${policy.path}`, "HttpOnly", "SameSite=Lax", "Max-Age=0"];
if (policy.secure) attrs.push("Secure");
return attrs.join("; ");
}
@@ -55,7 +69,13 @@ function readCookie(request: Request, name: string): string | null {
}
export function readIdTokenFromRequest(request: Request, opts: { secret?: string } = {}): string | null {
const value = readCookie(request, ADMIN_SSO_ID_TOKEN_COOKIE);
let cookieName: string;
try {
cookieName = getCookiePolicy().name;
} catch {
return null;
}
const value = readCookie(request, cookieName);
if (!value) return null;
const dot = value.lastIndexOf(".");
if (dot <= 0) return null;
@@ -1,9 +1,32 @@
import { describe, expect, it } from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { testWebConfig } = vi.hoisted(() => ({
testWebConfig: {
nodeEnv: "test" as string,
routing: {
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
apiHost: "api.example.test",
protocol: "https" as "http" | "https",
},
},
}));
vi.mock("@hivegrid/config", async () => {
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
return {
...actual,
loadRequiredWebConfig: () => testWebConfig,
};
});
import {
ADMIN_SSO_CHALLENGE_COOKIE,
ADMIN_SSO_CHALLENGE_TTL_MS,
consumeAdminSsoChallenge,
createAdminSsoChallenge,
LOCAL_ADMIN_SSO_CHALLENGE_COOKIE,
serializeAdminSsoChallengeCookie,
} from "./state.server";
@@ -14,12 +37,18 @@ function cookieValue(cookie: string): string {
return head.slice(`${ADMIN_SSO_CHALLENGE_COOKIE}=`.length);
}
function requestWithCookie(value: string): Request {
function requestWithCookie(value: string, name = ADMIN_SSO_CHALLENGE_COOKIE): Request {
return new Request("https://admin.example.test/auth/admin/callback", {
headers: { cookie: `${ADMIN_SSO_CHALLENGE_COOKIE}=${value}` },
headers: { cookie: `${name}=${value}` },
});
}
beforeEach(() => {
testWebConfig.nodeEnv = "test";
testWebConfig.routing.protocol = "https";
testWebConfig.routing.appBaseDomain = "example.test";
});
describe("createAdminSsoChallenge", () => {
it("produces distinct state, nonce and codeVerifier for each invocation", () => {
const a = createAdminSsoChallenge({ secret: SECRET });
@@ -38,11 +67,27 @@ describe("createAdminSsoChallenge", () => {
expect(payload.codeChallenge).not.toBe(payload.codeVerifier);
});
it("emits an HttpOnly, Path-scoped cookie", () => {
it("emits a host-prefixed cookie on HTTPS without a Domain attribute", () => {
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
expect(cookie).toContain(`${ADMIN_SSO_CHALLENGE_COOKIE}=`);
expect(cookie).toMatch(/HttpOnly/);
expect(cookie).toMatch(/Path=\/auth\/admin/);
expect(cookie).toMatch(/Path=\//);
expect(cookie).toMatch(/SameSite=Lax/);
expect(cookie).toMatch(/Secure/);
expect(cookie).not.toMatch(/Domain=/);
});
it("uses a distinct localhost-compatible name on local HTTP", () => {
testWebConfig.nodeEnv = "development";
testWebConfig.routing.protocol = "http";
testWebConfig.routing.appBaseDomain = "localhost:3000";
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
expect(cookie).toContain(`${LOCAL_ADMIN_SSO_CHALLENGE_COOKIE}=`);
expect(cookie).not.toContain(ADMIN_SSO_CHALLENGE_COOKIE);
expect(cookie).not.toContain("Secure");
expect(cookie).not.toContain("Domain=");
});
});
@@ -70,6 +115,26 @@ describe("consumeAdminSsoChallenge", () => {
if (!result.ok) expect(result.reason).toBe("missing");
});
it("ignores a legacy parent-domain cookie on HTTPS", () => {
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
const result = consumeAdminSsoChallenge(requestWithCookie(cookieValue(cookie), LOCAL_ADMIN_SSO_CHALLENGE_COOKIE), { secret: SECRET });
expect(result).toEqual({ ok: false, reason: "missing" });
});
it("does not let a legacy cookie shadow the host-prefixed challenge", () => {
const { payload, cookie } = createAdminSsoChallenge({ secret: SECRET });
const value = cookieValue(cookie);
const request = new Request("https://admin.example.test/auth/admin/callback", {
headers: { cookie: `${LOCAL_ADMIN_SSO_CHALLENGE_COOKIE}=attacker; ${ADMIN_SSO_CHALLENGE_COOKIE}=${value}` },
});
const result = consumeAdminSsoChallenge(request, { secret: SECRET });
expect(result.ok).toBe(true);
if (result.ok) expect(result.payload.state).toBe(payload.state);
});
it("rejects a cookie with a tampered signature", () => {
const { cookie } = createAdminSsoChallenge({ secret: SECRET });
const value = cookieValue(cookie);
@@ -96,6 +161,22 @@ describe("consumeAdminSsoChallenge", () => {
if (!result.ok) expect(result.reason).toBe("expired");
});
it("rejects a challenge dated implausibly far in the future", () => {
const now = Date.now();
const { payload } = createAdminSsoChallenge({ secret: SECRET, now: () => now + 5 * 60 * 1000 });
const cookie = serializeAdminSsoChallengeCookie(payload, SECRET);
const result = consumeAdminSsoChallenge(requestWithCookie(cookieValue(cookie)), { secret: SECRET, now: () => now });
expect(result).toEqual({ ok: false, reason: "malformed" });
});
it("rejects a signed payload whose PKCE verifier and challenge do not match", () => {
const { payload } = createAdminSsoChallenge({ secret: SECRET });
const inconsistent = { ...payload, codeChallenge: "A".repeat(43) };
const cookie = serializeAdminSsoChallengeCookie(inconsistent, SECRET);
const result = consumeAdminSsoChallenge(requestWithCookie(cookieValue(cookie)), { secret: SECRET });
expect(result).toEqual({ ok: false, reason: "malformed" });
});
it("rejects a malformed cookie value", () => {
const result = consumeAdminSsoChallenge(requestWithCookie("garbage"), { secret: SECRET });
expect(result.ok).toBe(false);
@@ -2,7 +2,7 @@
* Phase 09 Task #82 — PKCE / state / nonce challenge persistence.
*
* Stores the tuple { state, nonce, codeVerifier, createdAt } in an
* HMAC-signed HttpOnly cookie scoped to /auth/admin. The cookie is
* HMAC-signed HttpOnly cookie scoped to the dedicated admin host. The cookie is
* single-use: `consumeAdminSsoChallenge()` returns the payload and emits a
* `Set-Cookie` header that clears it.
*
@@ -17,12 +17,13 @@
* server-side (cookie Max-Age is best-effort; clients lie).
*/
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
import { generators } from "openid-client";
export const ADMIN_SSO_CHALLENGE_COOKIE = "hivegrid_admin_sso_challenge";
export const ADMIN_SSO_CHALLENGE_COOKIE = "__Host-hivegrid_admin_sso_challenge";
export const LOCAL_ADMIN_SSO_CHALLENGE_COOKIE = "hivegrid_admin_sso_challenge";
export const ADMIN_SSO_CHALLENGE_TTL_MS = 10 * 60 * 1000;
const COOKIE_PATH = "/auth/admin";
const ADMIN_SSO_CHALLENGE_CLOCK_SKEW_MS = 60 * 1000;
const PAYLOAD_VERSION = "v1";
export type AdminSsoChallengePayload = {
@@ -58,6 +59,19 @@ function getSigningSecret(override?: string): string {
return secret;
}
function getCookiePolicy() {
const webConfig = loadRequiredWebConfig();
// `__Host-` requires Path=/. The dedicated admin hostname is the narrowest
// safe scope that preserves the browser-enforced no-Domain guarantee.
return resolveHostOnlyCookiePolicy({
nodeEnv: webConfig.nodeEnv,
routing: webConfig.routing,
secureName: ADMIN_SSO_CHALLENGE_COOKIE,
localName: LOCAL_ADMIN_SSO_CHALLENGE_COOKIE,
maxAge: Math.ceil(ADMIN_SSO_CHALLENGE_TTL_MS / 1000),
});
}
function base64UrlEncode(buf: Buffer | string): string {
const b = typeof buf === "string" ? Buffer.from(buf, "utf8") : buf;
return b.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -105,15 +119,9 @@ export function serializeAdminSsoChallengeCookie(payload: AdminSsoChallengePaylo
const body = base64UrlEncode(JSON.stringify({ v: PAYLOAD_VERSION, p: payload }));
const sig = sign(body, secret);
const value = `${body}.${sig}`;
const maxAgeSeconds = Math.ceil(ADMIN_SSO_CHALLENGE_TTL_MS / 1000);
const attributes = [
`${ADMIN_SSO_CHALLENGE_COOKIE}=${value}`,
`Path=${COOKIE_PATH}`,
"HttpOnly",
"SameSite=Lax",
`Max-Age=${maxAgeSeconds}`,
];
if (process.env.NODE_ENV !== "test") {
const policy = getCookiePolicy();
const attributes = [`${policy.name}=${value}`, `Path=${policy.path}`, "HttpOnly", "SameSite=Lax", `Max-Age=${policy.maxAge}`];
if (policy.secure) {
attributes.push("Secure");
}
return attributes.join("; ");
@@ -123,14 +131,9 @@ export function serializeAdminSsoChallengeCookie(payload: AdminSsoChallengePaylo
* Returns a `Set-Cookie` header that clears the challenge cookie.
*/
export function clearAdminSsoChallengeCookie(): string {
const attributes = [
`${ADMIN_SSO_CHALLENGE_COOKIE}=`,
`Path=${COOKIE_PATH}`,
"HttpOnly",
"SameSite=Lax",
"Max-Age=0",
];
if (process.env.NODE_ENV !== "test") {
const policy = getCookiePolicy();
const attributes = [`${policy.name}=`, `Path=${policy.path}`, "HttpOnly", "SameSite=Lax", "Max-Age=0"];
if (policy.secure) {
attributes.push("Secure");
}
return attributes.join("; ");
@@ -153,11 +156,14 @@ function readCookieValue(request: Request, name: string): string | null {
* Always returns a `clearCookie` header that the caller must include on
* the redirect response so the cookie cannot be replayed.
*/
export function consumeAdminSsoChallenge(
request: Request,
options: { now?: () => number; secret?: string } = {}
): ConsumeResult {
const value = readCookieValue(request, ADMIN_SSO_CHALLENGE_COOKIE);
export function consumeAdminSsoChallenge(request: Request, options: { now?: () => number; secret?: string } = {}): ConsumeResult {
let cookieName: string;
try {
cookieName = getCookiePolicy().name;
} catch {
return { ok: false, reason: "malformed" };
}
const value = readCookieValue(request, cookieName);
if (!value) return { ok: false, reason: "missing" };
const dot = value.lastIndexOf(".");
if (dot <= 0) return { ok: false, reason: "malformed" };
@@ -172,18 +178,48 @@ export function consumeAdminSsoChallenge(
if (!verifySignature(body, sig, secret)) {
return { ok: false, reason: "bad-signature" };
}
let decoded: { v: string; p: AdminSsoChallengePayload };
let decoded: { v?: unknown; p?: unknown };
try {
decoded = JSON.parse(base64UrlDecode(body).toString("utf8"));
decoded = JSON.parse(base64UrlDecode(body).toString("utf8")) as { v?: unknown; p?: unknown };
} catch {
return { ok: false, reason: "malformed" };
}
if (decoded.v !== PAYLOAD_VERSION || !decoded.p) {
if (decoded.v !== PAYLOAD_VERSION || !isAdminSsoChallengePayload(decoded.p)) {
return { ok: false, reason: "malformed" };
}
const now = options.now ? options.now() : Date.now();
if (typeof decoded.p.createdAt !== "number" || now - decoded.p.createdAt > ADMIN_SSO_CHALLENGE_TTL_MS) {
if (decoded.p.createdAt > now + ADMIN_SSO_CHALLENGE_CLOCK_SKEW_MS) {
return { ok: false, reason: "malformed" };
}
if (now - decoded.p.createdAt > ADMIN_SSO_CHALLENGE_TTL_MS) {
return { ok: false, reason: "expired" };
}
return { ok: true, payload: decoded.p, clearCookie: clearAdminSsoChallengeCookie() };
}
function isAdminSsoChallengePayload(value: unknown): value is AdminSsoChallengePayload {
if (!value || typeof value !== "object") {
return false;
}
const payload = value as Partial<Record<keyof AdminSsoChallengePayload, unknown>>;
if (
typeof payload.state !== "string" ||
!/^[0-9a-f]{64}$/.test(payload.state) ||
typeof payload.nonce !== "string" ||
!/^[0-9a-f]{64}$/.test(payload.nonce) ||
typeof payload.codeVerifier !== "string" ||
!/^[A-Za-z0-9._~-]{43,128}$/.test(payload.codeVerifier) ||
typeof payload.codeChallenge !== "string" ||
!/^[A-Za-z0-9_-]{43}$/.test(payload.codeChallenge) ||
typeof payload.createdAt !== "number" ||
!Number.isFinite(payload.createdAt) ||
(payload.returnTo !== undefined && typeof payload.returnTo !== "string")
) {
return false;
}
try {
return generators.codeChallenge(payload.codeVerifier) === payload.codeChallenge;
} catch {
return false;
}
}
@@ -0,0 +1,67 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
const mocks = vi.hoisted(() => ({
tenantFindMany: vi.fn(),
visitorGroupBy: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({
dbRead: {
tenant: { findMany: mocks.tenantFindMany },
analyticsUniqueVisitor: { groupBy: mocks.visitorGroupBy },
},
}));
import { groupUniqueVisitorsBy } from "./analyticsUniqueVisitors.db.server";
describe("admin analytics visitor grouping", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.tenantFindMany.mockImplementation(async () => {
expect(getRlsExecutionContext()).toEqual({ userId: "operator_1" });
return [{ id: "tenant_1" }, { id: "tenant_2" }];
});
mocks.visitorGroupBy.mockImplementation(async () => {
const context = getRlsExecutionContext();
if (context?.tenantId === "tenant_1") {
expect(context).toEqual({ userId: "operator_1", tenantId: "tenant_1" });
return [
{ browser: "Chrome", _count: 2 },
{ browser: "Safari", _count: 1 },
];
}
if (context?.tenantId === "tenant_2") {
expect(context).toEqual({ userId: "operator_1", tenantId: "tenant_2" });
return [
{ browser: "Chrome", _count: 3 },
{ browser: null, _count: 2 },
];
}
if (context?.platformAnalytics) {
expect(context).toEqual({ platformAnalytics: true });
return [
{ browser: "Chrome", _count: 4 },
{ browser: "Firefox", _count: 5 },
];
}
throw new Error(`Unexpected RLS context: ${JSON.stringify(context)}`);
});
});
it("merges tenant-scoped counts with isolated anonymous platform counts", async () => {
const result = await runWithRlsContext({ userId: "operator_1" }, () => groupUniqueVisitorsBy("browser"));
expect(result).toEqual([
{ name: "Chrome", count: 9 },
{ name: "Safari", count: 1 },
{ name: "", count: 2 },
{ name: "Firefox", count: 5 },
]);
expect(mocks.tenantFindMany).toHaveBeenCalledWith({ select: { id: true }, orderBy: { id: "asc" } });
expect(mocks.visitorGroupBy).toHaveBeenCalledTimes(3);
expect(mocks.visitorGroupBy).toHaveBeenNthCalledWith(1, { by: ["browser"], _count: true });
expect(getRlsExecutionContext()).toBeNull();
});
});
@@ -1,12 +1,35 @@
import { Prisma } from "@hivegrid/db/prisma-browser";
import { runWithIsolatedPlatformAnalyticsRlsContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { dbRead } from "~/utils/db.server";
export async function groupUniqueVisitorsBy(by: Prisma.AnalyticsUniqueVisitorScalarFieldEnum) {
// Pure aggregation for analytics dashboards — eventually-consistent is fine.
return (
await dbRead.analyticsUniqueVisitor.groupBy({
const tenantIds = await dbRead.tenant.findMany({
select: { id: true },
orderBy: { id: "asc" },
});
const counts = new Map<string, number>();
async function addGroupsVisibleInCurrentContext() {
// Pure aggregation for analytics dashboards — eventually-consistent is fine.
const groups = await dbRead.analyticsUniqueVisitor.groupBy({
by: [by],
_count: true,
})
).map((f) => ({ name: f[by]?.toString() ?? ("" as string), count: f._count }));
});
for (const group of groups) {
const name = group[by]?.toString() ?? "";
counts.set(name, (counts.get(name) ?? 0) + group._count);
}
}
// Keep tenant reads independently scoped. Sequential execution also avoids
// opening an unbounded number of read-replica transactions for large estates.
for (const tenant of tenantIds) {
await runWithRlsContext({ tenantId: tenant.id }, addGroupsVisibleInCurrentContext);
}
// Tenantless analytics is a separate anonymous capability and must never
// inherit the authenticated operator identity from the admin request.
await runWithIsolatedPlatformAnalyticsRlsContext(addGroupsVisibleInCurrentContext);
return [...counts].map(([name, count]) => ({ name, count }));
}
@@ -1,10 +1,8 @@
import { useSubmit, useSearchParams, useNavigation, useParams } from "react-router";
import { useSubmit, useParams } from "react-router";
import { useState } from "react";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import RefreshIcon from "~/components/ui/icons/RefreshIcon";
import InputFilters from "~/components/ui/input/InputFilters";
import InputSearchWithURL from "~/components/ui/input/InputSearchWithURL";
import ShowPayloadModalButton from "~/components/ui/json/ShowPayloadModalButton";
@@ -32,13 +30,10 @@ export default function ApiKeyLogsDetails({ data }: Props) {
const formatters = useLocaleFormatters();
const appOrAdminData = useAppOrAdminData();
const submit = useSubmit();
const navigation = useNavigation();
const params = useParams();
const canDelete = !params.tenant;
const [searchParams, setSearchParams] = useSearchParams();
const [selectedRows, setSelectedRows] = useState<ApiKeyLogDto[]>([]);
function onDelete(ids: string[]) {
if (!canDelete) {
@@ -1,28 +0,0 @@
import { describe, expect, it } from "vitest";
import { readRepoFile } from "~/utils/testing/repoPaths";
describe("ApiKeyLogsSummary i18n", () => {
it("keeps visible summary controls behind semantic API log keys", () => {
const source = [
"apps/web/app/modules/api/components/ApiKeyLogsSummary.tsx",
"apps/web/app/modules/api/components/ApiCallSpeedBadge.tsx",
"apps/web/app/modules/metrics/components/SpeedBadge.tsx",
]
.map((file) => readRepoFile(file))
.join("\n");
expect(source).toContain("models.apiKeyLog.groupBy.placeholder");
expect(source).toContain("models.apiKeyLog.calls");
expect(source).toContain("models.apiKeyLog.avgDuration");
expect(source).toContain("metrics.speed.lightningFast");
expect(source).toContain("metrics.speed.verySlow");
expect(source).not.toContain("ui.autogenerated");
expect(source).not.toContain("lightning_fast");
expect(source).not.toContain("response_schema");
expect(source).not.toContain("body_example");
expect(source).not.toContain('"Group by"');
expect(source).not.toContain('"Select group by"');
expect(source).not.toContain('"Please select at least one group by"');
expect(source).not.toContain('"Speed"');
});
});
@@ -1,192 +0,0 @@
import { Link, useParams, useSearchParams } from "react-router";
import { useEffect, useState } from "react";
import ApiKeyLogUtils from "../utils/ApiKeyLogUtils";
import { RowHeaderDisplayDto } from "~/application/dtos/data/RowHeaderDisplayDto";
import { ApiCallSummaryDto } from "../dtos/ApiCallSummaryDto";
import ApiKeyLogsConstants from "../utils/ApiKeyLogsConstants";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { FilterableValueLink } from "~/components/ui/links/FilterableValueLink";
import WarningBanner from "~/components/ui/banners/WarningBanner";
import InputCombobox from "~/components/ui/input/InputCombobox";
import InputFilters from "~/components/ui/input/InputFilters";
import TableSimple from "~/components/ui/tables/TableSimple";
import { useLocaleFormatters } from "~/locale/format";
import UrlUtils from "~/utils/app/UrlUtils";
import ApiUtils from "~/utils/app/ApiUtils";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
import { Colors } from "~/application/enums/shared/Colors";
import ApiCallSpeedBadge from "./ApiCallSpeedBadge";
import { useTranslation } from "react-i18next";
interface Props {
data: {
items: ApiCallSummaryDto[];
allTenants: { id: string; name: string }[];
filterableProperties: FilterablePropertyDto[];
};
}
export default function ApiKeyLogsSummary({ data }: Props) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const params = useParams();
const [searchParams, setSearchParams] = useSearchParams();
const [groupBy, setGroupBy] = useState<string[]>(ApiKeyLogUtils.getGroupByValues(searchParams));
const [headers, setHeaders] = useState<RowHeaderDisplayDto<ApiCallSummaryDto>[]>([]);
useEffect(() => {
if (ApiKeyLogUtils.getGroupByValues(searchParams).sort().join(",") !== groupBy.sort().join(",")) {
searchParams.delete("groupBy");
groupBy.forEach((by) => {
searchParams.append("groupBy", by);
});
setSearchParams(searchParams);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [groupBy]);
useEffect(() => {
const headers: RowHeaderDisplayDto<ApiCallSummaryDto>[] = [];
let currentGroupBy = groupBy;
if (currentGroupBy.length === 0) {
currentGroupBy = ApiKeyLogsConstants.DEFAULT_GROUP_BY;
}
const getTenant = (item: ApiCallSummaryDto) => {
return data.allTenants.find((x) => x.id === item.tenantId);
};
const getCountLink = (item: ApiCallSummaryDto) => {
const searchParams = new URLSearchParams();
// searchParams.set("pageSize", "100");
currentGroupBy.forEach((groupBy) => {
if (groupBy === "method") {
searchParams.append("method", item.method);
} else if (groupBy === "endpoint") {
searchParams.append("endpoint", item.endpoint);
} else if (groupBy === "params") {
searchParams.append("params", item.params);
} else if (groupBy === "status") {
searchParams.append("status", item.status?.toString() ?? "{null}");
}
});
return UrlUtils.getModulePath(params, `api/logs?${searchParams.toString()}`);
};
if (groupBy.includes("method")) {
headers.push({
name: "method",
title: t("models.apiKeyLog.method"),
value: (item) => (
<FilterableValueLink name="method" value={item.method}>
<SimpleBadge title={item.method} color={ApiUtils.getMethodColor(item.method)} underline />
</FilterableValueLink>
),
});
}
if (groupBy.includes("endpoint")) {
headers.push({
name: "endpoint",
title: t("models.apiKeyLog.endpoint"),
value: (item) => <FilterableValueLink name="endpoint" value={item.endpoint} />,
});
}
if (groupBy.includes("params")) {
headers.push({
name: "params",
title: t("models.apiKeyLog.params"),
value: (item) => <FilterableValueLink name="params" value={item.params} />,
});
}
if (groupBy.includes("status")) {
headers.push({
name: "status",
title: t("models.apiKeyLog.status"),
value: (item) => (
<FilterableValueLink name="status" value={item.status?.toString() ?? "{null}"}>
<SimpleBadge title={item.status?.toString() ?? t("shared.unknown")} color={item.status?.toString().startsWith("4") ? Colors.RED : Colors.GREEN} />
</FilterableValueLink>
),
});
}
if (groupBy.includes("tenantId")) {
headers.push({
name: "tenantId",
title: t("models.apiKeyLog.tenant"),
value: (item) => <FilterableValueLink name="tenantId" value={getTenant(item)?.name ?? ""} />,
});
}
headers.push({
name: "apiCalls",
title: t("models.apiKeyLog.apiCalls"),
align: "right",
value: (item) => (
<div className="flex justify-end text-right">
<Link to={getCountLink(item)} className="hover:underline">
{t("models.apiKeyLog.calls", { count: Number(item._count._all), formattedCount: formatters.number(Number(item._count._all)) })}
</Link>
</div>
),
});
headers.push({
name: "duration",
title: t("models.apiKeyLog.avgDuration"),
value: (item) =>
item._avg.duration === null ? (
<span className="text-muted-foreground text-xs italic">{t("shared.notAvailable")}</span>
) : (
<div>{formatters.number(Number(item._avg.duration), { style: "unit", unit: "millisecond", unitDisplay: "short", maximumFractionDigits: 3 })}</div>
),
});
headers.push({
name: "speed",
title: t("models.apiKeyLog.speed"),
value: (item) =>
item._avg.duration === null ? (
<span className="text-muted-foreground text-xs italic">{t("shared.notAvailable")}</span>
) : (
<ApiCallSpeedBadge duration={Number(item._avg.duration)} />
),
});
headers.push({
name: "actions",
title: "",
value: (item) => (
<Link to={getCountLink(item)} className="hover:underline">
{t("shared.details")} <span className="ml-1">&rarr;</span>
</Link>
),
});
setHeaders(headers);
}, [data, groupBy, params, t]);
return (
<div className="space-y-2">
<div className="flex w-full items-center space-x-2">
<InputCombobox
name="groupBy"
prefix={t("models.apiKeyLog.groupBy.prefix")}
className="bg-background h-8"
selectPlaceholder={t("models.apiKeyLog.groupBy.placeholder")}
options={[
{ value: "method", name: t("models.apiKeyLog.method") },
{ value: "endpoint", name: t("models.apiKeyLog.endpoint") },
{ value: "params", name: t("models.apiKeyLog.params") },
{ value: "status", name: t("models.apiKeyLog.status") },
{ value: "tenantId", name: t("models.apiKeyLog.tenant") },
]}
value={groupBy}
onChange={(value) => {
setGroupBy(value as string[]);
}}
/>
<div className="grow">{/* <InputSearchWithURL /> */}</div>
<InputFilters size="sm" filters={data.filterableProperties} />
</div>
{groupBy.length === 0 ? (
<WarningBanner title={t("models.apiKeyLog.groupBy.title")} text={t("models.apiKeyLog.groupBy.required")} />
) : (
<TableSimple items={data.items} headers={headers} />
)}
</div>
);
}
@@ -0,0 +1,66 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
const mocks = vi.hoisted(() => ({
findScopes: vi.fn(),
deleteForTenant: vi.fn(),
}));
vi.mock("@hivegrid/db/accounts.server", () => ({
adminGetAllLegacyTenantSummaries: vi.fn(async () => []),
}));
vi.mock("@hivegrid/db/api-keys.server", () => ({
countLegacyApiKeyLogs: vi.fn(),
deleteTenantLegacyApiKeyLogsByIds: mocks.deleteForTenant,
findLegacyApiKeyLogTenantScopesByIds: mocks.findScopes,
getLegacyApiKeyLogAdminDetails: vi.fn(),
groupLegacyApiKeyLogs: vi.fn(),
tenantLegacyApiKeyLogScope: (tenantId: string) => ({ tenantId }),
}));
import ApiKeyLogService from "./ApiKeyLogService";
describe("ApiKeyLogService admin RLS deletion", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.deleteForTenant.mockImplementation(async ({ tenantId }: { tenantId: string }) => {
expect(getRlsExecutionContext()).toMatchObject({ userId: "operator_1", tenantId });
return { count: 1 };
});
});
it("deletes each selected log only inside its owning tenant context", async () => {
mocks.findScopes.mockResolvedValue([
{ id: "log_a", tenantId: "tenant_a" },
{ id: "log_b", tenantId: "tenant_b" },
]);
const result = await runWithRlsContext({ userId: "operator_1" }, () => ApiKeyLogService.adminDeleteMany(["log_a", "log_b"]));
expect(result).toEqual({ deletedCount: 2, rejectedTenantlessIds: [] });
expect(mocks.deleteForTenant).toHaveBeenCalledTimes(2);
expect(mocks.deleteForTenant).toHaveBeenCalledWith({ ids: ["log_a"], tenantId: "tenant_a" });
expect(mocks.deleteForTenant).toHaveBeenCalledWith({ ids: ["log_b"], tenantId: "tenant_b" });
});
it("rejects the whole batch when it contains a tenantless platform log", async () => {
mocks.findScopes.mockResolvedValue([
{ id: "log_a", tenantId: "tenant_a" },
{ id: "log_platform", tenantId: null },
]);
const result = await runWithRlsContext({ userId: "operator_1" }, () => ApiKeyLogService.adminDeleteMany(["log_a", "log_platform"]));
expect(result).toEqual({ deletedCount: 0, rejectedTenantlessIds: ["log_platform"] });
expect(mocks.deleteForTenant).not.toHaveBeenCalled();
});
it("fails closed outside an unscoped authenticated operator request", async () => {
await expect(ApiKeyLogService.adminDeleteMany(["log_a"])).rejects.toThrow("unscoped authenticated operator context");
await expect(runWithRlsContext({ userId: "operator_1", tenantId: "tenant_a" }, () => ApiKeyLogService.adminDeleteMany(["log_a"]))).rejects.toThrow(
"unscoped authenticated operator context"
);
expect(mocks.findScopes).not.toHaveBeenCalled();
});
});
@@ -1,14 +1,15 @@
import { adminGetAllLegacyTenantSummaries } from "@hivegrid/db/accounts.server";
import {
adminDeleteLegacyApiKeyLogsByIds,
countLegacyApiKeyLogs,
deleteTenantLegacyApiKeyLogsByIds,
findLegacyApiKeyLogTenantScopesByIds,
getLegacyApiKeyLogAdminDetails,
groupLegacyApiKeyLogs,
tenantLegacyApiKeyLogScope,
type LegacyApiKeyLogOrderByInput,
type LegacyApiKeyLogWhereInput,
} from "@hivegrid/db/api-keys.server";
import { getRlsExecutionContext, runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { Prisma } from "@hivegrid/db/prisma-browser";
import { Params } from "react-router";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
@@ -63,7 +64,7 @@ async function getDetails({ request, params }: { request: Request; params: Param
const totalItems = await countLegacyApiKeyLogs(whereFilters);
return {
items: items as ApiKeyLogDto[],
items: items.map(toApiKeyLogDto),
filterableProperties,
pagination: {
page: pagination.page,
@@ -170,12 +171,55 @@ async function getFilters({ request, params }: { request: Request; params: Param
return { filterableProperties, whereFilters, allTenants };
}
async function adminDeleteMany(ids: string[]) {
return await adminDeleteLegacyApiKeyLogsByIds(ids);
async function adminDeleteMany(ids: string[]): Promise<{ deletedCount: number; rejectedTenantlessIds: string[] }> {
const context = getRlsExecutionContext();
if (!context?.userId || context.tenantId) {
throw new Error("Admin API log deletion requires an unscoped authenticated operator context");
}
const normalizedIds = [...new Set(ids.map((id) => id.trim()).filter(Boolean))];
if (normalizedIds.length === 0) return { deletedCount: 0, rejectedTenantlessIds: [] };
if (normalizedIds.length > 500) {
throw new Error("At most 500 API log entries can be deleted at once");
}
const scopes = await findLegacyApiKeyLogTenantScopesByIds(normalizedIds);
const rejectedTenantlessIds = scopes.filter((scope) => !scope.tenantId).map((scope) => scope.id);
if (rejectedTenantlessIds.length > 0) {
return { deletedCount: 0, rejectedTenantlessIds };
}
const byTenant = new Map<string, string[]>();
for (const scope of scopes) {
if (!scope.tenantId) continue;
const tenantIds = byTenant.get(scope.tenantId) ?? [];
tenantIds.push(scope.id);
byTenant.set(scope.tenantId, tenantIds);
}
await Promise.all(
[...byTenant].map(([tenantId, tenantIds]) => runWithRlsContext({ tenantId }, () => deleteTenantLegacyApiKeyLogsByIds({ ids: tenantIds, tenantId })))
);
return { deletedCount: scopes.length, rejectedTenantlessIds: [] };
}
async function deleteManyForTenant(ids: string[], tenantId: string | null) {
return await deleteTenantLegacyApiKeyLogsByIds({ ids, tenantId });
return tenantId
? runWithRlsContext({ tenantId }, () => deleteTenantLegacyApiKeyLogsByIds({ ids, tenantId }))
: deleteTenantLegacyApiKeyLogsByIds({ ids, tenantId });
}
function toApiKeyLogDto(item: Awaited<ReturnType<typeof getLegacyApiKeyLogAdminDetails>>[number]): ApiKeyLogDto {
if (item.apiKey || !item.apiKeyId || !item.alias || !item.tenantId) return item as ApiKeyLogDto;
return {
...item,
apiKey: {
alias: item.alias,
tenant: {
id: item.tenantId,
name: item.tenant?.name ?? item.tenantName ?? item.tenantId,
},
},
} as ApiKeyLogDto;
}
export default {
@@ -1,89 +1,15 @@
// AK-P16b · booking-page editor UI (M06 Block E.2 + H). Minimal FUNCTIONAL form
// (bespoke polish follows D-P16): grunddata + providers + confirmation template +
// publish toggle, and the public-URL + iframe embed-code generator with copy buttons.
// AK-P16b · booking-page editor route component (M06 Block E.2 + H). Thin
// wrapper: injects the loader data + csrf into the interim ~/ui screen
// (AD-28); final Subframe optics follow David's D-P16 delta.
import { Form, useActionData, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { useActionData, useLoaderData } from "react-router";
import { useRootData } from "~/utils/data/useRootData";
import { BookingPageEditorPage } from "~/components/screens/booking/BookingPageEditorPage";
import type { BookingPageEditorLoaderData, BookingPageEditorActionData } from "../routes/BookingPageEditor.server";
function CopyField({ label, value }: { label: string; value: string }): JSX.Element {
return (
<div className="mt-2">
<span className="text-muted-foreground text-xs">{label}</span>
<div className="flex gap-2">
<input readOnly value={value} className="w-full rounded border px-2 py-1 text-xs" data-ui-id="ui.booking.pages.embed.value" />
<button type="button" className="rounded border px-2 py-1 text-xs" onClick={() => navigator.clipboard?.writeText(value)}>
⧉
</button>
</div>
</div>
);
}
export default function BookingPageEditorRoute(): JSX.Element {
const { t } = useTranslation();
export default function BookingPageEditorRoute(): React.JSX.Element {
const vm = useLoaderData<BookingPageEditorLoaderData>();
const actionData = useActionData<BookingPageEditorActionData>();
const rootData = useRootData();
const page = vm.page;
return (
<main className="mx-auto max-w-2xl px-4 py-10" data-ui-id="ui.booking.pages.editor">
<h1 className="text-foreground text-xl font-semibold">{t("bookings.pages.editor.title")}</h1>
{actionData && !actionData.ok ? (
<p role="alert" className="mt-4 text-red-600" data-ui-id="ui.booking.pages.editor.error">
{t(actionData.errorKey)}
</p>
) : null}
<Form method="post" className="mt-6 space-y-3">
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.slug")}</span>
<input name="slug" defaultValue={page?.slug ?? ""} required className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.pageTitle")}</span>
<input name="title" defaultValue={page?.title ?? ""} required className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.description")}</span>
<textarea name="description" defaultValue={page?.description ?? ""} className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.duration")}</span>
<input name="durationMinutes" type="number" defaultValue={page?.durationMinutes ?? 30} className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.providers")}</span>
<input name="providers" defaultValue={page?.providerUserIds.join(",") ?? ""} placeholder="userId1,userId2" className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.confirmationSubject")}</span>
<input name="confirmationEmailSubject" defaultValue={page?.confirmationEmailSubject ?? ""} className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.confirmationBody")}</span>
<textarea name="confirmationEmailBody" defaultValue={page?.confirmationEmailBody ?? ""} className="w-full rounded border px-2 py-1" />
</label>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="isPublished" defaultChecked={page?.isPublished ?? false} />
{t("bookings.pages.editor.publishToggle")}
</label>
<button type="submit" className="rounded bg-primary px-4 py-2 text-primary-foreground" data-ui-id="ui.booking.pages.editor.save">
{t("bookings.pages.editor.save")}
</button>
</Form>
{vm.publicUrl && vm.embedCode ? (
<section className="mt-8" data-ui-id="ui.booking.pages.embed">
<h2 className="font-medium">{t("bookings.pages.embedCode")}</h2>
<CopyField label={t("bookings.pages.publicUrl")} value={vm.publicUrl} />
<CopyField label={t("bookings.pages.embedCode")} value={vm.embedCode} />
</section>
) : null}
</main>
);
return <BookingPageEditorPage vm={vm} actionErrorKey={actionData && !actionData.ok ? actionData.errorKey : null} csrf={rootData.csrf ?? null} />;
}
@@ -1,14 +1,102 @@
// AK-P16b · public booking page (M06 Block G) — minimal FUNCTIONAL UI (reachable +
// i18n + states), NOT the bespoke Calendly-polish screen (that waits on David D-P16).
// Single-page flow: pick a slot → fill the mini-form (GDPR required) → confirmation
// with an "add to calendar" (.ics) download. The component reads route-injected data
// only (no DB import); it is in apps/web so useLoaderData is allowed here.
// AK-P16b · public booking page (M06 Block G) — interim S04-style look (AD-28)
// matching the PublicFormRenderer target screens: centered card with accent bar,
// slot pills, themed submit and centered success state. Kept as plain `tcbook-*`
// CSS (no `~/ui`, no Tailwind) so the `/embed` iframe variant stays
// dependency-free — same documented deviation as PublicFormRenderer. The bespoke
// Calendly-polish screen still follows David D-BOOK/D-P16 (design-nachzug).
// Single-page flow: pick a slot → fill the mini-form (GDPR required) →
// confirmation with an "add to calendar" (.ics) download. The component reads
// route-injected data only (no DB import); useLoaderData is allowed here.
import { Form, useActionData, useLoaderData, useNavigation } from "react-router";
import { useTranslation } from "react-i18next";
import type { PublicBookingLoaderData, PublicBookingActionData } from "../routes/PublicBooking.server";
export default function PublicBookingRoute(): JSX.Element {
/**
* Self-contained styles mirroring TCFORM_CSS (S04 public form, V01 success,
* V03 submit error) with booking-specific slot pills. Driven by the same CSS
* variable names' booking twins so a tenant theme can restyle both surfaces.
*/
const TCBOOK_CSS = `
.tcbook-root { font-family: var(--tcbook-font, system-ui, -apple-system, "Segoe UI", sans-serif); color: var(--tcbook-text, #16232e); box-sizing: border-box; padding: 16px; }
.tcbook-root *, .tcbook-root *::before, .tcbook-root *::after { box-sizing: border-box; }
.tcbook-root--page { min-height: 100vh; background: #f2f4f7; padding: 48px 16px; }
.tcbook-shell { max-width: 576px; margin: 0 auto; display: flex; flex-direction: column; gap: 16px; }
.tcbook-brand { display: flex; justify-content: center; }
.tcbook-brand-badge { display: inline-flex; align-items: center; justify-content: center; width: 44px; height: 44px; border-radius: 50%; border: 1px solid #e0e5eb; background: #eef2f7; background: color-mix(in srgb, var(--tcbook-primary, #2563eb) 10%, #ffffff); color: var(--tcbook-primary, #2563eb); font-size: 1.15rem; font-weight: 700; }
.tcbook-card { background: var(--tcbook-bg, #ffffff); border: 1px solid #e0e5eb; border-top: 4px solid var(--tcbook-primary, #2563eb); border-radius: var(--tcbook-radius, 10px); box-shadow: 0 1px 2px rgba(16, 24, 40, 0.05), 0 8px 24px rgba(16, 24, 40, 0.06); padding: 32px 28px; }
.tcbook-root h1 { font-size: 1.35rem; line-height: 1.3; margin: 0 0 6px; font-weight: 700; }
.tcbook-tenant { margin: 0 0 4px; font-size: 0.8rem; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; opacity: 0.6; }
.tcbook-root p.tcbook-description { margin: 0; font-size: 0.9rem; line-height: 1.5; opacity: 0.72; }
.tcbook-duration { margin: 8px 0 0; font-size: 0.85rem; opacity: 0.72; }
.tcbook-divider { border: 0; height: 1px; background: #e7ebef; margin: 20px 0; }
.tcbook-legend { display: block; font-weight: 600; font-size: 0.9rem; margin-bottom: 8px; padding: 0; }
.tcbook-slots { display: flex; flex-wrap: wrap; gap: 8px; margin: 0; padding: 0; border: 0; }
.tcbook-slot { position: relative; }
.tcbook-slot input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; margin: 0; }
.tcbook-slot span { display: inline-flex; align-items: center; justify-content: center; min-width: 72px; padding: 9px 14px; border: 1px solid #cfd6dd; border-radius: var(--tcbook-radius, 8px); font-size: 0.92rem; font-weight: 500; background: #fff; transition: border-color 120ms ease, background 120ms ease, color 120ms ease; }
.tcbook-slot input:checked + span { border-color: var(--tcbook-primary, #2563eb); background: var(--tcbook-primary, #2563eb); color: #fff; }
.tcbook-slot input:focus-visible + span { outline: 2px solid var(--tcbook-primary, #2563eb); outline-offset: 2px; }
.tcbook-slot input:hover:not(:checked) + span { border-color: var(--tcbook-primary, #2563eb); }
.tcbook-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.tcbook-row { display: block; margin-bottom: 14px; }
.tcbook-root input[type=text], .tcbook-root input[type=email], .tcbook-root input[type=tel] { width: 100%; padding: 10px 12px; border: 1px solid #cfd6dd; border-radius: var(--tcbook-radius, 8px); font: inherit; font-size: 0.95rem; color: inherit; background: #fff; transition: border-color 120ms ease, box-shadow 120ms ease; }
.tcbook-root input:focus { outline: none; border-color: var(--tcbook-primary, #2563eb); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.15); box-shadow: 0 0 0 3px color-mix(in srgb, var(--tcbook-primary, #2563eb) 18%, transparent); }
.tcbook-root input::placeholder { color: inherit; opacity: 0.45; }
.tcbook-root input[type=checkbox] { width: 16px; height: 16px; margin: 2px 0 0; accent-color: var(--tcbook-primary, #2563eb); flex: none; }
.tcbook-consent { border: 1px solid #e0e5eb; border-radius: var(--tcbook-radius, 8px); background: #fbfcfd; padding: 12px 14px; margin-bottom: 14px; }
.tcbook-consent label { display: flex; align-items: flex-start; gap: 10px; font-weight: 500; font-size: 0.875rem; line-height: 1.45; margin: 0; cursor: pointer; }
.tcbook-error { display: flex; align-items: flex-start; gap: 10px; padding: 12px 14px; border: 1px solid #fecaca; border-radius: var(--tcbook-radius, 8px); background: #fef2f2; color: #991b1b; font-size: 0.9rem; line-height: 1.45; margin: 16px 0 0; }
.tcbook-error svg { flex: none; margin-top: 2px; }
.tcbook-empty { padding: 12px 14px; border: 1px dashed #cfd6dd; border-radius: var(--tcbook-radius, 8px); background: #fbfcfd; font-size: 0.9rem; line-height: 1.45; margin-top: 16px; opacity: 0.85; }
.tcbook-root button.tcbook-submit { display: block; width: 100%; background: var(--tcbook-primary, #2563eb); color: #fff; border: 0; padding: 12px 18px; border-radius: var(--tcbook-radius, 8px); cursor: pointer; font: inherit; font-size: 0.95rem; font-weight: 600; transition: filter 120ms ease; }
.tcbook-root button.tcbook-submit:hover:not([disabled]) { filter: brightness(0.92); }
.tcbook-root button.tcbook-submit:focus-visible { outline: 2px solid var(--tcbook-primary, #2563eb); outline-offset: 2px; }
.tcbook-root button.tcbook-submit[disabled] { opacity: 0.6; cursor: progress; }
.tcbook-success { display: flex; flex-direction: column; align-items: center; gap: 16px; text-align: center; padding: 16px 0; }
.tcbook-success-icon { display: inline-flex; align-items: center; justify-content: center; width: 56px; height: 56px; border-radius: 50%; background: #ecfdf5; color: #059669; }
.tcbook-success-message { margin: 0; font-size: 1.1rem; font-weight: 600; line-height: 1.4; }
.tcbook-success-body { margin: 0; font-size: 0.92rem; line-height: 1.5; opacity: 0.78; }
.tcbook-ics { display: inline-flex; align-items: center; justify-content: center; gap: 8px; background: var(--tcbook-primary, #2563eb); color: #fff; text-decoration: none; padding: 11px 18px; border-radius: var(--tcbook-radius, 8px); font-size: 0.92rem; font-weight: 600; transition: filter 120ms ease; }
.tcbook-ics:hover { filter: brightness(0.92); }
@media (max-width: 520px) { .tcbook-card { padding: 24px 16px; } .tcbook-root--page { padding: 24px 12px; } .tcbook-grid-2 { grid-template-columns: 1fr; } }
`;
function IconCheck(): React.JSX.Element {
return (
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<path d="M20 6 9 17l-5-5" />
</svg>
);
}
function IconAlert(): React.JSX.Element {
return (
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
);
}
function BookingShell({ isEmbed, tenantName, children }: { isEmbed: boolean; tenantName: string; children: React.ReactNode }): React.JSX.Element {
return (
<main data-ui-id="ui.booking.public" className={isEmbed ? "tcbook-root" : "tcbook-root tcbook-root--page"}>
<style dangerouslySetInnerHTML={{ __html: TCBOOK_CSS }} />
<div className="tcbook-shell">
{!isEmbed ? (
<div className="tcbook-brand" aria-hidden="true">
<span className="tcbook-brand-badge">{(tenantName.trim()[0] ?? "•").toUpperCase()}</span>
</div>
) : null}
<div className="tcbook-card">{children}</div>
</div>
</main>
);
}
export default function PublicBookingRoute(): React.JSX.Element {
const vm = useLoaderData<PublicBookingLoaderData>();
const actionData = useActionData<PublicBookingActionData>();
const navigation = useNavigation();
@@ -18,73 +106,86 @@ export default function PublicBookingRoute(): JSX.Element {
if (actionData?.ok) {
const icsHref = `data:text/calendar;base64,${actionData.icsBase64}`;
return (
<main data-ui-id="ui.booking.public" className={vm.isEmbed ? "p-4" : "mx-auto max-w-xl p-6"}>
<h1 className="text-xl font-semibold">{t("bookings.public.confirmedHeadline")}</h1>
<p className="mt-2">
{t("bookings.public.confirmedBody", { title: actionData.titleLabel, date: actionData.dateLabel, time: actionData.timeLabel })}
</p>
<a data-ui-id="ui.booking.public.ics" href={icsHref} download="termin.ics" className="mt-4 inline-block underline">
{t("bookings.public.addToCalendar")}
</a>
</main>
<BookingShell isEmbed={vm.isEmbed} tenantName={vm.tenantName}>
<div className="tcbook-success">
<span className="tcbook-success-icon">
<IconCheck />
</span>
<p className="tcbook-success-message">{t("bookings.public.confirmedHeadline")}</p>
<p className="tcbook-success-body">
{t("bookings.public.confirmedBody", { title: actionData.titleLabel, date: actionData.dateLabel, time: actionData.timeLabel })}
</p>
<a data-ui-id="ui.booking.public.ics" href={icsHref} download="termin.ics" className="tcbook-ics">
{t("bookings.public.addToCalendar")}
</a>
</div>
</BookingShell>
);
}
return (
<main data-ui-id="ui.booking.public" className={vm.isEmbed ? "p-4" : "mx-auto max-w-xl p-6"}>
<BookingShell isEmbed={vm.isEmbed} tenantName={vm.tenantName}>
<header>
<p className="text-sm text-muted-foreground">{vm.tenantName}</p>
<h1 className="text-xl font-semibold">{vm.title}</h1>
{vm.description ? <p className="mt-1 text-muted-foreground">{vm.description}</p> : null}
<p className="mt-1 text-sm">{t("bookings.public.duration", { minutes: vm.durationMinutes })}</p>
<p className="tcbook-tenant">{vm.tenantName}</p>
<h1>{vm.title}</h1>
{vm.description ? <p className="tcbook-description">{vm.description}</p> : null}
<p className="tcbook-duration">{t("bookings.public.duration", { minutes: vm.durationMinutes })}</p>
</header>
{actionData && !actionData.ok ? (
<p data-ui-id="ui.booking.public.error" role="alert" className="mt-4 text-red-600">
{t(actionData.errorKey)}
<p data-ui-id="ui.booking.public.error" role="alert" className="tcbook-error">
<IconAlert />
<span>{t(actionData.errorKey)}</span>
</p>
) : null}
{vm.slots.length === 0 ? (
<p data-ui-id="ui.booking.public.empty" className="mt-6">
<p data-ui-id="ui.booking.public.empty" className="tcbook-empty">
{t("bookings.public.noSlots")}
</p>
) : (
<Form method="post" className="mt-6 space-y-4" data-ui-id="ui.booking.public.form">
<Form method="post" data-ui-id="ui.booking.public.form">
<input type="hidden" name="date" value={vm.date} />
<input type="hidden" name="tz" value={vm.timezone} />
{/* Honeypot — hidden from real users (M06 abuse guard). */}
<input type="text" name="company" tabIndex={-1} autoComplete="off" className="hidden" aria-hidden="true" />
<input type="text" name="company" tabIndex={-1} autoComplete="off" aria-hidden="true" style={{ position: "absolute", left: "-9999px", width: 1, height: 1, opacity: 0 }} />
<fieldset>
<legend className="text-sm font-medium">{t("bookings.public.chooseSlot", { date: vm.date })}</legend>
<div className="mt-2 flex flex-wrap gap-2">
<hr className="tcbook-divider" />
<fieldset className="tcbook-slots-fieldset" style={{ border: 0, margin: 0, padding: 0, marginBottom: 18 }}>
<legend className="tcbook-legend">{t("bookings.public.chooseSlot", { date: vm.date })}</legend>
<div className="tcbook-slots">
{vm.slots.map((slot, index) => (
<label key={slot.startAtIso} className="cursor-pointer rounded border px-3 py-1">
<input type="radio" name="startAt" value={slot.startAtIso} defaultChecked={index === 0} className="mr-1" />
{slot.label}
<label key={slot.startAtIso} className="tcbook-slot">
<input type="radio" name="startAt" value={slot.startAtIso} defaultChecked={index === 0} />
<span>{slot.label}</span>
</label>
))}
</div>
</fieldset>
<div className="grid grid-cols-2 gap-3">
<input name="vorname" placeholder={t("bookings.public.firstName")} className="rounded border px-3 py-2" required />
<input name="nachname" placeholder={t("bookings.public.lastName")} className="rounded border px-3 py-2" required />
<div className="tcbook-grid-2 tcbook-row">
<input name="vorname" type="text" placeholder={t("bookings.public.firstName")} required />
<input name="nachname" type="text" placeholder={t("bookings.public.lastName")} required />
</div>
<div className="tcbook-row">
<input name="email" type="email" placeholder={t("bookings.public.email")} required />
</div>
<div className="tcbook-row">
<input name="telefon" type="tel" placeholder={t("bookings.public.phone")} />
</div>
<input name="email" type="email" placeholder={t("bookings.public.email")} className="w-full rounded border px-3 py-2" required />
<input name="telefon" placeholder={t("bookings.public.phone")} className="w-full rounded border px-3 py-2" />
<label className="flex items-start gap-2 text-sm">
<input type="checkbox" name="gdpr" required className="mt-1" />
<span>{t("bookings.public.gdpr")}</span>
</label>
<div className="tcbook-consent">
<label>
<input type="checkbox" name="gdpr" required />
<span>{t("bookings.public.gdpr")}</span>
</label>
</div>
<button type="submit" disabled={submitting} data-ui-id="ui.booking.public.submit" className="rounded bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50">
<button type="submit" disabled={submitting} data-ui-id="ui.booking.public.submit" className="tcbook-submit">
{submitting ? t("bookings.public.submitting") : t("bookings.public.submit")}
</button>
</Form>
)}
</main>
</BookingShell>
);
}
@@ -0,0 +1,111 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
const mocks = vi.hoisted(() => {
const tx = {
bookingPage: { findFirst: vi.fn(), create: vi.fn(), update: vi.fn() },
bookingPageProvider: { deleteMany: vi.fn(), createMany: vi.fn() },
tenantUser: { findMany: vi.fn() },
form: { findFirst: vi.fn() },
};
return {
tx,
withTenantRLS: vi.fn(async (_tenantId: string, callback: (client: typeof tx) => Promise<unknown>) => callback(tx)),
};
});
vi.mock("~/utils/db.server", () => ({ db: {} }));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS }));
import { createBookingPage, updateBookingPage, type BookingPageInput } from "./booking.db.server";
const input: BookingPageInput = {
tenantId: "tenant-a",
createdByUserId: "admin-a",
slug: "beratung",
title: "Beratung",
description: null,
durationMinutes: 30,
confirmationEmailSubject: "Bestätigt",
confirmationEmailBody: "Dein Termin ist bestätigt.",
isPublished: true,
providerUserIds: ["provider-a"],
intakeFormId: "form-a",
};
describe("booking page tenant boundaries", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.tx.bookingPage.findFirst.mockResolvedValue({ id: "page-a" });
mocks.tx.bookingPage.create.mockResolvedValue({ id: "page-a" });
mocks.tx.tenantUser.findMany.mockResolvedValue([{ userId: "provider-a" }]);
mocks.tx.form.findFirst.mockResolvedValue({ id: "form-a" });
});
it("rejects a booking page owned by another tenant before any write", async () => {
mocks.tx.bookingPage.findFirst.mockResolvedValueOnce(null);
await expect(updateBookingPage("page-from-tenant-b", input)).resolves.toBe(false);
expect(mocks.withTenantRLS).toHaveBeenCalledWith("tenant-a", expect.any(Function));
expect(mocks.tx.bookingPage.findFirst).toHaveBeenCalledWith({
where: { id: "page-from-tenant-b", tenantId: "tenant-a", archivedAt: null },
select: { id: true },
});
expect(mocks.tx.tenantUser.findMany).not.toHaveBeenCalled();
expect(mocks.tx.bookingPage.update).not.toHaveBeenCalled();
expect(mocks.tx.bookingPageProvider.deleteMany).not.toHaveBeenCalled();
expect(mocks.tx.bookingPageProvider.createMany).not.toHaveBeenCalled();
});
it("rejects a provider who is not an active member of the tenant", async () => {
mocks.tx.tenantUser.findMany.mockResolvedValueOnce([]);
await expect(updateBookingPage("page-a", { ...input, providerUserIds: ["provider-from-tenant-b"] })).resolves.toBe(false);
expect(mocks.tx.tenantUser.findMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant-a",
userId: { in: ["provider-from-tenant-b"] },
status: TenantUserStatus.ACTIVE,
},
select: { userId: true },
});
expect(mocks.tx.bookingPage.update).not.toHaveBeenCalled();
expect(mocks.tx.bookingPageProvider.deleteMany).not.toHaveBeenCalled();
});
it("rejects an intake form that is not visible in the tenant", async () => {
mocks.tx.form.findFirst.mockResolvedValueOnce(null);
await expect(updateBookingPage("page-a", { ...input, intakeFormId: "form-from-tenant-b" })).resolves.toBe(false);
expect(mocks.tx.form.findFirst).toHaveBeenCalledWith({
where: { id: "form-from-tenant-b", tenantId: "tenant-a", status: { not: "archived" } },
select: { id: true },
});
expect(mocks.tx.bookingPage.update).not.toHaveBeenCalled();
expect(mocks.tx.bookingPageProvider.deleteMany).not.toHaveBeenCalled();
});
it("tenant-scopes the page update and provider replacement", async () => {
await expect(updateBookingPage("page-a", { ...input, providerUserIds: ["provider-a", "provider-a"] })).resolves.toBe(true);
expect(mocks.tx.bookingPage.update).toHaveBeenCalledWith(expect.objectContaining({ where: { id: "page-a", tenantId: "tenant-a" } }));
expect(mocks.tx.bookingPageProvider.deleteMany).toHaveBeenCalledWith({
where: { bookingPageId: "page-a", tenantId: "tenant-a" },
});
expect(mocks.tx.bookingPageProvider.createMany).toHaveBeenCalledWith({
data: [{ tenantId: "tenant-a", bookingPageId: "page-a", providerUserId: "provider-a", displayOrder: 0 }],
});
});
it("validates references before creating a booking page", async () => {
mocks.tx.form.findFirst.mockResolvedValueOnce(null);
await expect(createBookingPage({ ...input, intakeFormId: "form-from-tenant-b" })).resolves.toBeNull();
expect(mocks.tx.bookingPage.create).not.toHaveBeenCalled();
expect(mocks.tx.bookingPageProvider.createMany).not.toHaveBeenCalled();
});
});
@@ -3,6 +3,8 @@
// guard. Slot config + provider list feed the pure slot engine.
import { db } from "~/utils/db.server";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import type { SlotEngineConfig } from "../services/slotEngine";
export interface PublicBookingPage {
@@ -147,6 +149,8 @@ export interface AppointmentDetail {
intakeAnswers: Record<string, unknown>;
cancellationReason: string | null;
notesInternal: string | null;
/** The booking page's slot config, so the reschedule picker reuses the engine. */
pageConfig: SlotEngineConfig;
}
/** One appointment's detail (M06 Block D). Returns providerUserId so the route owner-checks. */
@@ -163,7 +167,17 @@ export async function getAppointmentDetail(tenantId: string, appointmentId: stri
intakeAnswers: true,
cancellationReason: true,
notesInternal: true,
bookingPage: { select: { title: true } },
bookingPage: {
select: {
title: true,
durationMinutes: true,
bufferBeforeMinutes: true,
bufferAfterMinutes: true,
slotIncrementMinutes: true,
minNoticeHours: true,
maxAdvanceDays: true,
},
},
},
});
if (!row) {
@@ -183,6 +197,7 @@ export async function getAppointmentDetail(tenantId: string, appointmentId: stri
intakeAnswers: (row.intakeAnswers as Record<string, unknown>) ?? {},
cancellationReason: row.cancellationReason,
notesInternal: row.notesInternal,
pageConfig: toConfig(row.bookingPage),
};
}
@@ -215,13 +230,14 @@ export interface BookingPageEdit {
confirmationEmailBody: string;
isPublished: boolean;
providerUserIds: string[];
intakeFormId: string | null;
}
/** Load a booking page for the editor (M06 Block E.2). */
export async function getBookingPageForEdit(tenantId: string, pageId: string): Promise<BookingPageEdit | null> {
const row = await db.bookingPage.findFirst({
where: { id: pageId, tenantId, archivedAt: null },
select: { id: true, slug: true, title: true, description: true, durationMinutes: true, confirmationEmailSubject: true, confirmationEmailBody: true, isPublished: true, providers: { select: { providerUserId: true } } },
select: { id: true, slug: true, title: true, description: true, durationMinutes: true, confirmationEmailSubject: true, confirmationEmailBody: true, isPublished: true, intakeFormId: true, providers: { select: { providerUserId: true } } },
});
if (!row) {
return null;
@@ -236,9 +252,25 @@ export async function getBookingPageForEdit(tenantId: string, pageId: string): P
confirmationEmailBody: row.confirmationEmailBody,
isPublished: row.isPublished,
providerUserIds: row.providers.map((p) => p.providerUserId),
intakeFormId: row.intakeFormId,
};
}
export interface IntakeFormOption {
id: string;
name: string;
}
/** Non-archived tenant forms selectable as a booking page's intake form (AK-P16c link). */
export async function listIntakeFormOptions(tenantId: string): Promise<IntakeFormOption[]> {
const rows = await db.form.findMany({
where: { tenantId, status: { not: "archived" } },
select: { id: true, name: true },
orderBy: { updatedAt: "desc" },
});
return rows.map((r) => ({ id: r.id, name: r.name }));
}
export interface BookingPageInput {
tenantId: string;
createdByUserId: string;
@@ -250,11 +282,51 @@ export interface BookingPageInput {
confirmationEmailBody: string;
isPublished: boolean;
providerUserIds: string[];
intakeFormId?: string | null;
}
async function validateBookingPageReferences(
tx: TenantRlsClient,
input: Pick<BookingPageInput, "tenantId" | "providerUserIds" | "intakeFormId">,
): Promise<string[] | null> {
const providerUserIds = [...new Set(input.providerUserIds)];
if (providerUserIds.length === 0) {
return null;
}
const activeProviders = await tx.tenantUser.findMany({
where: {
tenantId: input.tenantId,
userId: { in: providerUserIds },
status: TenantUserStatus.ACTIVE,
},
select: { userId: true },
});
const activeProviderIds = new Set(activeProviders.map((provider) => provider.userId));
if (providerUserIds.some((providerUserId) => !activeProviderIds.has(providerUserId))) {
return null;
}
if (input.intakeFormId) {
const intakeForm = await tx.form.findFirst({
where: { id: input.intakeFormId, tenantId: input.tenantId, status: { not: "archived" } },
select: { id: true },
});
if (!intakeForm) {
return null;
}
}
return providerUserIds;
}
/** Create a booking page + its provider links (M06 Block E.2). */
export async function createBookingPage(input: BookingPageInput): Promise<string> {
return db.$transaction(async (tx) => {
export async function createBookingPage(input: BookingPageInput): Promise<string | null> {
return withTenantRLS(input.tenantId, async (tx) => {
const providerUserIds = await validateBookingPageReferences(tx, input);
if (!providerUserIds) {
return null;
}
const page = await tx.bookingPage.create({
data: {
tenantId: input.tenantId,
@@ -266,21 +338,35 @@ export async function createBookingPage(input: BookingPageInput): Promise<string
confirmationEmailSubject: input.confirmationEmailSubject,
confirmationEmailBody: input.confirmationEmailBody,
isPublished: input.isPublished,
intakeFormId: input.intakeFormId ?? null,
},
select: { id: true },
});
await tx.bookingPageProvider.createMany({
data: input.providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: page.id, providerUserId, displayOrder: index })),
data: providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: page.id, providerUserId, displayOrder: index })),
});
return page.id;
});
}
/** Update a booking page + replace its provider links (M06 Block E.2). */
export async function updateBookingPage(pageId: string, input: BookingPageInput): Promise<void> {
await db.$transaction(async (tx) => {
export async function updateBookingPage(pageId: string, input: BookingPageInput): Promise<boolean> {
return withTenantRLS(input.tenantId, async (tx) => {
const page = await tx.bookingPage.findFirst({
where: { id: pageId, tenantId: input.tenantId, archivedAt: null },
select: { id: true },
});
if (!page) {
return false;
}
const providerUserIds = await validateBookingPageReferences(tx, input);
if (!providerUserIds) {
return false;
}
await tx.bookingPage.update({
where: { id: pageId },
where: { id: page.id, tenantId: input.tenantId },
data: {
slug: input.slug,
title: input.title,
@@ -289,12 +375,14 @@ export async function updateBookingPage(pageId: string, input: BookingPageInput)
confirmationEmailSubject: input.confirmationEmailSubject,
confirmationEmailBody: input.confirmationEmailBody,
isPublished: input.isPublished,
intakeFormId: input.intakeFormId ?? null,
},
});
await tx.bookingPageProvider.deleteMany({ where: { bookingPageId: pageId } });
await tx.bookingPageProvider.deleteMany({ where: { bookingPageId: page.id, tenantId: input.tenantId } });
await tx.bookingPageProvider.createMany({
data: input.providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: pageId, providerUserId, displayOrder: index })),
data: providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: page.id, providerUserId, displayOrder: index })),
});
return true;
});
}
@@ -0,0 +1,101 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadBookingContext: vi.fn(),
requireBookingPermission: vi.fn(),
validateCSRFToken: vi.fn(),
getBookingPageForEdit: vi.fn(),
createBookingPage: vi.fn(),
updateBookingPage: vi.fn(),
isSlugTaken: vi.fn(),
getTenantUsers: vi.fn(),
listIntakeFormOptions: vi.fn(),
getTranslations: vi.fn(),
}));
vi.mock("./bookingAccess.server", () => ({
BOOKING_PERMISSIONS: { admin: "bookings.admin" },
loadBookingContext: mocks.loadBookingContext,
requireBookingPermission: mocks.requireBookingPermission,
}));
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRFToken }));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: mocks.getTranslations }));
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenantUsers: mocks.getTenantUsers }));
vi.mock("../db/booking.db.server", () => ({
getBookingPageForEdit: mocks.getBookingPageForEdit,
createBookingPage: mocks.createBookingPage,
updateBookingPage: mocks.updateBookingPage,
isSlugTaken: mocks.isSlugTaken,
listIntakeFormOptions: mocks.listIntakeFormOptions,
}));
import { bookingPageEditorAction, bookingPageEditorLoader } from "./BookingPageEditor.server";
function actionRequest(): Request {
const form = new URLSearchParams();
form.set("slug", "beratung");
form.set("title", "Beratung");
form.set("providers", "provider-a");
form.set("durationMinutes", "30");
return new Request("http://app.localhost/acme/bookings/pages/page-a", { method: "POST", body: form });
}
describe("booking page editor action tenant boundary", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.loadBookingContext.mockResolvedValue({
tenantId: "tenant-a",
userId: "admin-a",
permissions: ["bookings.admin"],
hasModule: true,
});
mocks.getBookingPageForEdit.mockResolvedValue({ id: "page-a" });
mocks.isSlugTaken.mockResolvedValue(false);
mocks.updateBookingPage.mockResolvedValue(true);
mocks.getTenantUsers.mockResolvedValue([]);
mocks.listIntakeFormOptions.mockResolvedValue([]);
mocks.getTranslations.mockResolvedValue({ t: (key: string) => key });
});
it("returns 404 for a foreign edit target before parsing or writing", async () => {
mocks.getBookingPageForEdit.mockResolvedValueOnce(null);
await expect(bookingPageEditorAction({ request: actionRequest(), params: { tenant: "acme", id: "page-from-tenant-b" } } as never)).rejects.toMatchObject({
status: 404,
});
expect(mocks.getBookingPageForEdit).toHaveBeenCalledWith("tenant-a", "page-from-tenant-b");
expect(mocks.isSlugTaken).not.toHaveBeenCalled();
expect(mocks.updateBookingPage).not.toHaveBeenCalled();
});
it("returns 404 when the transaction loses the tenant-owned target", async () => {
mocks.updateBookingPage.mockResolvedValueOnce(false);
await expect(bookingPageEditorAction({ request: actionRequest(), params: { tenant: "acme", id: "page-a" } } as never)).rejects.toMatchObject({
status: 404,
});
expect(mocks.updateBookingPage).toHaveBeenCalledWith("page-a", expect.objectContaining({ tenantId: "tenant-a" }));
});
it("exposes a translated title for the new-page breadcrumb", async () => {
const result = await bookingPageEditorLoader({
request: new Request("http://app.localhost/acme/bookings/pages/new"),
params: { tenant: "acme" },
} as never);
expect(result).toMatchObject({ data: { title: `bookings.pages.new | ${process.env.APP_NAME}` } });
});
it("uses the booking page name for an edit breadcrumb", async () => {
mocks.getBookingPageForEdit.mockResolvedValueOnce({ id: "page-a", slug: "beratung", title: "Erstberatung" });
const result = await bookingPageEditorLoader({
request: new Request("http://app.localhost/acme/bookings/pages/page-a"),
params: { tenant: "acme", id: "page-a" },
} as never);
expect(result).toMatchObject({ data: { title: `Erstberatung | ${process.env.APP_NAME}` } });
});
});
@@ -5,16 +5,30 @@
import { type LoaderFunctionArgs, type ActionFunctionArgs, data, redirect } from "react-router";
import { validateCSRFToken } from "~/utils/session.server";
import { getTranslations } from "~/locale/i18next.server";
import { getTenantUsers } from "~/utils/db/tenants.db.server";
import { loadBookingContext, requireBookingPermission, BOOKING_PERMISSIONS } from "./bookingAccess.server";
import { RESERVED_BOOKING_SLUGS, bookingPagesListPath, publicBookingPath, publicBookingEmbedPath, notFoundResponse } from "./bookingRoutePaths";
import { getBookingPageForEdit, createBookingPage, updateBookingPage, isSlugTaken, type BookingPageEdit } from "../db/booking.db.server";
import { getBookingPageForEdit, createBookingPage, updateBookingPage, isSlugTaken, listIntakeFormOptions, type BookingPageEdit, type IntakeFormOption } from "../db/booking.db.server";
export interface BookingPageProviderOption {
readonly id: string;
readonly label: string;
}
export interface BookingPageEditorLoaderData {
readonly title: string;
readonly mode: "new" | "edit";
readonly tenantSlug: string;
readonly page: BookingPageEdit | null;
readonly publicUrl: string | null;
readonly embedCode: string | null;
readonly providerOptions: readonly BookingPageProviderOption[];
readonly intakeFormOptions: readonly IntakeFormOption[];
/** Booking-pages list this editor sits under — back link target. */
readonly listHref: string;
/** Breadcrumb ancestor for the shell: the booking-pages list this editor sits under. */
readonly breadcrumbAncestors: readonly { readonly label: string; readonly href: string }[];
}
export type BookingPageEditorActionData = { readonly ok: false; readonly errorKey: string; readonly field?: string };
@@ -24,6 +38,7 @@ function embedSnippet(url: string): string {
}
export async function bookingPageEditorLoader({ request, params }: LoaderFunctionArgs) {
const { t } = await getTranslations(request);
const ctx = await loadBookingContext({ request, params, requireModule: true });
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
const tenantSlug = params.tenant ?? "";
@@ -36,7 +51,29 @@ export async function bookingPageEditorLoader({ request, params }: LoaderFunctio
const publicUrl = page ? `${origin}${publicBookingPath(tenantSlug, page.slug)}` : null;
const embedCode = page ? embedSnippet(`${origin}${publicBookingEmbedPath(tenantSlug, page.slug)}`) : null;
return data<BookingPageEditorLoaderData>({ mode: params.id ? "edit" : "new", tenantSlug, page, publicUrl, embedCode });
const [members, intakeFormOptions] = await Promise.all([getTenantUsers(ctx.tenantId), listIntakeFormOptions(ctx.tenantId)]);
const providerOptions: BookingPageProviderOption[] = members.map((member) => ({
id: member.userId,
label: [member.user.firstName, member.user.lastName].filter(Boolean).join(" ") || member.user.email,
}));
const pageTitle = page?.title ?? t(params.id ? "bookings.pages.editor.title" : "bookings.pages.new");
return data<BookingPageEditorLoaderData>({
title: `${pageTitle} | ${process.env.APP_NAME}`,
mode: params.id ? "edit" : "new",
tenantSlug,
page,
publicUrl,
embedCode,
providerOptions,
intakeFormOptions,
listHref: bookingPagesListPath(tenantSlug),
// Names the booking-pages list this editor was reached through, so the shell
// breadcrumb reads tenant > Termine > Booking-Seiten > <page> instead of
// jumping straight from the module crumb to the page.
breadcrumbAncestors: [{ label: t("bookings.pages.title"), href: bookingPagesListPath(tenantSlug) }],
});
}
export async function bookingPageEditorAction({ request, params }: ActionFunctionArgs) {
@@ -44,6 +81,10 @@ export async function bookingPageEditorAction({ request, params }: ActionFunctio
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
await validateCSRFToken(request);
if (params.id && !(await getBookingPageForEdit(ctx.tenantId, params.id))) {
throw notFoundResponse();
}
const form = await request.formData();
const slug = ((form.get("slug") as string | null) ?? "").trim().toLowerCase();
const title = ((form.get("title") as string | null) ?? "").trim();
@@ -77,12 +118,14 @@ export async function bookingPageEditorAction({ request, params }: ActionFunctio
confirmationEmailBody: ((form.get("confirmationEmailBody") as string | null) ?? "").trim() || "Dein Termin ist bestätigt.",
isPublished: form.get("isPublished") === "on" || form.get("isPublished") === "true",
providerUserIds,
// AK-P16c link: the selected intake form drives the real FormSubmission on booking.
intakeFormId: ((form.get("intakeFormId") as string | null) ?? "").trim() || null,
};
if (params.id) {
await updateBookingPage(params.id, input);
} else {
await createBookingPage(input);
const writeResult = params.id ? await updateBookingPage(params.id, input) : await createBookingPage(input);
if (!writeResult) {
throw notFoundResponse();
}
return redirect(bookingPagesListPath(params.tenant ?? ""));
const messageKey = params.id ? "bookings.pages.toast.saved" : "bookings.pages.toast.created";
return redirect(`${bookingPagesListPath(params.tenant ?? "")}?toast=${encodeURIComponent(messageKey)}`);
}
@@ -0,0 +1,21 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
import { normalizePublicBookingRedirect } from "./PublicBooking.server";
describe("public booking completion redirect", () => {
test("allows HTTPS completion URLs and local HTTP development targets", () => {
expect(normalizePublicBookingRedirect("https://customer.example/thanks?booking=1")).toBe(
"https://customer.example/thanks?booking=1",
);
expect(normalizePublicBookingRedirect("http://localhost:3000/thanks")).toBe("http://localhost:3000/thanks");
});
test("rejects scriptable, relative, malformed and oversized redirect values", () => {
expect(normalizePublicBookingRedirect("javascript:alert(document.cookie)")).toBeNull();
expect(normalizePublicBookingRedirect("data:text/html,<script>alert(1)</script>")).toBeNull();
expect(normalizePublicBookingRedirect("//attacker.example/phish")).toBeNull();
expect(normalizePublicBookingRedirect("/relative-path")).toBeNull();
expect(normalizePublicBookingRedirect("http://customer.example/phish")).toBeNull();
expect(normalizePublicBookingRedirect("x".repeat(2_049))).toBeNull();
});
});
@@ -0,0 +1,77 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActionFunctionArgs } from "react-router";
const mocks = vi.hoisted(() => ({
checkAuthRateLimit: vi.fn(),
resolvePublicBookingPageRlsIdentity: vi.fn(),
resolvePublicBookingPage: vi.fn(),
submitBooking: vi.fn(),
}));
vi.mock("~/services/auth/auth-rate-limit.server", () => ({ checkAuthRateLimit: mocks.checkAuthRateLimit }));
vi.mock("@hivegrid/db/rls-resolvers.server", () => ({
resolvePublicBookingPageRlsIdentity: mocks.resolvePublicBookingPageRlsIdentity,
}));
vi.mock("../db/booking.db.server", () => ({ resolvePublicBookingPage: mocks.resolvePublicBookingPage }));
vi.mock("../services/SlotQueryService.server", () => ({ loadSlotsForDate: vi.fn() }));
vi.mock("../services/slotEngine", () => ({ pickFirstAvailableProvider: vi.fn() }));
vi.mock("../services/BookingSubmitService.server", () => ({
BookingSlotTakenError: class BookingSlotTakenError extends Error {},
BookingValidationError: class BookingValidationError extends Error {},
submitBooking: mocks.submitBooking,
}));
const { publicBookingAction } = await import("./PublicBooking.server");
beforeEach(() => {
vi.clearAllMocks();
mocks.checkAuthRateLimit.mockResolvedValue({ allowed: true });
mocks.resolvePublicBookingPageRlsIdentity.mockResolvedValue({ tenantId: "tenant_1", resourceId: "page_1" });
});
describe("public booking abuse protection", () => {
it("rate-limits before page lookup, form parsing, or booking writes", async () => {
mocks.checkAuthRateLimit.mockResolvedValueOnce({ allowed: false, retryAfterSeconds: 45 });
const request = new Request("https://app.example.test/b/acme/consulting", {
method: "POST",
body: "attacker-controlled-body",
});
const response = await publicBookingAction({
request,
params: { tenant: "acme", slug: "consulting" },
context: {},
unstable_pattern: "b.$tenant.$slug",
} as ActionFunctionArgs);
expect(response.status).toBe(429);
expect(response.headers.get("Retry-After")).toBe("45");
expect(response.headers.get("Cache-Control")).toBe("no-store");
expect(mocks.checkAuthRateLimit).toHaveBeenCalledWith(expect.objectContaining({ action: "booking-submit", identifier: "acme/consulting", limit: 10 }));
expect(mocks.resolvePublicBookingPage).not.toHaveBeenCalled();
expect(mocks.submitBooking).not.toHaveBeenCalled();
});
it("enters the resolved tenant context before reading the protected booking page", async () => {
const { getRlsExecutionContext } = await import("@hivegrid/db/rls-context.server");
mocks.resolvePublicBookingPage.mockImplementationOnce(async () => {
expect(getRlsExecutionContext()).toMatchObject({ tenantId: "tenant_1" });
return null;
});
const request = new Request("https://app.example.test/b/acme/consulting", {
method: "POST",
body: new URLSearchParams(),
});
await expect(
publicBookingAction({
request,
params: { tenant: "acme", slug: "consulting" },
context: {},
unstable_pattern: "b.$tenant.$slug",
} as ActionFunctionArgs)
).rejects.toMatchObject({ status: 404 });
expect(mocks.resolvePublicBookingPageRlsIdentity).toHaveBeenCalledWith("acme", "consulting");
});
});
@@ -12,8 +12,14 @@ import { resolvePublicBookingPage } from "../db/booking.db.server";
import { loadSlotsForDate } from "../services/SlotQueryService.server";
import { pickFirstAvailableProvider } from "../services/slotEngine";
import { submitBooking, BookingValidationError, BookingSlotTakenError } from "../services/BookingSubmitService.server";
import { checkAuthRateLimit } from "~/services/auth/auth-rate-limit.server";
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
import { resolvePublicBookingPageRlsIdentity } from "@hivegrid/db/rls-resolvers.server";
import { getTranslations } from "~/locale/i18next.server";
const DEFAULT_TZ = "Europe/Berlin";
const BOOKING_SUBMIT_RATE_LIMIT = 10;
const BOOKING_SUBMIT_RATE_WINDOW_MS = 60 * 1000;
export interface PublicBookingSlotVM {
readonly startAtIso: string;
@@ -49,7 +55,14 @@ function resolveDate(url: URL, timezone: string, now: Date): string {
return formatInTimeZone(now, timezone, "yyyy-MM-dd");
}
async function buildSlots(tenantId: string, providerUserIds: string[], date: string, config: Parameters<typeof loadSlotsForDate>[0]["config"], timezone: string, now: Date): Promise<PublicBookingSlotVM[]> {
async function buildSlots(
tenantId: string,
providerUserIds: string[],
date: string,
config: Parameters<typeof loadSlotsForDate>[0]["config"],
timezone: string,
now: Date
): Promise<PublicBookingSlotVM[]> {
const slots = await loadSlotsForDate({ tenantId, providerUserIds, date, config, now });
return slots
.filter((slot) => pickFirstAvailableProvider(slot) !== null)
@@ -57,80 +70,127 @@ async function buildSlots(tenantId: string, providerUserIds: string[], date: str
}
export async function publicBookingLoader({ request, params }: LoaderFunctionArgs) {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
const identity = await resolvePublicBookingPageRlsIdentity(params.tenant ?? "", params.slug ?? "");
if (!identity) {
throw notFoundResponse();
}
const url = new URL(request.url);
const now = new Date();
const timezone = resolveTimezone(url);
const date = resolveDate(url, timezone, now);
const slots = await buildSlots(page.tenantId, page.providerUserIds, date, page.config, timezone, now);
return runWithRlsContext({ tenantId: identity.tenantId }, async () => {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
throw notFoundResponse();
}
const url = new URL(request.url);
const now = new Date();
const timezone = resolveTimezone(url);
const date = resolveDate(url, timezone, now);
const slots = await buildSlots(page.tenantId, page.providerUserIds, date, page.config, timezone, now);
const payload: PublicBookingLoaderData = {
tenantSlug: page.tenantSlug,
slug: page.slug,
title: page.title,
description: page.description,
tenantName: page.tenantName,
durationMinutes: page.durationMinutes,
date,
timezone,
slots,
isEmbed: url.pathname.endsWith("/embed"),
};
return data(payload);
const payload: PublicBookingLoaderData = {
tenantSlug: page.tenantSlug,
slug: page.slug,
title: page.title,
description: page.description,
tenantName: page.tenantName,
durationMinutes: page.durationMinutes,
date,
timezone,
slots,
isEmbed: url.pathname.endsWith("/embed"),
};
return data(payload);
});
}
export async function publicBookingAction({ request, params }: ActionFunctionArgs) {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
const rateLimit = await checkAuthRateLimit({
request,
action: "booking-submit",
identifier: `${params.tenant ?? ""}/${params.slug ?? ""}`,
limit: BOOKING_SUBMIT_RATE_LIMIT,
windowMs: BOOKING_SUBMIT_RATE_WINDOW_MS,
});
if (!rateLimit.allowed) {
return Response.json(
{ ok: false, errorKey: "bookings.error.submitFailed" },
{
status: 429,
headers: {
"Cache-Control": "no-store",
"Retry-After": String(rateLimit.retryAfterSeconds),
},
}
);
}
const identity = await resolvePublicBookingPageRlsIdentity(params.tenant ?? "", params.slug ?? "");
if (!identity) {
throw notFoundResponse();
}
const form = await request.formData();
return runWithRlsContext({ tenantId: identity.tenantId }, async () => {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
throw notFoundResponse();
}
const form = await request.formData();
// Honeypot: real users never fill this hidden field (M06 abuse guard).
if ((form.get("company") as string | null)?.trim()) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 400 });
}
// Honeypot: real users never fill this hidden field (M06 abuse guard).
if ((form.get("company") as string | null)?.trim()) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 400 });
}
const url = new URL(request.url);
const timezone = (form.get("tz") as string | null) || resolveTimezone(url);
const date = (form.get("date") as string | null) ?? "";
const startAtIso = (form.get("startAt") as string | null) ?? "";
const url = new URL(request.url);
const timezone = (form.get("tz") as string | null) || resolveTimezone(url);
const date = (form.get("date") as string | null) ?? "";
const startAtIso = (form.get("startAt") as string | null) ?? "";
const translations = await getTranslations(request);
try {
const result = await submitBooking({
page,
startAtIso,
date,
viewerTimeZone: timezone,
locale: translations.locale,
intake: {
vorname: (form.get("vorname") as string | null) ?? "",
nachname: (form.get("nachname") as string | null) ?? "",
email: (form.get("email") as string | null) ?? "",
telefon: (form.get("telefon") as string | null) ?? undefined,
gdprAccepted: form.get("gdpr") === "on" || form.get("gdpr") === "true",
},
now: new Date(),
});
const redirectUrl = normalizePublicBookingRedirect(result.redirectUrl);
if (redirectUrl) {
return redirect(redirectUrl);
}
return data<PublicBookingActionData>({
ok: true,
titleLabel: page.title,
dateLabel: formatInTimeZone(result.startAt, timezone, "dd.MM.yyyy"),
timeLabel: formatInTimeZone(result.startAt, timezone, "HH:mm"),
icsBase64: result.icsBase64,
});
} catch (error) {
if (error instanceof BookingValidationError) {
return data<PublicBookingActionData>({ ok: false, errorKey: error.code, field: error.field }, { status: 400 });
}
if (error instanceof BookingSlotTakenError) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.slotTaken" }, { status: 409 });
}
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 500 });
}
});
}
export function normalizePublicBookingRedirect(value: string | null | undefined): string | null {
if (!value || value.length > 2_048) return null;
try {
const result = await submitBooking({
page,
startAtIso,
date,
viewerTimeZone: timezone,
intake: {
vorname: (form.get("vorname") as string | null) ?? "",
nachname: (form.get("nachname") as string | null) ?? "",
email: (form.get("email") as string | null) ?? "",
telefon: (form.get("telefon") as string | null) ?? undefined,
gdprAccepted: form.get("gdpr") === "on" || form.get("gdpr") === "true",
},
now: new Date(),
});
if (result.redirectUrl) {
return redirect(result.redirectUrl);
}
return data<PublicBookingActionData>({
ok: true,
titleLabel: page.title,
dateLabel: formatInTimeZone(result.startAt, timezone, "dd.MM.yyyy"),
timeLabel: formatInTimeZone(result.startAt, timezone, "HH:mm"),
icsBase64: result.icsBase64,
});
} catch (error) {
if (error instanceof BookingValidationError) {
return data<PublicBookingActionData>({ ok: false, errorKey: error.code, field: error.field }, { status: 400 });
}
if (error instanceof BookingSlotTakenError) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.slotTaken" }, { status: 409 });
}
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 500 });
const url = new URL(value);
const localDevelopmentUrl = url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]");
if (url.protocol !== "https:" && !localDevelopmentUrl) return null;
return url.toString();
} catch {
return null;
}
}
@@ -39,6 +39,21 @@ describe("booking route authorization boundary", () => {
expect(source).toContain('intent === "reassign"');
});
test("availability action guards permission + CSRF before parsing the form", () => {
const source = fs.readFileSync(path.join(appRoot, "routes/app.$tenant/availability.tsx"), "utf8");
const formDataAt = source.indexOf("await request.formData()");
expect(formDataAt).toBeGreaterThanOrEqual(0);
const permissionAt = source.indexOf("requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn)", source.indexOf("export const action"));
const csrfAt = source.indexOf("await validateCSRFToken(request)");
expect(permissionAt).toBeGreaterThanOrEqual(0);
expect(csrfAt).toBeGreaterThanOrEqual(0);
expect(permissionAt).toBeLessThan(formDataAt);
expect(csrfAt).toBeLessThan(formDataAt);
// The action only ever writes the CALLER's availability (own scope).
expect(source).toContain("providerUserId: ctx.userId");
});
test("booking-page editor action guards admin permission + CSRF before parsing the form", () => {
const source = fs.readFileSync(path.join(appRoot, "modules/booking/routes/BookingPageEditor.server.ts"), "utf8");
const formDataAt = source.indexOf("await request.formData()");
@@ -8,10 +8,14 @@
import { formatInTimeZone } from "date-fns-tz";
import { logActivity, type ActivityType } from "@hivegrid/activity";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { notify, type NotificationClient } from "@hivegrid/foundation";
import { renderSystemMessageEmail, type SystemMessageDetail } from "@hivegrid/mail";
import { getMailTranslator, type MailTranslator } from "~/locale/mail-translator.server";
import { db } from "~/utils/db.server";
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
import { assertTransition, statusAfter, notifiesCustomer, type LifecycleAction } from "./bookingTransitions";
import { buildBookingCancelledWorkflowEvent, buildCalendarCreatedWorkflowEvent } from "./bookingAutomationEvents.server";
const MINUTE_MS = 60_000;
@@ -27,6 +31,7 @@ interface AppointmentForAction {
internalCalendarEventId: string | null;
intakeAnswers: unknown;
pageTitle: string;
bookingPageSlug: string;
durationMinutes: number;
tenantName: string;
}
@@ -45,7 +50,7 @@ async function loadAppointmentForAction(tenantId: string, appointmentId: string)
timezone: true,
internalCalendarEventId: true,
intakeAnswers: true,
bookingPage: { select: { title: true, durationMinutes: true } },
bookingPage: { select: { title: true, slug: true, durationMinutes: true } },
},
});
if (!row) {
@@ -64,6 +69,7 @@ async function loadAppointmentForAction(tenantId: string, appointmentId: string)
internalCalendarEventId: row.internalCalendarEventId,
intakeAnswers: row.intakeAnswers,
pageTitle: row.bookingPage.title,
bookingPageSlug: row.bookingPage.slug,
durationMinutes: row.bookingPage.durationMinutes,
tenantName: tenant?.name ?? "",
};
@@ -77,7 +83,21 @@ function bookerEmail(intakeAnswers: unknown): string | null {
return null;
}
async function recordActivity(tenantId: string, appt: AppointmentForAction, activityType: ActivityType, summaryText: string, actorUserId: string | null): Promise<void> {
function bookerLocale(intakeAnswers: unknown): string | null {
if (intakeAnswers && typeof intakeAnswers === "object" && "locale" in intakeAnswers) {
const locale = (intakeAnswers as { locale?: unknown }).locale;
return typeof locale === "string" && locale.trim() ? locale.trim() : null;
}
return null;
}
async function recordActivity(
tenantId: string,
appt: AppointmentForAction,
activityType: ActivityType,
summaryText: string,
actorUserId: string | null
): Promise<void> {
if (!appt.kontaktId) {
return;
}
@@ -95,39 +115,114 @@ async function recordActivity(tenantId: string, appt: AppointmentForAction, acti
async function notifyProvider(tenantId: string, providerUserId: string, messageKey: string, appointmentId: string): Promise<void> {
await notify(
{ tenantId, userId: providerUserId, channel: "IN_APP", category: "bookings", messageKey, sourceKey: `${messageKey}:${appointmentId}`, payloadMetadata: { appointmentId } },
{
tenantId,
userId: providerUserId,
channel: "IN_APP",
category: "bookings",
messageKey,
sourceKey: `${messageKey}:${appointmentId}`,
payloadMetadata: { appointmentId },
},
db as unknown as NotificationClient
).catch(() => undefined);
}
async function sendLifecycleMail(appt: AppointmentForAction, subject: string, body: string): Promise<boolean> {
async function sendLifecycleMail(
appt: AppointmentForAction,
input: {
readonly kind: "cancelled" | "reassigned" | "rescheduled";
readonly newWhen?: string;
readonly reason?: string;
}
): Promise<boolean> {
const to = bookerEmail(appt.intakeAnswers);
if (!to) {
return false;
}
try {
await sendEmailMailjet({ data: { to, subject, body: body.replace(/\r?\n/gu, "<br/>") } });
const { t, locale } = await getMailTranslator(bookerLocale(appt.intakeAnswers));
const content = lifecycleMailContent(t, appt, input);
const rendered = renderSystemMessageEmail({
locale,
subject: content.subject,
previewText: content.intro,
eyebrow: content.eyebrow,
title: content.title,
intro: content.intro,
details: content.details,
notice: content.notice,
noticeTone: content.notice ? "info" : undefined,
});
await sendEmailMailjet({
data: {
to,
subject: content.subject,
body: rendered.html,
text: rendered.text,
},
});
return true;
} catch {
return false;
}
}
function lifecycleMailContent(
t: MailTranslator,
appt: AppointmentForAction,
input: {
readonly kind: "cancelled" | "reassigned" | "rescheduled";
readonly newWhen?: string;
readonly reason?: string;
}
): {
readonly subject: string;
readonly eyebrow: string;
readonly title: string;
readonly intro: string;
readonly details: readonly SystemMessageDetail[];
readonly notice?: string;
} {
const prefix = `booking.${input.kind}`;
const details: SystemMessageDetail[] = [{ label: t(`${prefix}.fields.appointment`), value: appt.pageTitle }];
if (input.kind === "rescheduled") {
details.push({ label: t(`${prefix}.fields.previous`), value: whenLabel(appt) }, { label: t(`${prefix}.fields.new`), value: input.newWhen ?? "" });
} else {
details.push({ label: t(`${prefix}.fields.when`), value: whenLabel(appt) });
}
return {
subject: t(`${prefix}.subject`, { title: appt.pageTitle }),
eyebrow: t(`${prefix}.eyebrow`),
title: t(`${prefix}.title`),
intro: t(`${prefix}.intro`),
details,
notice: input.reason ? t(`${prefix}.reason`, { reason: input.reason }) : undefined,
};
}
function whenLabel(appt: AppointmentForAction): string {
return formatInTimeZone(appt.startAt, appt.timezone, "dd.MM.yyyy HH:mm");
}
/** Mark a past appointment as held (M06 D). */
export async function markAppointmentHeld(tenantId: string, appointmentId: string, actorUserId: string): Promise<void> {
await applyStatusOnly(tenantId, appointmentId, "mark_held", actorUserId, "appointment_held", "als stattgefunden markiert");
await applyStatusOnly(tenantId, appointmentId, "mark_held", actorUserId, "appointment_held", "activity.runtime.booking.held");
}
/** Mark an appointment as no-show (M06 D). */
export async function markAppointmentNoShow(tenantId: string, appointmentId: string, actorUserId: string): Promise<void> {
await applyStatusOnly(tenantId, appointmentId, "mark_no_show", actorUserId, "appointment_no_show", "als nicht erschienen markiert");
await applyStatusOnly(tenantId, appointmentId, "mark_no_show", actorUserId, "appointment_no_show", "activity.runtime.booking.noShow");
}
async function applyStatusOnly(tenantId: string, appointmentId: string, action: LifecycleAction, actorUserId: string, activityType: ActivityType, summaryVerb: string): Promise<void> {
async function applyStatusOnly(
tenantId: string,
appointmentId: string,
action: LifecycleAction,
actorUserId: string,
activityType: ActivityType,
summaryKey: string
): Promise<void> {
const appt = await loadAppointmentForAction(tenantId, appointmentId);
if (!appt) {
return;
@@ -137,35 +232,64 @@ async function applyStatusOnly(tenantId: string, appointmentId: string, action:
if (next) {
await db.appointment.update({ where: { id: appt.id }, data: { status: next } });
}
await recordActivity(tenantId, appt, activityType, `Termin ${appt.pageTitle} (${whenLabel(appt)}) ${summaryVerb}`, actorUserId);
await recordActivity(tenantId, appt, activityType, summaryKey, actorUserId);
}
/** Cancel an appointment with a reason + auto-mail (M06 D / I). */
export async function cancelAppointment(input: { tenantId: string; appointmentId: string; reason: string; byKind: "customer" | "provider" | "system"; actorUserId: string | null }): Promise<void> {
export async function cancelAppointment(input: {
tenantId: string;
appointmentId: string;
reason: string;
byKind: "customer" | "provider" | "system";
actorUserId: string | null;
}): Promise<void> {
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
if (!appt) {
return;
}
assertTransition(appt.status, "cancel");
const cancelledAt = new Date();
await db.$transaction(async (tx) => {
await tx.appointment.update({
where: { id: appt.id },
data: { status: "cancelled", cancelledAt: new Date(), cancelledByKind: input.byKind, cancellationReason: input.reason },
data: { status: "cancelled", cancelledAt, cancelledByKind: input.byKind, cancellationReason: input.reason },
});
if (appt.internalCalendarEventId) {
// Free the slot: archive the local mirror so it stops blocking availability.
await tx.calendarEvent.update({ where: { id: appt.internalCalendarEventId }, data: { archivedAt: new Date(), isBusyForAvailability: false } });
}
await publishOutboxEvent(
tx as unknown as OutboxPublisherTransaction,
buildBookingCancelledWorkflowEvent({
tenantId: input.tenantId,
appointmentId: appt.id,
bookingPageId: appt.bookingPageId,
bookingPageSlug: appt.bookingPageSlug,
providerUserId: appt.providerUserId,
cancelledByKind: input.byKind,
cancellationReason: input.reason,
cancelledAt,
actorUserId: input.actorUserId,
})
);
});
await sendLifecycleMail(appt, `Termin storniert: ${appt.pageTitle}`, `Dein Termin am ${whenLabel(appt)} wurde storniert.\nGrund: ${input.reason}`);
await recordActivity(input.tenantId, appt, "appointment_cancelled", `Termin ${appt.pageTitle} (${whenLabel(appt)}) storniert: ${input.reason}`, input.actorUserId);
await sendLifecycleMail(appt, {
kind: "cancelled",
reason: input.reason,
});
await recordActivity(input.tenantId, appt, "appointment_cancelled", "activity.runtime.booking.cancelled", input.actorUserId);
if (notifiesCustomer("cancel")) {
await notifyProvider(input.tenantId, appt.providerUserId, "bookings.status.cancelled", appt.id);
}
}
/** Reschedule to a new start time: supersede the old appointment with a successor (M06 D). */
export async function rescheduleAppointment(input: { tenantId: string; appointmentId: string; newStartAt: Date; actorUserId: string }): Promise<{ newAppointmentId: string }> {
export async function rescheduleAppointment(input: {
tenantId: string;
appointmentId: string;
newStartAt: Date;
actorUserId: string;
}): Promise<{ newAppointmentId: string }> {
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
if (!appt) {
throw new Error("appointment_not_found");
@@ -194,16 +318,42 @@ export async function rescheduleAppointment(input: { tenantId: string; appointme
select: { id: true },
});
const calendarEvent = await tx.calendarEvent.create({
data: { tenantId: input.tenantId, userId: appt.providerUserId, source: "hivegrid_internal", title: appt.pageTitle, startsAt: input.newStartAt, endsAt: newEndAt, isBusyForAvailability: true, internalEntityLink: { type: "booking_appointment", id: successor.id } },
data: {
tenantId: input.tenantId,
userId: appt.providerUserId,
source: "hivegrid_internal",
title: appt.pageTitle,
startsAt: input.newStartAt,
endsAt: newEndAt,
isBusyForAvailability: true,
internalEntityLink: { type: "booking_appointment", id: successor.id },
},
select: { id: true },
});
await tx.appointment.update({ where: { id: successor.id }, data: { internalCalendarEventId: calendarEvent.id } });
await publishOutboxEvent(
tx as unknown as OutboxPublisherTransaction,
buildCalendarCreatedWorkflowEvent({
tenantId: input.tenantId,
calendarEventId: calendarEvent.id,
userId: input.actorUserId,
calendarKey: "hauptkalender",
eventKind: "termin",
source: "booking_reschedule",
sourceEntityId: successor.id,
startsAt: input.newStartAt,
endsAt: newEndAt,
})
);
return successor.id;
});
const newWhen = formatInTimeZone(input.newStartAt, appt.timezone, "dd.MM.yyyy HH:mm");
await sendLifecycleMail(appt, `Termin verschoben: ${appt.pageTitle}`, `Dein Termin wurde von ${whenLabel(appt)} auf ${newWhen} verschoben.`);
await recordActivity(input.tenantId, appt, "appointment_rescheduled", `Termin ${appt.pageTitle} verschoben von ${whenLabel(appt)} auf ${newWhen}`, input.actorUserId);
await sendLifecycleMail(appt, {
kind: "rescheduled",
newWhen,
});
await recordActivity(input.tenantId, appt, "appointment_rescheduled", "activity.runtime.booking.rescheduled", input.actorUserId);
await notifyProvider(input.tenantId, appt.providerUserId, "bookings.status.rescheduled", newAppointmentId);
return { newAppointmentId };
}
@@ -222,7 +372,9 @@ export async function reassignAppointment(input: { tenantId: string; appointment
await tx.calendarEvent.update({ where: { id: appt.internalCalendarEventId }, data: { userId: input.newProviderUserId } });
}
});
await sendLifecycleMail(appt, `Termin: neuer Ansprechpartner — ${appt.pageTitle}`, `Dein Termin am ${whenLabel(appt)} wird von einem anderen Mitarbeiter betreut.`);
await recordActivity(input.tenantId, appt, "appointment_rescheduled", `Termin ${appt.pageTitle} (${whenLabel(appt)}) neu zugewiesen`, input.actorUserId);
await sendLifecycleMail(appt, {
kind: "reassigned",
});
await recordActivity(input.tenantId, appt, "appointment_rescheduled", "activity.runtime.booking.reassigned", input.actorUserId);
await notifyProvider(input.tenantId, input.newProviderUserId, "bookings.status.scheduled", appt.id);
}
@@ -13,14 +13,18 @@
import { formatInTimeZone } from "date-fns-tz";
import { logActivity } from "@hivegrid/activity";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { db } from "~/utils/db.server";
import { createLead } from "~/utils/integrations/leads/leadService.server";
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
import { renderSystemMessageEmail } from "@hivegrid/mail";
import { getMailTranslator } from "~/locale/mail-translator.server";
import type { PublicBookingPage } from "../db/booking.db.server";
import { findKontaktIdByEmail } from "../db/booking.db.server";
import { loadSlotsForDate } from "./SlotQueryService.server";
import { pickFirstAvailableProvider } from "./slotEngine";
import { buildIcs, icsToBase64 } from "./ics";
import { buildBookingBookedWorkflowEvents } from "./bookingAutomationEvents.server";
const MINUTE_MS = 60_000;
@@ -59,6 +63,7 @@ export interface BookingSubmitInput {
readonly date: string;
/** Booker's IANA timezone (for display + the appointment record). */
readonly viewerTimeZone: string;
readonly locale?: string;
readonly intake: BookingIntake;
readonly now: Date;
}
@@ -129,6 +134,7 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
email: input.intake.email.trim(),
telefon: input.intake.telefon?.trim() ?? null,
gdprAccepted: true,
locale: input.locale ?? "de",
};
const eventTitle = renderTemplate(page.internalEventTitleTemplate ?? "{{booking_page.title}}", {
"booking_page.title": page.title,
@@ -206,6 +212,19 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
where: { id: appointment.id },
data: { internalCalendarEventId: calendarEvent.id, formSubmissionId: formSubmission?.id ?? null },
});
for (const event of buildBookingBookedWorkflowEvents({
tenantId: page.tenantId,
appointmentId: appointment.id,
bookingPageId: page.pageId,
bookingPageSlug: page.slug,
providerUserId,
calendarEventId: calendarEvent.id,
startAt,
endAt,
kontaktId,
})) {
await publishOutboxEvent(tx as unknown as OutboxPublisherTransaction, event);
}
return appointment.id;
},
{ isolationLevel: "Serializable" }
@@ -238,7 +257,7 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
}
// 4) Activity on the contact/lead (M06 J.4). Best-effort — never break the booking.
const activitySubject = kontaktId ? ({ type: "contact" as const, id: kontaktId }) : leadId ? ({ type: "lead" as const, id: leadId }) : null;
const activitySubject = kontaktId ? { type: "contact" as const, id: kontaktId } : leadId ? { type: "lead" as const, id: leadId } : null;
if (activitySubject) {
await logActivity({
tenantId: page.tenantId,
@@ -247,15 +266,26 @@ export async function submitBooking(input: BookingSubmitInput): Promise<BookingS
activityType: "appointment_scheduled",
subjectType: activitySubject.type,
subjectId: activitySubject.id,
summaryText: `Termin ${page.title} am ${formatInTimeZone(startAt, input.viewerTimeZone, "dd.MM.yyyy HH:mm")} gebucht`,
metadata: { appointmentId, bookingPageId: page.pageId, leadId, kontaktId },
summaryText: "activity.runtime.booking.scheduled",
metadata: {
appointmentId,
bookingPageId: page.pageId,
bookingPageTitle: page.title,
startAt: startAt.toISOString(),
timezone: input.viewerTimeZone,
leadId,
kontaktId,
},
}).catch(() => undefined);
}
// 5) Confirmation mail + .ics (best-effort, M06 I.3).
const icsBase64 = await sendConfirmation({ input, providerUserId, startAt, endAt, appointmentId }).catch(async () => {
await db.appointment
.update({ where: { id: appointmentId }, data: { notesInternal: `Bestätigungsmail an ${input.intake.email} konnte nicht versendet werden — Endkunde bitte direkt informieren.` } })
.update({
where: { id: appointmentId },
data: { notesInternal: `Bestätigungsmail an ${input.intake.email} konnte nicht versendet werden — Endkunde bitte direkt informieren.` },
})
.catch(() => undefined);
return buildBookingIcs({ input, providerUserId, startAt, endAt, appointmentId });
});
@@ -279,8 +309,14 @@ function buildBookingIcs(args: { input: BookingSubmitInput; providerUserId: stri
return icsToBase64(ics);
}
async function sendConfirmation(args: { input: BookingSubmitInput; providerUserId: string; startAt: Date; endAt: Date; appointmentId: string }): Promise<string> {
const { input, startAt, endAt } = args;
async function sendConfirmation(args: {
input: BookingSubmitInput;
providerUserId: string;
startAt: Date;
endAt: Date;
appointmentId: string;
}): Promise<string> {
const { input, startAt } = args;
const { page } = input;
const icsBase64 = buildBookingIcs(args);
@@ -298,12 +334,31 @@ async function sendConfirmation(args: { input: BookingSubmitInput; providerUserI
};
const subject = renderTemplate(page.confirmationEmailSubject, vars);
const body = renderTemplate(page.confirmationEmailBody, vars);
const { t, locale } = await getMailTranslator(input.locale);
const rendered = renderSystemMessageEmail({
locale,
brand: { tenantName: page.tenantName },
subject,
previewText: t("booking.confirmation.previewText", { company: page.tenantName }),
eyebrow: t("booking.confirmation.eyebrow"),
title: t("booking.confirmation.title"),
intro: body,
details: [
{ label: t("booking.confirmation.fields.appointment"), value: page.title },
{ label: t("booking.confirmation.fields.date"), value: vars["appointment.date"] ?? "" },
{ label: t("booking.confirmation.fields.time"), value: t("booking.confirmation.timeValue", { time: vars["appointment.time"] ?? "" }) },
{ label: t("booking.confirmation.fields.duration"), value: t("booking.confirmation.durationValue", { minutes: page.durationMinutes }) },
{ label: t("booking.confirmation.fields.company"), value: page.tenantName },
],
notice: t("booking.confirmation.notice"),
});
await sendEmailMailjet({
data: {
to: input.intake.email.trim(),
subject,
body: body.replace(/\r?\n/gu, "<br/>"),
body: rendered.html,
text: rendered.text,
tenantId: page.tenantId,
attachments: [{ filename: "termin.ics", content: icsBase64, disposition: "attachment" }],
},
@@ -0,0 +1,91 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
db: {
availabilityRule: { findMany: vi.fn() },
availabilityException: { findMany: vi.fn() },
appointment: { findMany: vi.fn() },
calendarEvent: { findMany: vi.fn() },
},
computeSlots: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({ db: mocks.db }));
vi.mock("./slotEngine", () => ({ computeSlots: mocks.computeSlots }));
import { loadSlotsForDate } from "./SlotQueryService.server";
describe("SlotQueryService.server", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.db.availabilityRule.findMany.mockResolvedValue([]);
mocks.db.availabilityException.findMany.mockResolvedValue([]);
mocks.db.appointment.findMany.mockResolvedValue([]);
mocks.db.calendarEvent.findMany.mockResolvedValue([]);
mocks.computeSlots.mockReturnValue([]);
});
it("loads any number of providers with four bulk queries", async () => {
const startAt = new Date("2026-07-20T09:00:00.000Z");
const endAt = new Date("2026-07-20T10:00:00.000Z");
mocks.db.availabilityRule.findMany.mockResolvedValue([
{ providerUserId: "provider_2", dayOfWeek: "monday", startTime: "09:00", endTime: "17:00", timezone: "Europe/Berlin" },
]);
mocks.db.appointment.findMany.mockResolvedValue([{ providerUserId: "provider_1", startAt, endAt }]);
mocks.db.calendarEvent.findMany.mockResolvedValue([
{ userId: "provider_2", startsAt: startAt, endsAt: endAt, isBusyForAvailability: true, archivedAt: null },
]);
await loadSlotsForDate({
tenantId: "tenant_1",
providerUserIds: ["provider_1", "provider_2"],
date: "2026-07-20",
now: new Date("2026-07-10T00:00:00.000Z"),
config: {
durationMinutes: 30,
bufferBeforeMinutes: 0,
bufferAfterMinutes: 0,
slotIncrementMinutes: 15,
minNoticeHours: 4,
maxAdvanceDays: 60,
},
});
expect(mocks.db.availabilityRule.findMany).toHaveBeenCalledTimes(1);
expect(mocks.db.availabilityException.findMany).toHaveBeenCalledTimes(1);
expect(mocks.db.appointment.findMany).toHaveBeenCalledTimes(1);
expect(mocks.db.calendarEvent.findMany).toHaveBeenCalledTimes(1);
expect(mocks.db.availabilityRule.findMany).toHaveBeenCalledWith(
expect.objectContaining({ where: { tenantId: "tenant_1", providerUserId: { in: ["provider_1", "provider_2"] } } }),
);
expect(mocks.computeSlots).toHaveBeenCalledWith(
expect.objectContaining({
providers: [
expect.objectContaining({ providerUserId: "provider_1", busyIntervals: [{ from: startAt, to: endAt }] }),
expect.objectContaining({ providerUserId: "provider_2", rules: [expect.objectContaining({ dayOfWeek: "monday" })], busyIntervals: [{ from: startAt, to: endAt }] }),
],
}),
);
});
it("short-circuits without querying when no provider is configured", async () => {
await expect(
loadSlotsForDate({
tenantId: "tenant_1",
providerUserIds: [],
date: "2026-07-20",
now: new Date("2026-07-10T00:00:00.000Z"),
config: {
durationMinutes: 30,
bufferBeforeMinutes: 0,
bufferAfterMinutes: 0,
slotIncrementMinutes: 15,
minNoticeHours: 4,
maxAdvanceDays: 60,
},
}),
).resolves.toEqual([]);
expect(mocks.db.availabilityRule.findMany).not.toHaveBeenCalled();
expect(mocks.computeSlots).not.toHaveBeenCalled();
});
});
@@ -37,44 +37,68 @@ function dayWindow(date: string): { from: Date; to: Date } {
return { from: new Date(midnightUtc - DAY_MS), to: new Date(midnightUtc + 2 * DAY_MS) };
}
/** Load one provider's rules, exceptions and busy intervals for the day. */
async function loadProviderInput(tenantId: string, providerUserId: string, date: string): Promise<ProviderAvailabilityInput> {
function groupByProvider<T>(rows: readonly T[], providerId: (row: T) => string): Map<string, T[]> {
const grouped = new Map<string, T[]>();
for (const row of rows) {
const id = providerId(row);
const group = grouped.get(id);
if (group) group.push(row);
else grouped.set(id, [row]);
}
return grouped;
}
/** Load all providers' rules, exceptions and busy intervals in four queries. */
async function loadProviderInputs(tenantId: string, providerUserIds: readonly string[], date: string): Promise<ProviderAvailabilityInput[]> {
const window = dayWindow(date);
const [rules, exceptions, appointments, events] = await Promise.all([
db.availabilityRule.findMany({
where: { tenantId, providerUserId },
select: { dayOfWeek: true, startTime: true, endTime: true, timezone: true },
where: { tenantId, providerUserId: { in: [...providerUserIds] } },
select: { providerUserId: true, dayOfWeek: true, startTime: true, endTime: true, timezone: true },
}),
db.availabilityException.findMany({
where: { tenantId, providerUserId, date: new Date(`${date}T00:00:00Z`) },
select: { date: true, kind: true, startTime: true, endTime: true, timezone: true },
where: { tenantId, providerUserId: { in: [...providerUserIds] }, date: new Date(`${date}T00:00:00Z`) },
select: { providerUserId: true, date: true, kind: true, startTime: true, endTime: true, timezone: true },
}),
db.appointment.findMany({
where: { tenantId, providerUserId, status: { in: [...OCCUPYING_STATUSES] }, startAt: { gte: window.from, lte: window.to } },
select: { startAt: true, endAt: true },
where: { tenantId, providerUserId: { in: [...providerUserIds] }, status: { in: [...OCCUPYING_STATUSES] }, startAt: { gte: window.from, lte: window.to } },
select: { providerUserId: true, startAt: true, endAt: true },
}),
db.calendarEvent.findMany({
where: { tenantId, userId: providerUserId, isBusyForAvailability: true, archivedAt: null, startsAt: { gte: window.from, lte: window.to } },
select: { startsAt: true, endsAt: true, isBusyForAvailability: true, archivedAt: true },
where: { tenantId, userId: { in: [...providerUserIds] }, isBusyForAvailability: true, archivedAt: null, startsAt: { gte: window.from, lte: window.to } },
select: { userId: true, startsAt: true, endsAt: true, isBusyForAvailability: true, archivedAt: true },
}),
]);
const appointmentBusy: BusyInterval[] = appointments.map((a) => ({ from: a.startAt, to: a.endAt }));
const calendarBusy = extractBusyIntervals(events);
const rulesByProvider = groupByProvider(rules, (row) => row.providerUserId);
const exceptionsByProvider = groupByProvider(exceptions, (row) => row.providerUserId);
const appointmentsByProvider = groupByProvider(appointments, (row) => row.providerUserId);
const eventsByProvider = groupByProvider(events, (row) => row.userId);
return {
providerUserId,
rules: rules.map((r) => ({ dayOfWeek: r.dayOfWeek as BookingWeekday, startTime: r.startTime, endTime: r.endTime, timezone: r.timezone })) satisfies SlotRuleInput[],
exceptions: exceptions.map((e) => ({
date,
kind: e.kind as SlotExceptionInput["kind"],
startTime: e.startTime,
endTime: e.endTime,
timezone: e.timezone,
})) satisfies SlotExceptionInput[],
busyIntervals: [...appointmentBusy, ...calendarBusy],
};
return providerUserIds.map((providerUserId) => {
const providerAppointments = appointmentsByProvider.get(providerUserId) ?? [];
const appointmentBusy: BusyInterval[] = providerAppointments.map((appointment) => ({ from: appointment.startAt, to: appointment.endAt }));
const calendarBusy = extractBusyIntervals(eventsByProvider.get(providerUserId) ?? []);
return {
providerUserId,
rules: (rulesByProvider.get(providerUserId) ?? []).map((rule) => ({
dayOfWeek: rule.dayOfWeek as BookingWeekday,
startTime: rule.startTime,
endTime: rule.endTime,
timezone: rule.timezone,
})) satisfies SlotRuleInput[],
exceptions: (exceptionsByProvider.get(providerUserId) ?? []).map((exception) => ({
date,
kind: exception.kind as SlotExceptionInput["kind"],
startTime: exception.startTime,
endTime: exception.endTime,
timezone: exception.timezone,
})) satisfies SlotExceptionInput[],
busyIntervals: [...appointmentBusy, ...calendarBusy],
};
});
}
/** Compute the bookable slots for a booking page's providers on a given local day. */
@@ -82,6 +106,6 @@ export async function loadSlotsForDate(input: SlotQueryInput): Promise<ComputedS
if (input.providerUserIds.length === 0) {
return [];
}
const providers = await Promise.all(input.providerUserIds.map((id) => loadProviderInput(input.tenantId, id, input.date)));
const providers = await loadProviderInputs(input.tenantId, input.providerUserIds, input.date);
return computeSlots({ date: input.date, now: input.now, providers, config: input.config });
}
@@ -11,15 +11,25 @@ function readArtifact(relativePath: string): string {
describe("booking DB rollout artifacts", () => {
test("hard double-booking guard uses an idempotent exclusion constraint for active appointments", () => {
const sql = readArtifact("prisma/rls/booking-constraints.sql");
// tsrange, not tstzrange: startAt/endAt are TIMESTAMP(3) (UTC by
// convention) and the timestamp->timestamptz cast is only STABLE, which
// Postgres rejects inside index expressions (42P17).
const reviewedArtifact = readArtifact("prisma/rls/booking-constraints.sql");
const baseline = readArtifact("prisma/migrations/00000000000000_hivegrid_baseline/migration.sql");
expect(sql).toContain("CREATE EXTENSION IF NOT EXISTS btree_gist");
expect(sql).toContain("appointment_no_overlap");
expect(sql).toContain('EXCLUDE USING gist');
expect(sql).toContain('"providerUserId" WITH =');
expect(sql).toContain('tstzrange("startAt", "endAt", \'\'[)\'\') WITH &&');
expect(sql).toContain("WHERE (status IN (''scheduled'', ''held''))");
expect(sql).toContain("23P01");
expect(reviewedArtifact).toContain("CREATE EXTENSION IF NOT EXISTS btree_gist");
expect(reviewedArtifact).toContain("23P01");
expect(baseline).toContain("CREATE EXTENSION IF NOT EXISTS btree_gist");
expect(baseline).toContain("appointment_no_overlap");
expect(baseline).toContain("EXCLUDE USING gist");
// Tenant-scoped on purpose: the slot engine is tenant-scoped and demo
// tenants share provider users — a tenant-agnostic constraint leaked
// cross-tenant busy state and broke the 2026-07-17 staging rollout.
expect(baseline).toContain('"tenantId" WITH =');
expect(baseline).toContain('"providerUserId" WITH =');
expect(baseline).toContain('tsrange("startAt", "endAt", \'[)\'::text) WITH &&');
expect(baseline).not.toContain("tstzrange(");
expect(baseline).toContain("status = ANY (ARRAY['scheduled'::public.\"AppointmentStatus\", 'held'::public.\"AppointmentStatus\"])");
});
test("booking RLS artifact covers every tenant-scoped booking table and fails closed without tenant GUC", () => {
@@ -17,6 +17,7 @@ describe("booking post-booking server wiring", () => {
expect(source).toContain("appointmentId");
expect(source).toContain("data: { leadId }");
expect(source).toContain('type: "lead" as const');
expect(source).toContain('summaryText: "activity.runtime.booking.scheduled"');
});
test("public booking persists a FormSubmission when an intake form is configured", () => {
@@ -0,0 +1,78 @@
import { describe, expect, test } from "vitest";
import { buildBookingBookedWorkflowEvents, buildBookingCancelledWorkflowEvent, buildCalendarCreatedWorkflowEvent } from "./bookingAutomationEvents.server";
const START = new Date("2026-08-03T08:00:00.000Z");
const END = new Date("2026-08-03T09:00:00.000Z");
describe("booking automation workflow events", () => {
test("builds one booked and one calendar-created event from the committed booking", () => {
const events = buildBookingBookedWorkflowEvents({
tenantId: "tenant-1",
appointmentId: "appointment-1",
bookingPageId: "page-1",
bookingPageSlug: "beratung",
providerUserId: "user-1",
calendarEventId: "calendar-1",
startAt: START,
endAt: END,
kontaktId: "kontakt-1",
});
expect(events).toEqual([
expect.objectContaining({
type: "workflow.trigger.event",
dispatchKey: "workflow-trigger:booking:appointment-1:booked",
payload: expect.objectContaining({
event: "booking.appointment_booked",
data: expect.objectContaining({ appointmentId: "appointment-1", appointmentType: "beratung", providerUserId: "user-1" }),
}),
}),
expect.objectContaining({
dispatchKey: "workflow-trigger:calendar:calendar-1:created",
payload: expect.objectContaining({
event: "calendar.event_created",
data: expect.objectContaining({ calendarKey: "hauptkalender", eventKind: "termin" }),
}),
}),
]);
});
test("keeps cancellation actor and timestamp in the idempotent event", () => {
const cancelledAt = new Date("2026-08-03T07:30:00.000Z");
expect(
buildBookingCancelledWorkflowEvent({
tenantId: "tenant-1",
appointmentId: "appointment-1",
bookingPageId: "page-1",
bookingPageSlug: "wartung",
providerUserId: "user-1",
cancelledByKind: "customer",
cancellationReason: "Keine Zeit",
cancelledAt,
actorUserId: null,
})
).toMatchObject({
dispatchKey: `workflow-trigger:booking:appointment-1:cancelled:${cancelledAt.getTime()}`,
payload: { event: "booking.appointment_cancelled", data: { cancelledByKind: "customer", appointmentType: "wartung" }, userId: null },
});
});
test("builds reusable calendar-created events for non-booking sources", () => {
expect(
buildCalendarCreatedWorkflowEvent({
tenantId: "tenant-1",
calendarEventId: "calendar-2",
userId: "user-2",
calendarKey: "urlaubskalender",
eventKind: "termin",
source: "leave",
sourceEntityId: "leave-1",
startsAt: START,
endsAt: END,
})
).toMatchObject({
payload: { event: "calendar.event_created", data: { calendarKey: "urlaubskalender", source: "leave" }, userId: "user-2" },
});
});
});
@@ -0,0 +1,78 @@
import { buildWorkflowTriggerOutboxEvent } from "@hivegrid/queue";
import { buildCalendarCreatedWorkflowEvent } from "~/services/automation/automation.producer-events.server";
export { buildCalendarCreatedWorkflowEvent } from "~/services/automation/automation.producer-events.server";
export function buildBookingBookedWorkflowEvents(input: {
readonly tenantId: string;
readonly appointmentId: string;
readonly bookingPageId: string;
readonly bookingPageSlug: string;
readonly providerUserId: string;
readonly calendarEventId: string;
readonly startAt: Date;
readonly endAt: Date;
readonly kontaktId: string | null;
}) {
return [
buildWorkflowTriggerOutboxEvent({
tenantId: input.tenantId,
event: "booking.appointment_booked",
data: {
appointmentId: input.appointmentId,
bookingPageId: input.bookingPageId,
bookingPageSlug: input.bookingPageSlug,
appointmentType: input.bookingPageSlug,
terminart: input.bookingPageSlug,
providerUserId: input.providerUserId,
mitarbeiter: input.providerUserId,
startAt: input.startAt.toISOString(),
endAt: input.endAt.toISOString(),
kontaktId: input.kontaktId,
},
userId: null,
sourceId: `booking:${input.appointmentId}:booked`,
}),
buildCalendarCreatedWorkflowEvent({
tenantId: input.tenantId,
calendarEventId: input.calendarEventId,
userId: input.providerUserId,
calendarKey: "hauptkalender",
eventKind: "termin",
source: "booking",
sourceEntityId: input.appointmentId,
startsAt: input.startAt,
endsAt: input.endAt,
}),
] as const;
}
export function buildBookingCancelledWorkflowEvent(input: {
readonly tenantId: string;
readonly appointmentId: string;
readonly bookingPageId: string;
readonly bookingPageSlug: string;
readonly providerUserId: string;
readonly cancelledByKind: "customer" | "provider" | "system";
readonly cancellationReason: string;
readonly cancelledAt: Date;
readonly actorUserId: string | null;
}) {
return buildWorkflowTriggerOutboxEvent({
tenantId: input.tenantId,
event: "booking.appointment_cancelled",
data: {
appointmentId: input.appointmentId,
bookingPageId: input.bookingPageId,
bookingPageSlug: input.bookingPageSlug,
appointmentType: input.bookingPageSlug,
terminart: input.bookingPageSlug,
providerUserId: input.providerUserId,
cancelledByKind: input.cancelledByKind,
cancellationReason: input.cancellationReason,
cancelledAt: input.cancelledAt.toISOString(),
},
userId: input.actorUserId,
sourceId: `booking:${input.appointmentId}:cancelled:${input.cancelledAt.getTime()}`,
});
}
@@ -46,15 +46,25 @@ export async function getConnectionForTenant(tenantId: string, connectionId: str
}) as unknown as Promise<CalendarConnectionListRow | null>;
}
/**
* Resolve the connection a Google push channel belongs to. The webhook entrypoint
* has NO tenant context (Google calls a fixed URL), so this is a deliberate
* cross-tenant lookup by the stored subscription id; the caller then scopes every
* follow-up to the returned tenantId.
*/
export async function findConnectionByWebhookSubscription(subscriptionId: string): Promise<{ id: string; tenantId: string; userId: string } | null> {
/** Exact full-row re-read after the narrow bootstrap resolver selected context. */
export async function getGoogleWebhookConnection(input: {
tenantId: string;
userId: string;
connectionId: string;
channelId: string;
channelToken: string;
}): Promise<{ id: string; tenantId: string; userId: string } | null> {
return db.calendarConnection.findFirst({
where: { webhookSubscriptionId: subscriptionId, archivedAt: null },
where: {
id: input.connectionId,
tenantId: input.tenantId,
userId: input.userId,
provider: "google",
status: "active",
archivedAt: null,
webhookSubscriptionId: input.channelId,
AND: { id: input.channelToken },
},
select: { id: true, tenantId: true, userId: true },
});
}
@@ -10,10 +10,9 @@ import { resolveRepoPath } from "~/utils/testing/repoPaths";
const appRoot = resolveRepoPath("apps/web/app");
const mutationRoutes = [
"routes/app.$tenant/settings.integrations.calendar._index.tsx",
"routes/app.$tenant/settings.integrations.calendar.$id.tsx",
];
const CALENDAR_DETAIL_ROUTE = "routes/app.$tenant/settings/integrations/calendar.$id.tsx";
const mutationRoutes = ["routes/app.$tenant/settings/integrations/calendar._index.tsx", CALENDAR_DETAIL_ROUTE];
describe("calendar route authorization boundary", () => {
test("guards permission + CSRF before parsing the form body", () => {
@@ -33,7 +32,7 @@ describe("calendar route authorization boundary", () => {
});
test("detail route owner-checks the connection before mutating", () => {
const source = fs.readFileSync(path.join(appRoot, "routes/app.$tenant/settings.integrations.calendar.$id.tsx"), "utf8");
const source = fs.readFileSync(path.join(appRoot, CALENDAR_DETAIL_ROUTE), "utf8");
const ownerAt = source.indexOf("requireConnectionOwner(ctx, connection.userId)");
const formDataAt = source.indexOf("await request.formData()");
expect(ownerAt).toBeGreaterThanOrEqual(0);
@@ -9,11 +9,11 @@
// block the connect.
import { decryptTenantField, encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
import { getRlsExecutionContext } from "@hivegrid/db/rls-context.server";
import { db } from "~/utils/db.server";
import { googleCalendarAdapter, CalendarNotConfiguredError } from "./adapters/GoogleCalendarAdapter.server";
import type { CalendarCreds } from "./adapters/CalendarAdapter";
import { signCalendarOAuthState, verifyCalendarOAuthState } from "./oauthState.server";
import { GOOGLE_OAUTH_CALLBACK_PATH } from "../routes/calendarRoutePaths";
export class CalendarConnectError extends Error {
readonly code: "not_configured" | "invalid_state" | "exchange_failed";
@@ -45,6 +45,10 @@ export async function completeOAuthCallback(input: { code: string; state: string
throw new CalendarConnectError("invalid_state");
}
const { tenantId, userId, tenantSlug } = verified.payload;
const rlsContext = getRlsExecutionContext();
if (rlsContext?.tenantId !== tenantId || rlsContext.userId !== userId) {
throw new CalendarConnectError("invalid_state");
}
let exchange: Awaited<ReturnType<typeof googleCalendarAdapter.exchangeCode>>;
try {
@@ -0,0 +1,253 @@
import { describe, expect, it } from "vitest";
import type { ChatChannelDetailVM, ChatFeatureMessageVM, ChatMessageVM, ChatPinnedMessagesVM, ChatThreadVM } from "@hivegrid/view-models";
import {
beginChatFeatureMutation,
chatFeatureErrorsByMessageId,
failedChatFeatureMutationForMessage,
overlayChatChannelFeatureMutations,
overlayChatPinnedFeatureMutations,
overlayChatThreadFeatureMutations,
reconcileChatChannelFeatureMutations,
reconcileChatPinnedFeatureMutations,
retryChatFeatureMutation,
settleChatFeatureMutation,
type ChatOptimisticFeatureMutationInput,
} from "./ChatFeatureOptimistic";
const reactionMutation: ChatOptimisticFeatureMutationInput = {
kind: "reaction",
requestId: "request_reaction",
messageId: "message_1",
emoji: "👍",
active: true,
actorLabel: "Raffael",
startedAtIso: "2026-07-16T09:00:00.000Z",
};
const pinMutation: ChatOptimisticFeatureMutationInput = {
kind: "pin",
requestId: "request_pin",
messageId: "message_1",
pinned: false,
actorLabel: "Raffael",
startedAtIso: "2026-07-16T09:00:00.000Z",
};
describe("chat feature optimistic overlays", () => {
it("sets a reaction immediately and never doubles the count when the authoritative echo arrives", () => {
const pending = beginChatFeatureMutation([], reactionMutation);
const optimistic = overlayChatChannelFeatureMutations(channelVM(message()), pending);
expect(readyChannelMessage(optimistic).reactions).toEqual([
{ emoji: "👍", count: 1, reactedByViewer: true, reactorLabels: ["Raffael"] },
]);
const confirmed = settleChatFeatureMutation(pending, reactionMutation.requestId, { ok: true, errorKey: null });
const echoed = channelVM(
message({ reactions: [{ emoji: "👍", count: 1, reactedByViewer: true, reactorLabels: ["Raffael"] }] })
);
expect(readyChannelMessage(overlayChatChannelFeatureMutations(echoed, confirmed)).reactions[0]?.count).toBe(1);
expect(reconcileChatChannelFeatureMutations(confirmed, echoed)).toEqual([]);
});
it("rolls a rejected reaction back, keeps an element-local error, and retries the same request id", () => {
const pending = beginChatFeatureMutation([], reactionMutation);
const failed = settleChatFeatureMutation(pending, reactionMutation.requestId, {
ok: false,
errorKey: "chat.errors.invalidInput",
});
expect(readyChannelMessage(overlayChatChannelFeatureMutations(channelVM(message()), failed)).reactions).toEqual([]);
expect(chatFeatureErrorsByMessageId(failed)).toEqual({ message_1: "chat.errors.invalidInput" });
expect(failedChatFeatureMutationForMessage(failed, "message_1")?.requestId).toBe("request_reaction");
expect(retryChatFeatureMutation(failed, "request_reaction")).toMatchObject([
{ requestId: "request_reaction", status: "pending", errorKey: null },
]);
});
it("removes a pin optimistically and restores it after an error", () => {
const canonical = channelVM(message({ pin: { pinnedAtIso: "2026-07-16T08:00:00.000Z", pinnedByLabel: "Ada", note: null } }));
const pending = beginChatFeatureMutation([], pinMutation);
expect(readyChannelMessage(overlayChatChannelFeatureMutations(canonical, pending)).pin).toBeNull();
const failed = settleChatFeatureMutation(pending, pinMutation.requestId, { ok: false, errorKey: "chat.errors.pinLimitReached" });
expect(readyChannelMessage(overlayChatChannelFeatureMutations(canonical, failed)).pin).not.toBeNull();
});
it("hides a pinned row until the loader echo confirms it without duplicating state", () => {
const canonical = pinnedVM([featureMessage({ pinned: true })]);
const pending = beginChatFeatureMutation([], pinMutation);
expect(readyPinnedRows(overlayChatPinnedFeatureMutations(canonical, pending))).toHaveLength(0);
const failed = settleChatFeatureMutation(pending, pinMutation.requestId, { ok: false, errorKey: "chat.errors.invalidInput" });
expect(readyPinnedRows(overlayChatPinnedFeatureMutations(canonical, failed))).toHaveLength(1);
const confirmed = settleChatFeatureMutation(pending, pinMutation.requestId, { ok: true, errorKey: null });
const authoritative = pinnedVM([]);
expect(reconcileChatPinnedFeatureMutations(confirmed, authoritative)).toEqual([]);
});
it("applies the same set-semantics reaction overlay in a thread", () => {
const pending = beginChatFeatureMutation([], reactionMutation);
const overlaid = overlayChatThreadFeatureMutations(threadVM(featureMessage()), pending);
expect(overlaid.status === "ready" ? overlaid.data.parent.reactions : []).toEqual([
{ emoji: "👍", count: 1, reactedByViewer: true },
]);
});
});
function message(overrides: Partial<ChatMessageVM> = {}): ChatMessageVM {
return {
id: "message_1",
clientMessageId: "client_1",
source: "persisted",
deliveryState: "sent",
deliveryStateKey: "chat.message.delivery.sent",
failureReasonKey: null,
retryable: false,
author: {
userId: "user_1",
displayName: "Raffael",
avatar: { imageUrl: null, fallbackLabel: "R" },
isCurrentUser: true,
},
bodyMarkdown: "Hello",
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: "2026-07-16T08:00:00.000Z",
updatedAtIso: "2026-07-16T08:00:00.000Z",
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: { readCount: 0, recipientCount: 0, readerUserIds: [], readerLabels: [], labelKey: "chat.message.read.none" },
pin: null,
actions: { canReact: true, canReply: true, canEdit: false, canDelete: false, canPin: true, canMarkAsTask: false },
tombstoneKey: null,
...overrides,
};
}
function channelVM(item: ChatMessageVM): ChatChannelDetailVM {
return {
status: "ready",
data: {
header: {
id: "chat_1",
kind: "group",
title: "Team",
subtitle: null,
avatar: { imageUrl: null, fallbackLabel: "T" },
project: null,
memberCount: 2,
isPrivate: false,
isArchived: false,
isAuditMode: false,
dmAuditBannerKey: null,
canManage: false,
settingsHref: null,
pinnedHref: "/demo/chat/chat_1/pinned",
searchHref: "/demo/chat/search",
},
messages: [item],
messageGroups: [{ dateIso: "2026-07-16", messages: [item] }],
presence: [],
typingLabels: [],
pinnedMessages: item.pin
? [{ messageId: item.id, authorLabel: "Raffael", snippet: "Hello", pinnedAtIso: item.pin.pinnedAtIso, pinnedByLabel: item.pin.pinnedByLabel, href: "#message-message_1" }]
: [],
history: { olderCursor: null, hasOlder: false },
composer: {
enabled: true,
disabledReasonKey: null,
canSend: true,
canAttachFiles: false,
canRecordVoice: false,
canMention: false,
canMarkAsTask: false,
draftStorageKey: "draft",
maxBodyLength: 10_000,
placeholderKey: "chat.composer.placeholder",
},
connection: { state: "online", stateLabelKey: "chat.connection.online", reconnectAttempt: 0, retryAtIso: null, canRetry: false },
emptyHeadlineKey: "chat.empty.headline",
emptyBodyKey: "chat.empty.body",
loadOlderLabelKey: "chat.message.loadOlder",
newMessagesLabelKey: "chat.message.newMessages",
},
};
}
function featureMessage(overrides: Partial<ChatFeatureMessageVM> = {}): ChatFeatureMessageVM {
return {
id: "message_1",
authorLabel: "Raffael",
authorAvatarUrl: null,
bodyMarkdown: "Hello",
createdAtIso: "2026-07-16T08:00:00.000Z",
deleted: false,
mentions: [],
attachments: [],
reactions: [],
pinned: false,
canReact: true,
canPin: true,
canEdit: true,
canDelete: true,
...overrides,
};
}
function threadVM(parent: ChatFeatureMessageVM): ChatThreadVM {
return {
status: "ready",
data: {
chatId: "chat_1",
threadId: parent.id,
channelTitle: "Team",
backHref: "/demo/chat/chat_1",
parent,
replies: [],
replyCount: 0,
canReply: true,
composerPlaceholderKey: "chat.thread.composerPlaceholder",
emptyRepliesHeadlineKey: "chat.thread.empty.headline",
emptyRepliesBodyKey: "chat.thread.empty.body",
},
};
}
function pinnedVM(messages: readonly ChatFeatureMessageVM[]): ChatPinnedMessagesVM {
return {
status: "ready",
data: {
chatId: "chat_1",
channelTitle: "Team",
backHref: "/demo/chat/chat_1",
rows: messages.map((item) => ({
message: item,
pinnedAtIso: "2026-07-16T08:00:00.000Z",
pinnedByLabel: "Raffael",
note: null,
messageHref: "/demo/chat/chat_1#message-message_1",
canUnpin: true,
})),
emptyHeadlineKey: "chat.pinned.empty.headline",
emptyBodyKey: "chat.pinned.empty.body",
},
};
}
function readyChannelMessage(vm: ChatChannelDetailVM): ChatMessageVM {
if (vm.status !== "ready") throw new Error("expected ready channel VM");
return vm.data.messages[0]!;
}
function readyPinnedRows(vm: ChatPinnedMessagesVM) {
if (vm.status !== "ready") throw new Error("expected ready pinned VM");
return vm.data.rows;
}
@@ -0,0 +1,270 @@
import type { ChatChannelDetailVM, ChatFeatureMessageVM, ChatMessageVM, ChatPinnedMessagesVM, ChatThreadVM } from "@hivegrid/view-models";
type FeatureMutationStatus = "pending" | "confirmed" | "failed";
const MAX_OPTIMISTIC_FEATURE_MUTATIONS = 100;
type FeatureMutationBase = {
readonly requestId: string;
readonly messageId: string;
readonly actorLabel: string;
readonly startedAtIso: string;
readonly status: FeatureMutationStatus;
readonly errorKey: string | null;
};
export type ChatOptimisticFeatureMutation =
| (FeatureMutationBase & {
readonly kind: "reaction";
readonly emoji: string;
readonly active: boolean;
})
| (FeatureMutationBase & {
readonly kind: "pin";
readonly pinned: boolean;
});
export type ChatOptimisticFeatureMutationInput =
| Omit<Extract<ChatOptimisticFeatureMutation, { kind: "reaction" }>, "status" | "errorKey">
| Omit<Extract<ChatOptimisticFeatureMutation, { kind: "pin" }>, "status" | "errorKey">;
export type ChatOptimisticFeatureState = readonly ChatOptimisticFeatureMutation[];
export function beginChatFeatureMutation(
state: ChatOptimisticFeatureState,
mutation: ChatOptimisticFeatureMutationInput
): ChatOptimisticFeatureState {
const next: ChatOptimisticFeatureMutation = { ...mutation, status: "pending", errorKey: null };
return [...state.filter((candidate) => candidate.requestId !== mutation.requestId && !sameFeature(candidate, next)), next].slice(
-MAX_OPTIMISTIC_FEATURE_MUTATIONS
);
}
export function settleChatFeatureMutation(
state: ChatOptimisticFeatureState,
requestId: string,
result: { readonly ok: boolean; readonly errorKey: string | null }
): ChatOptimisticFeatureState {
const status: FeatureMutationStatus = result.ok ? "confirmed" : "failed";
const errorKey = result.ok ? null : (result.errorKey ?? "chat.errors.invalidInput");
let changed = false;
const next = state.map<ChatOptimisticFeatureMutation>((mutation) => {
if (mutation.requestId !== requestId || (mutation.status === status && mutation.errorKey === errorKey)) return mutation;
changed = true;
return { ...mutation, status, errorKey };
});
return changed ? next : state;
}
export function retryChatFeatureMutation(
state: ChatOptimisticFeatureState,
requestId: string
): ChatOptimisticFeatureState {
return state.map<ChatOptimisticFeatureMutation>((mutation) =>
mutation.requestId === requestId ? { ...mutation, status: "pending", errorKey: null } : mutation
);
}
export function failedChatFeatureMutationForMessage(
state: ChatOptimisticFeatureState,
messageId: string
): ChatOptimisticFeatureMutation | null {
return [...state].reverse().find((mutation) => mutation.messageId === messageId && mutation.status === "failed") ?? null;
}
export function chatFeatureErrorsByMessageId(state: ChatOptimisticFeatureState): Readonly<Record<string, string>> {
const errors: Record<string, string> = {};
for (const mutation of state) {
if (mutation.status === "failed" && mutation.errorKey) errors[mutation.messageId] = mutation.errorKey;
}
return errors;
}
export function overlayChatChannelFeatureMutations(
vm: ChatChannelDetailVM,
state: ChatOptimisticFeatureState
): ChatChannelDetailVM {
if (vm.status !== "ready") return vm;
const overlayById = new Map(vm.data.messages.map((message) => [message.id, overlayChannelMessage(message, state)]));
return {
...vm,
data: {
...vm.data,
messages: vm.data.messages.map((message) => overlayById.get(message.id) ?? message),
messageGroups: vm.data.messageGroups.map((group) => ({
...group,
messages: group.messages.map((message) => overlayById.get(message.id) ?? message),
})),
pinnedMessages: vm.data.pinnedMessages.filter((row) => !isOptimisticallyUnpinned(state, row.messageId)),
},
};
}
export function overlayChatThreadFeatureMutations(vm: ChatThreadVM, state: ChatOptimisticFeatureState): ChatThreadVM {
if (vm.status !== "ready") return vm;
return {
...vm,
data: {
...vm.data,
parent: overlayFeatureMessage(vm.data.parent, state),
replies: vm.data.replies.map((message) => overlayFeatureMessage(message, state)),
},
};
}
export function overlayChatPinnedFeatureMutations(
vm: ChatPinnedMessagesVM,
state: ChatOptimisticFeatureState
): ChatPinnedMessagesVM {
if (vm.status !== "ready") return vm;
return {
...vm,
data: {
...vm.data,
rows: vm.data.rows.filter((row) => !isOptimisticallyUnpinned(state, row.message.id)),
},
};
}
export function reconcileChatChannelFeatureMutations(
state: ChatOptimisticFeatureState,
vm: ChatChannelDetailVM
): ChatOptimisticFeatureState {
if (vm.status !== "ready") return state;
const byId = new Map(vm.data.messages.map((message) => [message.id, message]));
return reconcileConfirmed(state, (mutation) => authoritativeChannelStateMatches(byId.get(mutation.messageId), mutation));
}
export function reconcileChatThreadFeatureMutations(
state: ChatOptimisticFeatureState,
vm: ChatThreadVM
): ChatOptimisticFeatureState {
if (vm.status !== "ready") return state;
const messages = [vm.data.parent, ...vm.data.replies];
const byId = new Map(messages.map((message) => [message.id, message]));
return reconcileConfirmed(state, (mutation) => authoritativeFeatureStateMatches(byId.get(mutation.messageId), mutation));
}
export function reconcileChatPinnedFeatureMutations(
state: ChatOptimisticFeatureState,
vm: ChatPinnedMessagesVM
): ChatOptimisticFeatureState {
if (vm.status !== "ready") return state;
const pinnedIds = new Set(vm.data.rows.map((row) => row.message.id));
return reconcileConfirmed(state, (mutation) => mutation.kind === "pin" && pinnedIds.has(mutation.messageId) === mutation.pinned);
}
function overlayChannelMessage(message: ChatMessageVM, state: ChatOptimisticFeatureState): ChatMessageVM {
let next = message;
for (const mutation of activeMutations(state, message.id)) {
if (mutation.kind === "reaction") {
next = { ...next, reactions: overlayReactions(next.reactions, mutation) };
} else {
next = {
...next,
pin: mutation.pinned
? { pinnedAtIso: mutation.startedAtIso, pinnedByLabel: mutation.actorLabel, note: null }
: null,
};
}
}
return next;
}
function overlayFeatureMessage(message: ChatFeatureMessageVM, state: ChatOptimisticFeatureState): ChatFeatureMessageVM {
let next = message;
for (const mutation of activeMutations(state, message.id)) {
if (mutation.kind === "reaction") {
next = {
...next,
reactions: overlayReactions(
next.reactions.map((reaction) => ({ ...reaction, reactorLabels: [] })),
mutation
).map(({ emoji, count, reactedByViewer }) => ({ emoji, count, reactedByViewer })),
};
} else {
next = { ...next, pinned: mutation.pinned };
}
}
return next;
}
type OverlayReaction = {
readonly emoji: string;
readonly count: number;
readonly reactedByViewer: boolean;
readonly reactorLabels: readonly string[];
};
function overlayReactions(
reactions: readonly OverlayReaction[],
mutation: Extract<ChatOptimisticFeatureMutation, { kind: "reaction" }>
): readonly OverlayReaction[] {
const current = reactions.find((reaction) => reaction.emoji === mutation.emoji);
if (current?.reactedByViewer === mutation.active || (!current && !mutation.active)) return reactions;
if (!current) {
return [
...reactions,
{
emoji: mutation.emoji,
count: 1,
reactedByViewer: true,
reactorLabels: [mutation.actorLabel],
},
];
}
const nextCount = current.count + (mutation.active ? 1 : -1);
if (nextCount <= 0) return reactions.filter((reaction) => reaction.emoji !== mutation.emoji);
const reactorLabels = mutation.active
? [...current.reactorLabels, mutation.actorLabel]
: removeFirst(current.reactorLabels, mutation.actorLabel);
return reactions.map((reaction) =>
reaction.emoji === mutation.emoji
? { ...reaction, count: nextCount, reactedByViewer: mutation.active, reactorLabels }
: reaction
);
}
function activeMutations(state: ChatOptimisticFeatureState, messageId: string): readonly ChatOptimisticFeatureMutation[] {
return state.filter((mutation) => mutation.messageId === messageId && mutation.status !== "failed");
}
function isOptimisticallyUnpinned(state: ChatOptimisticFeatureState, messageId: string): boolean {
return activeMutations(state, messageId).some((mutation) => mutation.kind === "pin" && !mutation.pinned);
}
function reconcileConfirmed(
state: ChatOptimisticFeatureState,
matches: (mutation: ChatOptimisticFeatureMutation) => boolean
): ChatOptimisticFeatureState {
const next = state.filter((mutation) => mutation.status !== "confirmed" || !matches(mutation));
return next.length === state.length ? state : next;
}
function authoritativeChannelStateMatches(
message: ChatMessageVM | undefined,
mutation: ChatOptimisticFeatureMutation
): boolean {
if (!message) return false;
if (mutation.kind === "pin") return (message.pin !== null) === mutation.pinned;
return (message.reactions.find((reaction) => reaction.emoji === mutation.emoji)?.reactedByViewer ?? false) === mutation.active;
}
function authoritativeFeatureStateMatches(
message: ChatFeatureMessageVM | undefined,
mutation: ChatOptimisticFeatureMutation
): boolean {
if (!message) return false;
if (mutation.kind === "pin") return message.pinned === mutation.pinned;
return (message.reactions.find((reaction) => reaction.emoji === mutation.emoji)?.reactedByViewer ?? false) === mutation.active;
}
function sameFeature(left: ChatOptimisticFeatureMutation, right: ChatOptimisticFeatureMutation): boolean {
if (left.messageId !== right.messageId || left.kind !== right.kind) return false;
return left.kind === "pin" || (right.kind === "reaction" && left.emoji === right.emoji);
}
function removeFirst(values: readonly string[], value: string): readonly string[] {
const index = values.indexOf(value);
if (index < 0) return values;
return [...values.slice(0, index), ...values.slice(index + 1)];
}
@@ -0,0 +1,99 @@
import { buildChatChannelDetailVM, type ChatResolvedAuthorVM } from "@hivegrid/view-models";
import { describe, expect, it } from "vitest";
import { overlayChatAttachmentSendAttempt, type ChatAttachmentSendAttempt } from "./chatAttachmentOptimistic";
const currentUser: ChatResolvedAuthorVM = {
userId: "user_1",
displayName: "Raffael",
avatar: { imageUrl: null, fallbackLabel: "RS" },
isCurrentUser: true,
};
function vm() {
return buildChatChannelDetailVM({
header: {
id: "chat_1",
kind: "group",
title: "Team",
subtitle: null,
avatar: { imageUrl: null, fallbackLabel: "T" },
project: null,
memberCount: 3,
isPrivate: true,
isArchived: false,
isAuditMode: false,
canManage: false,
settingsHref: null,
pinnedHref: null,
searchHref: "/demo/chat/search",
},
messages: [],
pinnedMessages: [],
typingLabels: [],
history: { hasOlder: false, olderCursor: null },
composer: {
disabledReasonKey: null,
canSend: true,
canAttachFiles: true,
canRecordVoice: true,
canMention: true,
canMarkAsTask: true,
draftStorageKey: "chat:draft:chat_1",
maxBodyLength: 4_000,
},
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
});
}
function attempt(deliveryState: "sending" | "failed", errorKey: string | null): ChatAttachmentSendAttempt {
return {
payloadKey: "payload",
requestId: "request_stable",
clientMessageId: "client_stable",
fileIds: ["file_1"],
body: "Montagefoto",
attachments: [
{
clientId: "upload_1",
fileId: "file_1",
fileName: "camera.jpg",
mimeType: "image/jpeg",
sizeBytes: 1024,
kind: "image",
status: "ready",
progress: 100,
errorKey: null,
durationSeconds: null,
},
],
createdAtIso: "2026-07-16T08:00:00.000Z",
deliveryState,
errorKey,
};
}
describe("attachment optimistic message overlay", () => {
it("shows a local sending echo with the stable client id and attachment metadata", () => {
const result = overlayChatAttachmentSendAttempt(vm(), attempt("sending", null), currentUser);
expect(result.status).toBe("ready");
if (result.status !== "ready") return;
expect(result.data.messages[0]).toMatchObject({
id: "local:client_stable",
clientMessageId: "client_stable",
source: "local_echo",
deliveryState: "sending",
attachments: [{ fileId: "file_1", fileName: "camera.jpg" }],
});
});
it("keeps a failed send element-local and retryable without changing its identity", () => {
const result = overlayChatAttachmentSendAttempt(vm(), attempt("failed", "chat.errors.invalidInput"), currentUser);
expect(result.status === "ready" ? result.data.messages[0] : null).toMatchObject({
clientMessageId: "client_stable",
deliveryState: "failed",
retryable: true,
failureReasonKey: "chat.errors.invalidInput",
});
});
});
@@ -0,0 +1,93 @@
import { chatMessageIdentityKey, groupChatMessagesByDay, type ChatChannelDetailVM, type ChatMessageVM, type ChatResolvedAuthorVM } from "@hivegrid/view-models";
import type { ChatPendingAttachment } from "./useChatAttachmentUploads";
export type ChatAttachmentSendAttempt = {
readonly payloadKey: string;
readonly requestId: string;
readonly clientMessageId: string;
readonly fileIds: readonly string[];
readonly body: string;
readonly attachments: readonly ChatPendingAttachment[];
readonly createdAtIso: string;
readonly deliveryState: "sending" | "failed";
readonly errorKey: string | null;
};
export function overlayChatAttachmentSendAttempt(
vm: ChatChannelDetailVM,
attempt: ChatAttachmentSendAttempt | null,
currentUser: ChatResolvedAuthorVM
): ChatChannelDetailVM {
if (vm.status !== "ready" || attempt === null) return vm;
const recipientCount = Math.max(0, vm.data.header.memberCount - 1);
const localMessage: ChatMessageVM = {
id: `local:${attempt.clientMessageId}`,
clientMessageId: attempt.clientMessageId,
source: "local_echo",
deliveryState: attempt.deliveryState,
deliveryStateKey: attempt.deliveryState === "sending" ? "chat.message.delivery.sending" : "chat.message.delivery.failed",
failureReasonKey: attempt.errorKey,
retryable: attempt.deliveryState === "failed",
author: currentUser,
bodyMarkdown: attempt.body || null,
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: attempt.createdAtIso,
updatedAtIso: attempt.createdAtIso,
editedAtIso: null,
deletedAtIso: null,
tombstoneKey: null,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: attempt.attachments.flatMap((attachment) =>
attachment.fileId
? [
{
id: `${attempt.clientMessageId}:${attachment.fileId}`,
fileId: attachment.fileId,
kind: attachment.kind,
fileName: attachment.fileName,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
downloadHref: "#pending-chat-attachment",
previewHref: null,
altText: attachment.kind === "image" ? attachment.fileName : null,
durationSeconds: attachment.durationSeconds,
scanStatus: "clean" as const,
},
]
: []
),
linkPreviews: [],
readAggregate: {
readCount: 0,
recipientCount,
readerUserIds: [],
readerLabels: [],
labelKey: "chat.message.read.aggregate",
},
pin: null,
actions: {
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
},
};
const byKey = new Map(vm.data.messages.map((message) => [chatMessageIdentityKey(message), message]));
byKey.set(chatMessageIdentityKey(localMessage), localMessage);
const messages = [...byKey.values()].sort((left, right) => left.createdAtIso.localeCompare(right.createdAtIso));
return {
...vm,
data: {
...vm.data,
messages,
messageGroups: groupChatMessagesByDay(messages),
},
};
}
@@ -0,0 +1,310 @@
import { CHAT_EVENT_NAMES, type ChatLocalEcho, type ChatMessageCreatedEvent, type ChatRealtimeMessage, type ChatThreadReplyEvent } from "@hivegrid/realtime";
import type { ChatResolvedAuthorVM } from "@hivegrid/view-models";
import { describe, expect, it } from "vitest";
import {
candidateFromChatEvent,
candidateFromLocalEcho,
chatChannelRealtimeReducer,
createChatRealtimeScopeKey,
createInitialChatChannelRealtimeState,
filterHydratedChatCandidates,
safeResolveChatAuthor,
type ChatCandidateMapping,
} from "./chatChannelRealtimeReducer";
const viewer: ChatResolvedAuthorVM = {
userId: "user_viewer",
displayName: "Raffael",
avatar: { imageUrl: null, fallbackLabel: "R" },
isCurrentUser: true,
};
const scopeKey = createChatRealtimeScopeKey("tenant_1", "chat_1");
function message(overrides: Partial<ChatRealtimeMessage> = {}): ChatRealtimeMessage {
return {
id: "message_1",
clientMessageId: "client_1",
authorUserId: "user_unknown",
body: "Hallo",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [{ type: "user", id: "user_viewer", label: null }],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-15T08:00:00.000Z",
updatedAt: "2026-07-15T08:00:00.000Z",
editedAt: null,
deletedAt: null,
...overrides,
};
}
function mapping(overrides: Partial<ChatCandidateMapping> = {}): ChatCandidateMapping {
return {
currentUser: viewer,
unknownAuthorLabel: "Unbekannt",
resolveAuthor: () => undefined,
...overrides,
};
}
describe("chatChannelRealtimeReducer", () => {
it("maps an event with an unknown or failing author projection without throwing", () => {
const event: ChatMessageCreatedEvent = {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "stream_1:1",
requestId: "request_1",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:00:00.000Z",
data: { message: message() },
};
const candidate = candidateFromChatEvent(
event,
mapping({
resolveAuthor: () => {
throw new Error("stale author cache");
},
messageActions: () => {
throw new Error("stale permission projection");
},
})
);
expect(candidate?.author).toMatchObject({ userId: "user_unknown", displayName: "Unbekannt", isCurrentUser: false });
expect(candidate?.mentions).toEqual([{ kind: "user", id: "user_viewer", label: "user_viewer", href: null }]);
expect(candidate?.actions).toEqual({
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
});
});
it("reconciles local echo lifecycle by author-scoped client id", () => {
const echo: ChatLocalEcho = {
chatId: "chat_1",
requestId: "request_1",
clientMessageId: "client_local",
body: "Optimistisch",
mentions: [],
status: "sending",
failureI18nKey: null,
retryable: false,
attempts: 1,
createdAtMs: Date.parse("2026-07-15T08:00:00.000Z"),
canonicalMessage: null,
};
const sending = candidateFromLocalEcho(echo, mapping());
let state = chatChannelRealtimeReducer(createInitialChatChannelRealtimeState(scopeKey), {
type: "upsert_candidate",
scopeKey,
candidate: sending,
});
expect(state.candidates).toHaveLength(1);
expect(state.candidates[0]?.deliveryState).toBe("sending");
const failed = candidateFromLocalEcho({ ...echo, status: "failed", failureI18nKey: "chat.errors.realtimeUnavailable", retryable: true }, mapping());
state = chatChannelRealtimeReducer(state, { type: "upsert_candidate", scopeKey, candidate: failed });
expect(state.candidates).toHaveLength(1);
expect(state.candidates[0]).toMatchObject({ deliveryState: "failed", failureReasonKey: "chat.errors.realtimeUnavailable" });
const acknowledged = candidateFromLocalEcho(
{ ...echo, status: "sent", canonicalMessage: message({ authorUserId: viewer.userId, clientMessageId: echo.clientMessageId }) },
mapping()
);
state = chatChannelRealtimeReducer(state, { type: "upsert_candidate", scopeKey, candidate: acknowledged });
expect(state.candidates[0]).toMatchObject({ id: "message_1", source: "http_ack", deliveryState: "sent" });
state = chatChannelRealtimeReducer(state, {
type: "remove_candidate",
scopeKey,
authorUserId: viewer.userId,
clientMessageId: echo.clientMessageId,
});
expect(state.candidates).toEqual([]);
});
it("deduplicates typing labels and safely falls back for the current user", () => {
const author = safeResolveChatAuthor(viewer.userId, mapping({ unknownAuthorLabel: "Unbekannt" }));
expect(author).toBe(viewer);
const state = chatChannelRealtimeReducer(createInitialChatChannelRealtimeState(scopeKey), {
type: "typing",
scopeKey,
labels: ["Ada", "Ada", "Grace"],
});
expect(state.typingLabels).toEqual(["Ada", "Grace"]);
});
it("lets the richer loader projection replace a hydrated realtime candidate", () => {
const event: ChatMessageCreatedEvent = {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "stream_1:1",
requestId: "request_1",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:00:00.000Z",
data: { message: message() },
};
const realtime = candidateFromChatEvent(event, mapping());
if (!realtime) throw new Error("fixture must map to a candidate");
if (!realtime.author) throw new Error("fixture must carry a markdown author");
const hydrated = {
...realtime,
source: "persisted" as const,
author: { ...realtime.author, displayName: "Grace Hopper" },
};
expect(filterHydratedChatCandidates([hydrated], [realtime])).toEqual([]);
expect(filterHydratedChatCandidates([], [realtime])).toEqual([realtime]);
});
it("drops stale-scope actions after a tenant or channel switch", () => {
const candidate = candidateFromLocalEcho(
{
chatId: "chat_1",
requestId: "request_old",
clientMessageId: "client_old",
body: "Alt",
mentions: [],
status: "sending",
failureI18nKey: null,
retryable: false,
attempts: 1,
createdAtMs: Date.parse("2026-07-15T08:00:00.000Z"),
canonicalMessage: null,
},
mapping()
);
const nextScopeKey = createChatRealtimeScopeKey("tenant_2", "chat_1");
let state = chatChannelRealtimeReducer(createInitialChatChannelRealtimeState(scopeKey), {
type: "upsert_candidate",
scopeKey,
candidate,
});
state = chatChannelRealtimeReducer(state, { type: "reset", scopeKey: nextScopeKey });
state = chatChannelRealtimeReducer(state, { type: "upsert_candidate", scopeKey, candidate });
state = chatChannelRealtimeReducer(state, {
type: "connection",
scopeKey,
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
});
expect(state).toEqual(createInitialChatChannelRealtimeState(nextScopeKey));
});
it("never projects thread replies into the top-level channel timeline", () => {
const event: ChatThreadReplyEvent = {
event: CHAT_EVENT_NAMES.threadReply,
cursor: "stream_1:2",
requestId: "request_reply",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:01:00.000Z",
data: {
thread: {
id: "thread_1",
parentMessageId: "message_parent",
replyCount: 1,
lastReplyAt: "2026-07-15T08:01:00.000Z",
participantUserIds: ["user_unknown"],
},
message: message({ id: "message_reply", parentMessageId: "message_parent" }),
},
};
expect(candidateFromChatEvent(event, mapping())).toBeNull();
});
it("projects actorless system events without fake author or user-message affordances", () => {
const event: ChatMessageCreatedEvent = {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "stream_1:4",
requestId: "request_system",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:03:00.000Z",
data: {
message: {
id: "system_message_1",
clientMessageId: "system:member-write:user_1:false",
authorUserId: null,
body: "stored fallback copy",
bodyFormat: "system",
systemEvent: {
kind: "member_write_access_changed",
metadata: { memberName: "Nora Weber", canWrite: false },
},
parentMessageId: null,
mentions: [],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-15T08:03:00.000Z",
updatedAt: "2026-07-15T08:03:00.000Z",
editedAt: null,
deletedAt: null,
},
},
};
const candidate = candidateFromChatEvent(event, mapping());
expect(candidate).toMatchObject({
author: null,
bodyMarkdown: null,
bodyFormat: "system",
readAggregate: null,
systemEvent: {
kind: "member_write_access_changed",
labelKey: "chat.systemEvent.memberWriteAccessRevoked",
values: { member: "Nora Weber" },
},
actions: { canReact: false, canReply: false, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: false },
});
});
it("strips mentions, previews and actions from deleted realtime candidates", () => {
const event: ChatMessageCreatedEvent = {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "stream_1:3",
requestId: "request_deleted",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:02:00.000Z",
data: {
message: message({
deletedAt: "2026-07-15T08:02:00.000Z",
linkPreviews: [
{
url: "https://example.test",
title: "Vorschau",
description: null,
imageUrl: null,
siteName: "Example",
},
],
}),
},
};
const candidate = candidateFromChatEvent(
event,
mapping({
messageActions: () => ({
canReact: true,
canReply: true,
canEdit: true,
canDelete: true,
canPin: true,
canMarkAsTask: true,
}),
})
);
expect(candidate).toMatchObject({ bodyMarkdown: null, mentions: [], linkPreviews: [], actions: expect.objectContaining({ canReact: false }) });
});
});
@@ -0,0 +1,307 @@
import { CHAT_EVENT_NAMES, type ChatLocalEcho, type ChatRealtimeMessage, type ChatRemotePresence, type ChatServerEvent } from "@hivegrid/realtime";
import {
buildChatSystemEventVM,
chatMessageIdentityKey,
type ChatMessageActionsVM,
type ChatMessageCandidate,
type ChatResolvedAuthorVM,
type ChatResolvedMentionVM,
} from "@hivegrid/view-models";
const MAX_OVERLAY_MESSAGES = 500;
const MAX_READ_RECEIPT_OVERLAYS = 500;
const NO_MESSAGE_ACTIONS: ChatMessageActionsVM = Object.freeze({
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
});
export type ChatRealtimeConnection = {
readonly state: "connecting" | "online" | "reconnecting" | "offline" | "blocked";
readonly reconnectAttempt: number;
readonly retryAtIso: string | null;
};
export type ChatChannelRealtimeState = {
readonly scopeKey: string | null;
readonly connection: ChatRealtimeConnection;
readonly candidates: readonly ChatMessageCandidate[];
readonly readReceipts: readonly ChatReadReceiptOverlay[];
readonly typingLabels: readonly string[];
readonly presence: readonly ChatRemotePresence[];
};
export type ChatReadReceiptOverlay = {
readonly messageId: string;
readonly userId: string;
};
export type ChatChannelRealtimeAction =
| { readonly type: "reset"; readonly scopeKey: string }
| { readonly type: "connection"; readonly scopeKey: string; readonly connection: ChatRealtimeConnection }
| { readonly type: "upsert_candidate"; readonly scopeKey: string; readonly candidate: ChatMessageCandidate }
| { readonly type: "remove_candidate"; readonly scopeKey: string; readonly authorUserId: string; readonly clientMessageId: string }
| { readonly type: "read_receipt"; readonly scopeKey: string; readonly receipt: ChatReadReceiptOverlay }
| { readonly type: "typing"; readonly scopeKey: string; readonly labels: readonly string[] }
| { readonly type: "presence"; readonly scopeKey: string; readonly entries: readonly ChatRemotePresence[] };
export type ChatCandidateMapping = {
readonly currentUser: ChatResolvedAuthorVM;
readonly unknownAuthorLabel: string;
readonly resolveAuthor: (userId: string) => ChatResolvedAuthorVM | null | undefined;
readonly messageActions?: (message: ChatRealtimeMessage) => ChatMessageActionsVM;
};
export function createChatRealtimeScopeKey(tenantSlug: string, chatId: string): string {
return `${tenantSlug}\u0000${chatId}`;
}
export function createInitialChatChannelRealtimeState(scopeKey: string | null = null): ChatChannelRealtimeState {
return {
scopeKey,
connection: { state: "offline", reconnectAttempt: 0, retryAtIso: null },
candidates: [],
readReceipts: [],
typingLabels: [],
presence: [],
};
}
export function chatChannelRealtimeReducer(state: ChatChannelRealtimeState, action: ChatChannelRealtimeAction): ChatChannelRealtimeState {
if (action.type !== "reset" && state.scopeKey !== action.scopeKey) return state;
switch (action.type) {
case "reset":
return createInitialChatChannelRealtimeState(action.scopeKey);
case "connection":
return { ...state, connection: action.connection };
case "upsert_candidate":
return { ...state, candidates: upsertCandidate(state.candidates, action.candidate) };
case "remove_candidate":
return {
...state,
candidates: state.candidates.filter(
(candidate) => candidate.author?.userId !== action.authorUserId || candidate.clientMessageId !== action.clientMessageId
),
};
case "read_receipt":
return { ...state, readReceipts: upsertReadReceipt(state.readReceipts, action.receipt) };
case "typing":
return { ...state, typingLabels: [...new Set(action.labels)] };
case "presence":
return { ...state, presence: action.entries.map((entry) => ({ ...entry })) };
}
}
/** Maps only top-level message events. All other persistent mutations are
* hydrated by the loader revalidation triggered by the hook. */
export function candidateFromChatEvent(event: ChatServerEvent, mapping: ChatCandidateMapping): ChatMessageCandidate | null {
if (event.event !== CHAT_EVENT_NAMES.messageCreated || event.data.message.parentMessageId !== null) return null;
return candidateFromRealtimeMessage(event.data.message, "websocket", "sent", null, mapping);
}
export function candidateFromLocalEcho(echo: ChatLocalEcho, mapping: ChatCandidateMapping): ChatMessageCandidate {
if (echo.canonicalMessage) {
return candidateFromRealtimeMessage(echo.canonicalMessage, "http_ack", "sent", null, mapping);
}
const timestamp = new Date(echo.createdAtMs).toISOString();
return {
id: `local:${echo.clientMessageId}`,
clientMessageId: echo.clientMessageId,
source: "local_echo",
deliveryState: echo.status,
failureReasonKey: echo.failureI18nKey,
retryable: echo.retryable,
author: mapping.currentUser,
bodyMarkdown: echo.body,
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: timestamp,
updatedAtIso: timestamp,
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: echo.mentions.map(resolveMention),
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: emptyReadAggregate(),
pin: null,
actions: NO_MESSAGE_ACTIONS,
};
}
export function safeResolveChatAuthor(userId: string, mapping: ChatCandidateMapping): ChatResolvedAuthorVM {
if (userId === mapping.currentUser.userId) return mapping.currentUser;
try {
const resolved = mapping.resolveAuthor(userId);
if (resolved) return resolved;
} catch {
// A stale author projection must not break the realtime stream.
}
const label = mapping.unknownAuthorLabel.trim() || userId;
return {
userId,
displayName: label,
avatar: { imageUrl: null, fallbackLabel: label.slice(0, 1).toUpperCase() || "?" },
isCurrentUser: userId === mapping.currentUser.userId,
};
}
/** Once the loader has hydrated a message, its richer author, attachment,
* permission and read projections replace the transport-only candidate. */
export function filterHydratedChatCandidates(
loaderMessages: readonly ChatMessageCandidate[],
realtimeCandidates: readonly ChatMessageCandidate[]
): readonly ChatMessageCandidate[] {
const hydratedKeys = new Set(loaderMessages.map(chatMessageCandidateKey));
return realtimeCandidates.filter((candidate) => !hydratedKeys.has(chatMessageCandidateKey(candidate)));
}
function candidateFromRealtimeMessage(
message: ChatRealtimeMessage,
source: "websocket" | "http_ack",
deliveryState: "sent",
failureReasonKey: null,
mapping: ChatCandidateMapping
): ChatMessageCandidate {
if (message.bodyFormat === "system") {
return {
id: message.id,
clientMessageId: message.clientMessageId,
source,
deliveryState,
failureReasonKey,
author: null,
bodyMarkdown: null,
bodyFormat: "system",
systemEvent: buildChatSystemEventVM(message.systemEvent.kind, message.systemEvent.metadata),
createdAtIso: message.createdAt,
updatedAtIso: message.updatedAt,
editedAtIso: message.editedAt,
deletedAtIso: message.deletedAt,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: null,
pin: null,
actions: NO_MESSAGE_ACTIONS,
};
}
const isDeleted = message.deletedAt !== null;
let actions = NO_MESSAGE_ACTIONS;
if (!isDeleted) {
try {
actions = mapping.messageActions?.(message) ?? NO_MESSAGE_ACTIONS;
} catch {
// Permission projections can become stale; safe read-only actions win.
}
}
return {
id: message.id,
clientMessageId: message.clientMessageId,
source,
deliveryState,
failureReasonKey,
author: safeResolveChatAuthor(message.authorUserId, mapping),
bodyMarkdown: isDeleted ? null : message.body,
bodyFormat: message.bodyFormat,
systemEvent: null,
createdAtIso: message.createdAt,
updatedAtIso: message.updatedAt,
editedAtIso: message.editedAt,
deletedAtIso: message.deletedAt,
parentMessageId: message.parentMessageId,
mentions: isDeleted ? [] : message.mentions.map(resolveMention),
reactions: [],
thread: null,
// Realtime frames intentionally contain only attachment ids. The loader
// resolves scan state, names and download URLs after revalidation.
attachments: [],
linkPreviews: isDeleted ? [] : message.linkPreviews.map((preview) => ({ ...preview })),
readAggregate: emptyReadAggregate(),
pin: null,
actions,
};
}
function resolveMention(mention: { readonly type: ChatResolvedMentionVM["kind"]; readonly id: string; readonly label: string | null }): ChatResolvedMentionVM {
return {
kind: mention.type,
id: mention.id,
label: mention.label?.trim() || mention.id,
href: null,
};
}
function emptyReadAggregate() {
return {
readCount: 0,
recipientCount: 0,
readerUserIds: [],
readerLabels: [],
labelKey: "chat.message.read.none",
} as const;
}
export function overlayChatReadReceipts(
candidates: readonly ChatMessageCandidate[],
receipts: readonly ChatReadReceiptOverlay[],
mapping: ChatCandidateMapping
): readonly ChatMessageCandidate[] {
if (receipts.length === 0) return candidates;
const receiptsByMessage = new Map<string, Set<string>>();
for (const receipt of receipts) {
const readers = receiptsByMessage.get(receipt.messageId) ?? new Set<string>();
readers.add(receipt.userId);
receiptsByMessage.set(receipt.messageId, readers);
}
return candidates.map((candidate) => {
if (candidate.author === null || candidate.readAggregate === null) return candidate;
const readAggregate = candidate.readAggregate;
const liveReaders = receiptsByMessage.get(candidate.id);
if (!liveReaders) return candidate;
const labelsByUserId = new Map(readAggregate.readerUserIds.map((userId, index) => [userId, readAggregate.readerLabels[index]!]));
for (const userId of liveReaders) {
if (userId === candidate.author.userId || labelsByUserId.has(userId)) continue;
labelsByUserId.set(userId, safeResolveChatAuthor(userId, mapping).displayName);
}
const readers = [...labelsByUserId.entries()].slice(0, readAggregate.recipientCount);
return {
...candidate,
readAggregate: {
...readAggregate,
readCount: readers.length,
readerUserIds: readers.map(([userId]) => userId),
readerLabels: readers.map(([, label]) => label),
labelKey: readers.length > 0 ? "chat.message.read.aggregate" : readAggregate.labelKey,
},
};
});
}
function upsertReadReceipt(receipts: readonly ChatReadReceiptOverlay[], receipt: ChatReadReceiptOverlay): readonly ChatReadReceiptOverlay[] {
const withoutDuplicate = receipts.filter((candidate) => candidate.messageId !== receipt.messageId || candidate.userId !== receipt.userId);
return [...withoutDuplicate, receipt].slice(-MAX_READ_RECEIPT_OVERLAYS);
}
function upsertCandidate(candidates: readonly ChatMessageCandidate[], candidate: ChatMessageCandidate): readonly ChatMessageCandidate[] {
const candidateKey = chatMessageIdentityKey(candidate);
const index = candidates.findIndex((existing) => chatMessageIdentityKey(existing) === candidateKey);
if (index < 0) return [...candidates, candidate].slice(-MAX_OVERLAY_MESSAGES);
const next = [...candidates];
next[index] = candidate;
return next;
}
function chatMessageCandidateKey(candidate: ChatMessageCandidate): string {
return chatMessageIdentityKey(candidate);
}
@@ -0,0 +1,278 @@
import { describe, expect, it, vi } from "vitest";
import {
createChatReadReceiptBatcher,
createChatTypingController,
type ChatInteractionScheduler,
type ChatVisibilitySource,
} from "./chatInteractionControllers";
class FakeScheduler implements ChatInteractionScheduler {
private nextHandle = 1;
private now = 0;
private readonly timers = new Map<number, { at: number; callback: () => void }>();
setTimeout(callback: () => void, delayMs: number): number {
const handle = this.nextHandle++;
this.timers.set(handle, { at: this.now + delayMs, callback });
return handle;
}
clearTimeout(handle: unknown): void {
if (typeof handle === "number") this.timers.delete(handle);
}
advanceBy(delayMs: number): void {
const target = this.now + delayMs;
while (true) {
const next = [...this.timers.entries()]
.filter(([, timer]) => timer.at <= target)
.sort((left, right) => left[1].at - right[1].at || left[0] - right[0])[0];
if (!next) break;
this.timers.delete(next[0]);
this.now = next[1].at;
next[1].callback();
}
this.now = target;
}
}
class FakeVisibility implements ChatVisibilitySource {
visibilityState: DocumentVisibilityState = "visible";
private readonly listeners = new Set<() => void>();
addEventListener(_type: "visibilitychange", listener: () => void): void {
this.listeners.add(listener);
}
removeEventListener(_type: "visibilitychange", listener: () => void): void {
this.listeners.delete(listener);
}
set(next: DocumentVisibilityState): void {
this.visibilityState = next;
for (const listener of this.listeners) listener();
}
}
describe("chat interaction controllers", () => {
it("debounces typing start and emits stop after inactivity or disposal", () => {
const scheduler = new FakeScheduler();
const send = vi.fn(() => true);
const controller = createChatTypingController({ chatId: "chat_1", send, scheduler, startDelayMs: 250, idleStopMs: 1_500, refreshMs: 3_000 });
controller.update("H");
scheduler.advanceBy(249);
expect(send).not.toHaveBeenCalled();
scheduler.advanceBy(1);
expect(send).toHaveBeenLastCalledWith("chat_1", "started");
scheduler.advanceBy(1_000);
controller.update("Hallo");
scheduler.advanceBy(1_499);
expect(send).toHaveBeenCalledTimes(1);
scheduler.advanceBy(1);
expect(send).toHaveBeenLastCalledWith("chat_1", "stopped");
controller.update("Noch einmal");
scheduler.advanceBy(250);
controller.dispose();
expect(send).toHaveBeenLastCalledWith("chat_1", "stopped");
});
it("never sends a receipt for visibility shorter than one foreground second", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_short", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(999);
batcher.endVisible("chat_1", "message_short");
scheduler.advanceBy(5_000);
expect(send).not.toHaveBeenCalled();
batcher.dispose();
});
it("restarts the continuous visibility window after the document was hidden", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_1", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(500);
visibility.set("hidden");
scheduler.advanceBy(5_000);
expect(send).not.toHaveBeenCalled();
visibility.set("visible");
scheduler.advanceBy(999);
expect(send).not.toHaveBeenCalled();
scheduler.advanceBy(1);
batcher.endVisible("chat_1", "message_1");
scheduler.advanceBy(1_999);
expect(send).not.toHaveBeenCalled();
scheduler.advanceBy(1);
expect(send).toHaveBeenCalledWith("chat_1", "message_1");
batcher.dispose();
});
it("holds qualified receipts while hidden and resumes the two-second cadence", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_pending", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(1_000);
visibility.set("hidden");
scheduler.advanceBy(10_000);
expect(send).not.toHaveBeenCalled();
visibility.set("visible");
scheduler.advanceBy(1_999);
expect(send).not.toHaveBeenCalled();
scheduler.advanceBy(1);
expect(send).toHaveBeenCalledWith("chat_1", "message_pending");
batcher.dispose();
});
it("keeps every qualified receipt and flushes out-of-order callbacks monotonically", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_z", "2026-07-15T08:05:00.000Z");
batcher.beginVisible("chat_1", "message_old", "2026-07-15T08:04:59.000Z");
batcher.beginVisible("chat_1", "message_a", "2026-07-15T08:05:00.000Z");
scheduler.advanceBy(1_000);
batcher.endVisible("chat_1", "message_z");
batcher.endVisible("chat_1", "message_old");
batcher.endVisible("chat_1", "message_a");
scheduler.advanceBy(2_000);
expect(send.mock.calls).toEqual([
["chat_1", "message_old"],
["chat_1", "message_a"],
["chat_1", "message_z"],
]);
batcher.acknowledge("chat_1", "message_old");
batcher.acknowledge("chat_1", "message_a");
batcher.acknowledge("chat_1", "message_z");
batcher.beginVisible("chat_1", "message_old", "2026-07-15T08:04:59.000Z");
scheduler.advanceBy(5_000);
expect(send).toHaveBeenCalledTimes(3);
batcher.dispose();
});
it("retains a failed exact receipt and does not overtake it within the same channel", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi
.fn()
.mockReturnValueOnce({ requestId: "request_1", sent: false })
.mockReturnValueOnce({ requestId: "request_2", sent: true })
.mockReturnValueOnce({ requestId: "request_1", sent: true })
.mockReturnValueOnce({ requestId: "request_4", sent: true });
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_1", "2026-07-15T08:00:00.000Z");
batcher.beginVisible("chat_1", "message_2", "2026-07-15T08:01:00.000Z");
batcher.beginVisible("chat_2", "message_3", "2026-07-15T08:02:00.000Z");
scheduler.advanceBy(3_000);
expect(send.mock.calls).toEqual([
["chat_1", "message_1"],
["chat_2", "message_3"],
]);
scheduler.advanceBy(2_000);
expect(send.mock.calls).toEqual([
["chat_1", "message_1"],
["chat_2", "message_3"],
["chat_1", "message_1", "request_1"],
["chat_1", "message_2"],
]);
batcher.acknowledge("chat_1", "message_1");
batcher.acknowledge("chat_1", "message_2");
batcher.acknowledge("chat_2", "message_3");
batcher.dispose();
});
it("sends at most fifty exact receipts per flush", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
const base = Date.parse("2026-07-15T08:00:00.000Z");
for (let index = 54; index >= 0; index -= 1) {
batcher.beginVisible("chat_1", `message_${String(index).padStart(2, "0")}`, new Date(base + index).toISOString());
}
scheduler.advanceBy(3_000);
expect(send).toHaveBeenCalledTimes(50);
expect(send.mock.calls[0]).toEqual(["chat_1", "message_00"]);
expect(send.mock.calls[49]).toEqual(["chat_1", "message_49"]);
for (let index = 0; index < 50; index += 1) {
batcher.acknowledge("chat_1", `message_${String(index).padStart(2, "0")}`);
}
scheduler.advanceBy(2_000);
expect(send).toHaveBeenCalledTimes(55);
expect(send.mock.calls[54]).toEqual(["chat_1", "message_54"]);
batcher.dispose();
});
it("retries an unacknowledged receipt with the same request id after reconnect and stops only on acknowledgement", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn((_chatId: string, _messageId: string, requestId?: string) => ({ requestId: requestId ?? "request_stable", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_1", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(3_000);
expect(send).toHaveBeenCalledOnce();
expect(send).toHaveBeenLastCalledWith("chat_1", "message_1");
expect(batcher.retryPending()).toBe(1);
expect(send).toHaveBeenLastCalledWith("chat_1", "message_1", "request_stable");
batcher.acknowledge("chat_1", "message_1");
expect(batcher.retryPending()).toBe(0);
scheduler.advanceBy(20_000);
expect(send).toHaveBeenCalledTimes(2);
batcher.dispose();
});
it("retries an unacknowledged receipt with the same request id after the acknowledgement timeout", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn((_chatId: string, _messageId: string, requestId?: string) => ({ requestId: requestId ?? "request_timeout", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler, acknowledgementTimeoutMs: 3_000 });
batcher.beginVisible("chat_1", "message_1", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(3_000);
expect(send).toHaveBeenCalledOnce();
scheduler.advanceBy(4_999);
expect(send).toHaveBeenCalledOnce();
scheduler.advanceBy(1);
expect(send).toHaveBeenLastCalledWith("chat_1", "message_1", "request_timeout");
batcher.dispose();
});
it("flushes qualified receipts once when leaving the channel", () => {
const scheduler = new FakeScheduler();
const visibility = new FakeVisibility();
const send = vi.fn(() => ({ requestId: "request_read", sent: true }));
const batcher = createChatReadReceiptBatcher({ send, visibility, scheduler });
batcher.beginVisible("chat_1", "message_1", "2026-07-15T08:00:00.000Z");
scheduler.advanceBy(1_000);
visibility.set("hidden");
batcher.dispose();
expect(send).toHaveBeenCalledOnce();
expect(send).toHaveBeenCalledWith("chat_1", "message_1");
});
});
@@ -0,0 +1,349 @@
import type { ChatReadResult } from "@hivegrid/realtime";
export type ChatInteractionScheduler = {
setTimeout(callback: () => void, delayMs: number): unknown;
clearTimeout(handle: unknown): void;
};
export type ChatVisibilitySource = {
readonly visibilityState: DocumentVisibilityState;
addEventListener(type: "visibilitychange", listener: () => void): void;
removeEventListener(type: "visibilitychange", listener: () => void): void;
};
export type ChatTypingController = {
update(body: string): void;
stop(): void;
dispose(): void;
};
export type ChatReadReceiptBatcher = {
beginVisible(chatId: string, messageId: string, createdAtIso: string): void;
endVisible(chatId: string, messageId: string): void;
acknowledge(chatId: string, messageId: string): void;
retryPending(): number;
flush(): number;
dispose(): void;
};
const globalScheduler: ChatInteractionScheduler = {
setTimeout: (callback, delayMs) => globalThis.setTimeout(callback, delayMs),
clearTimeout: (handle) => globalThis.clearTimeout(handle as ReturnType<typeof globalThis.setTimeout>),
};
export function createChatTypingController(input: {
readonly chatId: string;
readonly send: (chatId: string, status: "started" | "stopped") => boolean;
readonly scheduler?: ChatInteractionScheduler;
readonly startDelayMs?: number;
readonly idleStopMs?: number;
readonly refreshMs?: number;
}): ChatTypingController {
const scheduler = input.scheduler ?? globalScheduler;
const startDelayMs = positiveDelay(input.startDelayMs, 250);
const idleStopMs = positiveDelay(input.idleStopMs, 1_500);
const refreshMs = positiveDelay(input.refreshMs, 3_000);
let startTimer: unknown;
let stopTimer: unknown;
let refreshTimer: unknown;
let activeBody = false;
let started = false;
let disposed = false;
const clearTimer = (kind: "start" | "stop" | "refresh") => {
const handle = kind === "start" ? startTimer : kind === "stop" ? stopTimer : refreshTimer;
if (handle !== undefined) scheduler.clearTimeout(handle);
if (kind === "start") startTimer = undefined;
else if (kind === "stop") stopTimer = undefined;
else refreshTimer = undefined;
};
const scheduleRefresh = () => {
clearTimer("refresh");
if (!started || !activeBody || disposed) return;
refreshTimer = scheduler.setTimeout(() => {
refreshTimer = undefined;
if (!started || !activeBody || disposed) return;
input.send(input.chatId, "started");
scheduleRefresh();
}, refreshMs);
};
const signalStarted = () => {
startTimer = undefined;
if (!activeBody || started || disposed) return;
started = input.send(input.chatId, "started");
if (started) scheduleRefresh();
};
const stop = () => {
activeBody = false;
clearTimer("start");
clearTimer("stop");
clearTimer("refresh");
if (!started) return;
started = false;
input.send(input.chatId, "stopped");
};
return {
update(body) {
if (disposed) return;
activeBody = body.trim().length > 0;
if (!activeBody) {
stop();
return;
}
if (!started && startTimer === undefined) {
startTimer = scheduler.setTimeout(signalStarted, startDelayMs);
}
clearTimer("stop");
stopTimer = scheduler.setTimeout(stop, idleStopMs);
},
stop,
dispose() {
if (disposed) return;
stop();
disposed = true;
},
};
}
/** Qualifies exact message receipts after continuous foreground visibility and
* delivers them in monotonic channel order. */
export function createChatReadReceiptBatcher(input: {
readonly send: (chatId: string, messageId: string, requestId?: string) => ChatReadResult;
readonly visibility: ChatVisibilitySource;
readonly scheduler?: ChatInteractionScheduler;
readonly minimumVisibleMs?: number;
readonly flushIntervalMs?: number;
readonly acknowledgementTimeoutMs?: number;
readonly maxPerFlush?: number;
}): ChatReadReceiptBatcher {
const scheduler = input.scheduler ?? globalScheduler;
const minimumVisibleMs = positiveDelay(input.minimumVisibleMs, 1_000);
const flushIntervalMs = positiveDelay(input.flushIntervalMs, 2_000);
const acknowledgementTimeoutMs = positiveDelay(input.acknowledgementTimeoutMs, 10_000);
const maxPerFlush = positiveInteger(input.maxPerFlush, 50);
const visibilityEntries = new Map<string, ChatMessageVisibilityEntry>();
const pending = new Map<string, ChatPendingRead>();
const completed = new Set<string>();
let flushTimer: unknown;
let disposed = false;
const clearFlushTimer = () => {
if (flushTimer !== undefined) scheduler.clearTimeout(flushTimer);
flushTimer = undefined;
};
const clearAcknowledgementTimer = (receipt: ChatPendingRead) => {
if (receipt.acknowledgementTimer !== undefined) scheduler.clearTimeout(receipt.acknowledgementTimer);
receipt.acknowledgementTimer = undefined;
};
const scheduleAcknowledgementTimeout = (key: string, receipt: ChatPendingRead) => {
clearAcknowledgementTimer(receipt);
receipt.acknowledgementTimer = scheduler.setTimeout(() => {
receipt.acknowledgementTimer = undefined;
if (disposed || pending.get(key) !== receipt) return;
receipt.inFlight = false;
scheduleFlush();
}, acknowledgementTimeoutMs);
};
const flushPending = (allowHidden = false, scheduleNext = true): number => {
clearFlushTimer();
if (disposed || (!allowHidden && input.visibility.visibilityState !== "visible")) return 0;
const blockedChats = new Set<string>();
const ordered = [...pending.entries()].sort((left, right) => comparePendingRead(left[1], right[1]));
let sent = 0;
let attempted = 0;
for (const [key, receipt] of ordered) {
if (attempted >= maxPerFlush) break;
if (blockedChats.has(receipt.chatId)) continue;
if (receipt.inFlight) {
blockedChats.add(receipt.chatId);
continue;
}
attempted += 1;
const result = receipt.requestId
? input.send(receipt.chatId, receipt.messageId, receipt.requestId)
: input.send(receipt.chatId, receipt.messageId);
receipt.requestId = result.requestId;
if (!result.sent) {
blockedChats.add(receipt.chatId);
continue;
}
receipt.inFlight = true;
scheduleAcknowledgementTimeout(key, receipt);
sent += 1;
}
if (scheduleNext) scheduleFlush();
return sent;
};
const flush = (): number => flushPending();
const scheduleFlush = () => {
if (disposed || flushTimer !== undefined || input.visibility.visibilityState !== "visible" || !hasFlushCandidate(pending)) return;
flushTimer = scheduler.setTimeout(flush, flushIntervalMs);
};
const clearQualificationTimer = (entry: ChatMessageVisibilityEntry) => {
if (entry.qualificationTimer !== undefined) scheduler.clearTimeout(entry.qualificationTimer);
entry.qualificationTimer = undefined;
};
const scheduleQualification = (key: string, entry: ChatMessageVisibilityEntry) => {
if (disposed || !entry.intersecting || entry.qualificationTimer !== undefined || input.visibility.visibilityState !== "visible") return;
entry.qualificationTimer = scheduler.setTimeout(() => {
entry.qualificationTimer = undefined;
if (disposed || !entry.intersecting || input.visibility.visibilityState !== "visible") return;
visibilityEntries.delete(key);
if (!completed.has(key) && !pending.has(key)) {
pending.set(key, {
chatId: entry.chatId,
messageId: entry.messageId,
createdAtIso: entry.createdAtIso,
requestId: null,
inFlight: false,
acknowledgementTimer: undefined,
});
scheduleFlush();
}
}, minimumVisibleMs);
};
const onVisibilityChange = () => {
if (input.visibility.visibilityState === "visible") {
for (const [key, entry] of visibilityEntries) scheduleQualification(key, entry);
scheduleFlush();
return;
}
clearFlushTimer();
for (const entry of visibilityEntries.values()) clearQualificationTimer(entry);
};
input.visibility.addEventListener("visibilitychange", onVisibilityChange);
return {
beginVisible(chatId, messageId, createdAtIso) {
if (disposed) return;
const key = readKey(chatId, messageId);
if (completed.has(key) || pending.has(key)) return;
const existing = visibilityEntries.get(key);
if (existing) {
existing.intersecting = true;
existing.createdAtIso = createdAtIso;
scheduleQualification(key, existing);
return;
}
const entry: ChatMessageVisibilityEntry = {
chatId,
messageId,
createdAtIso,
intersecting: true,
qualificationTimer: undefined,
};
visibilityEntries.set(key, entry);
scheduleQualification(key, entry);
},
endVisible(chatId, messageId) {
if (disposed) return;
const key = readKey(chatId, messageId);
const entry = visibilityEntries.get(key);
if (!entry) return;
entry.intersecting = false;
clearQualificationTimer(entry);
visibilityEntries.delete(key);
},
acknowledge(chatId, messageId) {
if (disposed) return;
const key = readKey(chatId, messageId);
const entry = visibilityEntries.get(key);
if (entry) clearQualificationTimer(entry);
visibilityEntries.delete(key);
const receipt = pending.get(key);
if (receipt) clearAcknowledgementTimer(receipt);
pending.delete(key);
completed.add(key);
scheduleFlush();
},
retryPending() {
if (disposed) return 0;
for (const receipt of pending.values()) {
clearAcknowledgementTimer(receipt);
receipt.inFlight = false;
}
return flushPending();
},
flush,
dispose() {
if (disposed) return;
clearFlushTimer();
for (const entry of visibilityEntries.values()) clearQualificationTimer(entry);
// The channel teardown still has a live socket, so qualified receipts
// get one final best-effort batch even when the document is hidden.
for (const receipt of pending.values()) {
clearAcknowledgementTimer(receipt);
receipt.inFlight = false;
}
flushPending(true, false);
for (const receipt of pending.values()) clearAcknowledgementTimer(receipt);
disposed = true;
visibilityEntries.clear();
pending.clear();
completed.clear();
input.visibility.removeEventListener("visibilitychange", onVisibilityChange);
},
};
}
type ChatMessageVisibilityEntry = {
readonly chatId: string;
readonly messageId: string;
createdAtIso: string;
intersecting: boolean;
qualificationTimer: unknown;
};
type ChatPendingRead = {
readonly chatId: string;
readonly messageId: string;
readonly createdAtIso: string;
requestId: string | null;
inFlight: boolean;
acknowledgementTimer: unknown;
};
function comparePendingRead(left: ChatPendingRead, right: ChatPendingRead): number {
if (left.chatId < right.chatId) return -1;
if (left.chatId > right.chatId) return 1;
if (left.createdAtIso < right.createdAtIso) return -1;
if (left.createdAtIso > right.createdAtIso) return 1;
if (left.messageId < right.messageId) return -1;
if (left.messageId > right.messageId) return 1;
return 0;
}
function hasFlushCandidate(pending: ReadonlyMap<string, ChatPendingRead>): boolean {
const blockedChats = new Set<string>();
const ordered = [...pending.values()].sort(comparePendingRead);
for (const receipt of ordered) {
if (blockedChats.has(receipt.chatId)) continue;
if (!receipt.inFlight) return true;
blockedChats.add(receipt.chatId);
}
return false;
}
function readKey(chatId: string, messageId: string): string {
return `${chatId}\u0000${messageId}`;
}
function positiveDelay(value: number | undefined, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
}
function positiveInteger(value: number | undefined, fallback: number): number {
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : fallback;
}
@@ -0,0 +1,109 @@
import { describe, expect, it } from "vitest";
import type { ChatChannelDetailVM, ChatMessageVM } from "@hivegrid/view-models";
import {
beginChatMessageMutation,
overlayChatMessageMutations,
reconcileChatMessageMutations,
retryChatMessageMutation,
settleChatMessageMutation,
} from "./chatMessageMutationOptimistic";
const message = {
id: "message_1",
clientMessageId: "client_1",
source: "persisted",
deliveryState: "sent",
deliveryStateKey: "chat.message.sent",
failureReasonKey: null,
retryable: false,
author: { userId: "user_1", displayName: "Raffael", avatar: { imageUrl: null, fallbackLabel: "R" }, isCurrentUser: true },
bodyMarkdown: "Alt",
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: "2026-07-16T01:00:00.000Z",
updatedAtIso: "2026-07-16T01:00:00.000Z",
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: [],
reactions: [{ emoji: "👍", count: 1, reactedByViewer: true, reactorLabels: ["Raffael"] }],
thread: null,
attachments: [{ id: "a", fileId: "f", kind: "file", fileName: "a.pdf", mimeType: "application/pdf", sizeBytes: 1, downloadHref: "/f", previewHref: null, altText: null, durationSeconds: null, scanStatus: "clean" }],
linkPreviews: [],
readAggregate: null,
pin: { pinnedAtIso: "2026-07-16T01:00:00.000Z", pinnedByLabel: "Raffael", note: null },
actions: { canReact: true, canReply: true, canEdit: true, canDelete: true, canPin: true, canMarkAsTask: true },
tombstoneKey: null,
} satisfies ChatMessageVM;
function vm(currentMessage: ChatMessageVM = message): ChatChannelDetailVM {
return {
status: "ready",
data: {
header: { id: "chat_1", kind: "group", title: "Büro", subtitle: null, avatar: { imageUrl: null, fallbackLabel: "B" }, project: null, memberCount: 1, isPrivate: true, isArchived: false, isAuditMode: false, dmAuditBannerKey: null, canManage: false, settingsHref: null, pinnedHref: null, searchHref: "/chat" },
messages: [currentMessage],
messageGroups: [{ dateIso: "2026-07-16", messages: [currentMessage] }],
presence: [],
typingLabels: [],
pinnedMessages: [{ messageId: "message_1", authorLabel: "Raffael", snippet: "Alt", pinnedAtIso: "2026-07-16T01:00:00.000Z", pinnedByLabel: "Raffael", href: "#message-1" }],
history: { olderCursor: null, hasOlder: false },
composer: { enabled: true, disabledReasonKey: null, canSend: true, canAttachFiles: false, canRecordVoice: false, canMention: true, canMarkAsTask: false, draftStorageKey: "draft", maxBodyLength: 8000, placeholderKey: "chat.composer.placeholder" },
connection: { state: "online", stateLabelKey: "chat.connection.online", reconnectAttempt: 0, retryAtIso: null, canRetry: false },
emptyHeadlineKey: "chat.empty.title",
emptyBodyKey: "chat.empty.body",
loadOlderLabelKey: "chat.loadOlder",
newMessagesLabelKey: "chat.newMessages",
},
};
}
describe("optimistic chat message mutations", () => {
it("preserves the state reference when reconciliation has nothing to remove", () => {
const current = [] as const;
expect(reconcileChatMessageMutations(current, vm())).toBe(current);
});
it("overlays an edit and rolls it back when the request fails", () => {
const pending = beginChatMessageMutation([], {
kind: "edit_message",
requestId: "request_1",
messageId: "message_1",
startedAtIso: "2026-07-16T02:00:00.000Z",
bodyMarkdown: "Neu",
mentions: [],
});
expect(overlayChatMessageMutations(vm(), pending).data.messages[0]?.bodyMarkdown).toBe("Neu");
const failed = settleChatMessageMutation(pending, { ok: false, requestId: "request_1", errorKey: "chat.errors.invalidInput" });
expect(overlayChatMessageMutations(vm(), failed).data.messages[0]?.bodyMarkdown).toBe("Alt");
expect(retryChatMessageMutation(failed, "request_1")[0]).toMatchObject({ requestId: "request_1", state: "pending" });
});
it("tombstones optimistically and removes attachments, reactions and pins", () => {
const pending = beginChatMessageMutation([], {
kind: "delete_message",
requestId: "request_delete",
messageId: "message_1",
startedAtIso: "2026-07-16T02:00:00.000Z",
});
const overlaid = overlayChatMessageMutations(vm(), pending);
expect(overlaid.data.messages[0]).toMatchObject({ bodyMarkdown: null, tombstoneKey: "chat.message.deleted", attachments: [], reactions: [], pin: null });
expect(overlaid.data.pinnedMessages).toEqual([]);
});
it("drops a confirmed overlay once the authoritative echo is hydrated", () => {
const confirmed = settleChatMessageMutation(
beginChatMessageMutation([], {
kind: "edit_message",
requestId: "request_1",
messageId: "message_1",
startedAtIso: "2026-07-16T02:00:00.000Z",
bodyMarkdown: "Neu",
mentions: [],
}),
{ ok: true, requestId: "request_1", errorKey: null }
);
expect(reconcileChatMessageMutations(confirmed, vm({ ...message, bodyMarkdown: "Neu", editedAtIso: "2026-07-16T02:00:00.000Z" }))).toEqual([]);
});
});
@@ -0,0 +1,194 @@
import type { ChatChannelDetailVM, ChatFeatureMessageVM, ChatMessageVM, ChatResolvedMentionVM, ChatThreadVM } from "@hivegrid/view-models";
export type ChatMessageMutationState = "pending" | "confirmed" | "failed";
type ChatMessageMutationBase = Readonly<{
requestId: string;
messageId: string;
startedAtIso: string;
state: ChatMessageMutationState;
errorKey: string | null;
}>;
export type ChatOptimisticMessageMutation =
| (ChatMessageMutationBase &
Readonly<{
kind: "edit_message";
bodyMarkdown: string;
mentions: readonly ChatResolvedMentionVM[];
}>)
| (ChatMessageMutationBase & Readonly<{ kind: "delete_message" }>);
export type ChatOptimisticMessageMutationInput =
| Omit<Extract<ChatOptimisticMessageMutation, { kind: "edit_message" }>, "state" | "errorKey">
| Omit<Extract<ChatOptimisticMessageMutation, { kind: "delete_message" }>, "state" | "errorKey">;
export type ChatMessageMutationResponse = Readonly<{
ok: boolean;
requestId: string;
errorKey: string | null;
}>;
export function beginChatMessageMutation(
current: readonly ChatOptimisticMessageMutation[],
input: ChatOptimisticMessageMutationInput
): readonly ChatOptimisticMessageMutation[] {
return [
...current.filter((mutation) => mutation.messageId !== input.messageId),
{ ...input, state: "pending", errorKey: null } as ChatOptimisticMessageMutation,
];
}
export function settleChatMessageMutation(
current: readonly ChatOptimisticMessageMutation[],
response: ChatMessageMutationResponse
): readonly ChatOptimisticMessageMutation[] {
return current.map((mutation) =>
mutation.requestId === response.requestId
? { ...mutation, state: response.ok ? "confirmed" : "failed", errorKey: response.ok ? null : response.errorKey ?? "chat.errors.integrityFailure" }
: mutation
);
}
/** Retains the stable request id for an explicit retry. */
export function retryChatMessageMutation(
current: readonly ChatOptimisticMessageMutation[],
requestId: string
): readonly ChatOptimisticMessageMutation[] {
return current.map((mutation) => (mutation.requestId === requestId ? { ...mutation, state: "pending", errorKey: null } : mutation));
}
export function reconcileChatMessageMutations(
current: readonly ChatOptimisticMessageMutation[],
authoritativeVm: ChatChannelDetailVM
): readonly ChatOptimisticMessageMutation[] {
if (authoritativeVm.status !== "ready") return current;
const messages = new Map(authoritativeVm.data.messages.map((message) => [message.id, message]));
const next = current.filter((mutation) => {
if (mutation.state === "failed" || mutation.state === "pending") return true;
const message = messages.get(mutation.messageId);
if (!message) return true;
if (mutation.kind === "delete_message") return message.deletedAtIso === null;
return message.bodyMarkdown !== mutation.bodyMarkdown || message.editedAtIso === null;
});
return next.length === current.length ? current : next;
}
export function failedChatMessageMutationForMessage(
current: readonly ChatOptimisticMessageMutation[],
messageId: string
): ChatOptimisticMessageMutation | null {
return current.find((mutation) => mutation.messageId === messageId && mutation.state === "failed") ?? null;
}
export function chatMessageMutationErrors(
current: readonly ChatOptimisticMessageMutation[]
): Readonly<Record<string, string>> {
return Object.fromEntries(
current.flatMap((mutation) => (mutation.state === "failed" && mutation.errorKey ? [[mutation.messageId, mutation.errorKey] as const] : []))
);
}
export function overlayChatMessageMutations(
vm: ChatChannelDetailVM,
mutations: readonly ChatOptimisticMessageMutation[]
): ChatChannelDetailVM {
if (vm.status !== "ready" || mutations.length === 0) return vm;
const active = new Map(mutations.filter((mutation) => mutation.state !== "failed").map((mutation) => [mutation.messageId, mutation]));
if (active.size === 0) return vm;
const messages = vm.data.messages.map((message) => overlayMessage(message, active.get(message.id)));
const messagesById = new Map(messages.map((message) => [message.id, message]));
return {
...vm,
data: {
...vm.data,
messages,
messageGroups: vm.data.messageGroups.map((group) => ({
...group,
messages: group.messages.map((message) => messagesById.get(message.id) ?? message),
})),
pinnedMessages: vm.data.pinnedMessages.filter((pin) => active.get(pin.messageId)?.kind !== "delete_message"),
},
};
}
export function reconcileChatThreadMessageMutations(
current: readonly ChatOptimisticMessageMutation[],
authoritativeVm: ChatThreadVM
): readonly ChatOptimisticMessageMutation[] {
if (authoritativeVm.status !== "ready") return current;
const messages = new Map([authoritativeVm.data.parent, ...authoritativeVm.data.replies].map((message) => [message.id, message]));
const next = current.filter((mutation) => {
if (mutation.state === "failed" || mutation.state === "pending") return true;
const message = messages.get(mutation.messageId);
if (!message) return true;
if (mutation.kind === "delete_message") return !message.deleted;
return message.bodyMarkdown !== mutation.bodyMarkdown;
});
return next.length === current.length ? current : next;
}
export function overlayChatThreadMessageMutations(
vm: ChatThreadVM,
mutations: readonly ChatOptimisticMessageMutation[]
): ChatThreadVM {
if (vm.status !== "ready" || mutations.length === 0) return vm;
const active = new Map(mutations.filter((mutation) => mutation.state !== "failed").map((mutation) => [mutation.messageId, mutation]));
if (active.size === 0) return vm;
return {
...vm,
data: {
...vm.data,
parent: overlayFeatureMessage(vm.data.parent, active.get(vm.data.parent.id)),
replies: vm.data.replies.map((message) => overlayFeatureMessage(message, active.get(message.id))),
},
};
}
function overlayMessage(message: ChatMessageVM, mutation: ChatOptimisticMessageMutation | undefined): ChatMessageVM {
if (!mutation) return message;
if (mutation.kind === "delete_message") {
return {
...message,
bodyMarkdown: null,
editedAtIso: null,
deletedAtIso: mutation.startedAtIso,
mentions: [],
reactions: [],
attachments: [],
linkPreviews: [],
pin: null,
actions: { canReact: false, canReply: false, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: false },
tombstoneKey: "chat.message.deleted",
};
}
return {
...message,
bodyMarkdown: mutation.bodyMarkdown,
mentions: mutation.mentions,
editedAtIso: mutation.startedAtIso,
};
}
function overlayFeatureMessage(
message: ChatFeatureMessageVM,
mutation: ChatOptimisticMessageMutation | undefined
): ChatFeatureMessageVM {
if (!mutation) return message;
if (mutation.kind === "delete_message") {
return {
...message,
bodyMarkdown: null,
deleted: true,
mentions: [],
reactions: [],
attachments: [],
pinned: false,
canReact: false,
canPin: false,
canEdit: false,
canDelete: false,
};
}
return { ...message, bodyMarkdown: mutation.bodyMarkdown, mentions: mutation.mentions };
}
@@ -0,0 +1,174 @@
import { buildChatChannelDetailVM, type ChatMessageCandidate } from "@hivegrid/view-models";
import { describe, expect, it } from "vitest";
import { overlayChatChannelDetailRealtime } from "./chatRealtimeViewModel";
const message: ChatMessageCandidate = {
id: "message_1",
clientMessageId: "client_1",
source: "websocket",
deliveryState: "sent",
failureReasonKey: null,
author: {
userId: "user_1",
displayName: "Ada",
avatar: { imageUrl: null, fallbackLabel: "A" },
isCurrentUser: false,
},
bodyMarkdown: "Hallo",
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: "2026-07-15T08:00:00.000Z",
updatedAtIso: "2026-07-15T08:00:00.000Z",
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: { readCount: 0, recipientCount: 1, readerUserIds: [], readerLabels: [], labelKey: "chat.message.read.none" },
pin: null,
actions: { canReact: false, canReply: false, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: false },
};
function readyVm() {
return buildChatChannelDetailVM({
header: {
id: "chat_1",
kind: "group",
title: "Team",
subtitle: null,
avatar: { imageUrl: null, fallbackLabel: "T" },
project: null,
memberCount: 2,
isPrivate: false,
isArchived: false,
isAuditMode: false,
canManage: false,
settingsHref: null,
pinnedHref: null,
searchHref: "/tenant/chat/chat_1/search",
},
messages: [],
pinnedMessages: [],
typingLabels: [],
history: { olderCursor: null, hasOlder: false },
composer: {
disabledReasonKey: null,
canSend: true,
canAttachFiles: false,
canRecordVoice: false,
canMention: false,
canMarkAsTask: false,
draftStorageKey: "chat:draft",
maxBodyLength: 8_000,
},
connection: { state: "connecting", reconnectAttempt: 0, retryAtIso: null },
});
}
describe("overlayChatChannelDetailRealtime", () => {
it("overlays transport state on a ready loader VM without replacing domain data", () => {
const renderedMessage = buildChatChannelDetailVM({ ...readyVmInput(), messages: [message] });
if (renderedMessage.status !== "ready") throw new Error("fixture must be ready");
const vm = readyVm();
const result = overlayChatChannelDetailRealtime(vm, {
messages: renderedMessage.data.messages,
messageGroups: renderedMessage.data.messageGroups,
presence: [{ userId: "user_2", status: "online" }],
typingLabels: ["Ada"],
connection: { state: "reconnecting", reconnectAttempt: 2, retryAtIso: "2026-07-15T08:01:00.000Z" },
});
expect(result.status).toBe("ready");
if (result.status !== "ready" || vm.status !== "ready") throw new Error("fixture must be ready");
expect(result.data.header).toBe(vm.data.header);
expect(result.data.messages).toEqual(renderedMessage.data.messages);
expect(result.data.presence).toEqual([{ userId: "user_2", status: "online" }]);
expect(result.data.typingLabels).toEqual(["Ada"]);
expect(result.data.connection).toEqual({
state: "reconnecting",
stateLabelKey: "chat.connection.reconnecting",
reconnectAttempt: 2,
retryAtIso: "2026-07-15T08:01:00.000Z",
canRetry: true,
});
});
it("leaves non-ready loader states untouched", () => {
const vm = { status: "loading" } as const;
expect(
overlayChatChannelDetailRealtime(vm, {
messages: [],
messageGroups: [],
presence: [],
typingLabels: [],
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
})
).toBe(vm);
});
it("makes a terminally blocked connection read-only without hiding the draft", () => {
const vm = readyVm();
const result = overlayChatChannelDetailRealtime(vm, {
messages: [],
messageGroups: [],
presence: [],
typingLabels: [],
connection: { state: "blocked", reconnectAttempt: 0, retryAtIso: null },
});
expect(result.status).toBe("ready");
if (result.status !== "ready") return;
expect(result.data.composer).toMatchObject({
enabled: false,
canSend: false,
disabledReasonKey: "chat.composer.connectionBlocked",
});
expect(result.data.connection.canRetry).toBe(false);
});
});
function readyVmInput(): Parameters<typeof buildChatChannelDetailVM>[0] {
const vm = readyVm();
if (vm.status !== "ready") throw new Error("fixture must be ready");
return {
header: {
id: vm.data.header.id,
kind: vm.data.header.kind,
title: vm.data.header.title,
subtitle: vm.data.header.subtitle,
avatar: vm.data.header.avatar,
project: vm.data.header.project,
memberCount: vm.data.header.memberCount,
isPrivate: vm.data.header.isPrivate,
isArchived: vm.data.header.isArchived,
isAuditMode: vm.data.header.isAuditMode,
canManage: vm.data.header.canManage,
settingsHref: vm.data.header.settingsHref,
pinnedHref: vm.data.header.pinnedHref,
searchHref: vm.data.header.searchHref,
},
messages: [],
pinnedMessages: [],
typingLabels: [],
history: vm.data.history,
composer: {
disabledReasonKey: vm.data.composer.disabledReasonKey,
canSend: vm.data.composer.canSend,
canAttachFiles: vm.data.composer.canAttachFiles,
canRecordVoice: vm.data.composer.canRecordVoice,
canMention: vm.data.composer.canMention,
canMarkAsTask: vm.data.composer.canMarkAsTask,
draftStorageKey: vm.data.composer.draftStorageKey,
maxBodyLength: vm.data.composer.maxBodyLength,
},
connection: {
state: vm.data.connection.state,
reconnectAttempt: vm.data.connection.reconnectAttempt,
retryAtIso: vm.data.connection.retryAtIso,
},
};
}
@@ -0,0 +1,56 @@
import {
chatConnectionStateLabelKey,
type ChatChannelDetailVM,
type ChatMessageDayGroupVM,
type ChatMessageVM,
type ChatPresenceVM,
} from "@hivegrid/view-models";
import type { ChatRealtimeConnection } from "./chatChannelRealtimeReducer";
export type ChatChannelRealtimeViewOverlay = {
readonly messages: readonly ChatMessageVM[];
readonly messageGroups: readonly ChatMessageDayGroupVM[];
readonly presence: readonly ChatPresenceVM[];
readonly typingLabels: readonly string[];
readonly connection: ChatRealtimeConnection;
};
/** Applies transport-only state to the loader-owned render contract. Repository
* records never cross this boundary. */
export function overlayChatChannelDetailRealtime(vm: ChatChannelDetailVM, overlay: ChatChannelRealtimeViewOverlay): ChatChannelDetailVM {
if (vm.status !== "ready") return vm;
const canRetry = overlay.connection.state === "offline" || overlay.connection.state === "reconnecting";
const composer =
overlay.connection.state === "blocked"
? {
...vm.data.composer,
enabled: false,
disabledReasonKey: "chat.composer.connectionBlocked",
canSend: false,
canAttachFiles: false,
canRecordVoice: false,
canMention: false,
canMarkAsTask: false,
}
: vm.data.composer;
return {
status: "ready",
data: {
...vm.data,
messages: overlay.messages,
messageGroups: overlay.messageGroups,
presence: overlay.presence.map(({ userId, status }) => ({ userId, status })),
typingLabels: overlay.typingLabels,
composer,
connection: {
...vm.data.connection,
state: overlay.connection.state,
stateLabelKey: chatConnectionStateLabelKey(overlay.connection.state),
reconnectAttempt: overlay.connection.reconnectAttempt,
retryAtIso: overlay.connection.retryAtIso,
canRetry,
},
},
};
}
@@ -0,0 +1,41 @@
import { describe, expect, it, vi } from "vitest";
import { buildChatWebSocketUrl, createChatTokenProvider } from "./chatTokenProvider";
describe("chatTokenProvider", () => {
it("builds the gateway URL from the configured API host with the fixed chat path", () => {
expect(buildChatWebSocketUrl({ protocol: "https", apiHost: "api.example.test" })).toBe("wss://api.example.test/ws/chat");
expect(buildChatWebSocketUrl({ protocol: "http", apiHost: "api.localhost:3000" })).toBe("ws://api.localhost:3000/ws/chat");
expect(() => buildChatWebSocketUrl({ protocol: "https", apiHost: "api.example.test/not-allowed" })).toThrow();
});
it("requests a same-origin no-store token with header-only CSRF", async () => {
const fetchImpl = vi.fn(async () => Response.json({ ok: true, data: { token: "header.payload.signature", expiresIn: 300, refreshAfter: 240 } }));
const provider = createChatTokenProvider({ tenantSlug: "hivegrid demo", csrfToken: "csrf-token", fetchImpl });
await expect(provider({ reconnectAttempt: 2 })).resolves.toBe("header.payload.signature");
expect(fetchImpl).toHaveBeenCalledWith("/hivegrid%20demo/chat/token", {
method: "POST",
headers: { accept: "application/json", "x-csrf-token": "csrf-token" },
credentials: "same-origin",
cache: "no-store",
redirect: "error",
});
});
it("rejects failed and malformed token responses without exposing their bodies", async () => {
const failed = createChatTokenProvider({
tenantSlug: "tenant",
csrfToken: "csrf",
fetchImpl: async () => new Response("secret upstream detail", { status: 503 }),
});
await expect(failed({ reconnectAttempt: 0 })).rejects.toThrow("Chat gateway token could not be loaded.");
const malformed = createChatTokenProvider({
tenantSlug: "tenant",
csrfToken: "csrf",
fetchImpl: async () => Response.json({ ok: true, data: { token: " padded " } }),
});
await expect(malformed({ reconnectAttempt: 0 })).rejects.toThrow("Chat gateway token response was invalid.");
});
});
@@ -0,0 +1,83 @@
import type { ChatTokenProvider } from "@hivegrid/realtime";
export type ChatGatewayRouting = {
readonly protocol: "http" | "https";
readonly apiHost: string;
};
export type ChatTokenFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
export type CreateChatTokenProviderInput = {
readonly tenantSlug: string;
readonly csrfToken: string;
readonly fetchImpl?: ChatTokenFetch;
};
type ChatTokenPayload = {
readonly ok: true;
readonly data: {
readonly token: string;
};
};
/** The gateway lives on the configured API host and exposes one fixed path. */
export function buildChatWebSocketUrl(routing: ChatGatewayRouting): string {
const url = new URL(`${routing.protocol}://${routing.apiHost}`);
if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
throw new Error("Chat API routing must contain a host without credentials or a path.");
}
url.protocol = routing.protocol === "https" ? "wss:" : "ws:";
url.pathname = "/ws/chat";
return url.toString();
}
/** Loads a short-lived token over the same-origin session boundary. */
export function createChatTokenProvider(input: CreateChatTokenProviderInput): ChatTokenProvider {
const tenantSlug = requireNonEmpty(input.tenantSlug, "tenant slug");
const csrfToken = requireNonEmpty(input.csrfToken, "CSRF token");
const fetchImpl = input.fetchImpl ?? globalThis.fetch;
if (typeof fetchImpl !== "function") {
throw new Error("Fetch is not available; provide a fetch implementation.");
}
const tokenPath = `/${encodeURIComponent(tenantSlug)}/chat/token`;
return async () => {
const response = await fetchImpl(tokenPath, {
method: "POST",
headers: {
accept: "application/json",
"x-csrf-token": csrfToken,
},
credentials: "same-origin",
cache: "no-store",
redirect: "error",
});
if (!response.ok) throw new Error("Chat gateway token could not be loaded.");
let payload: unknown;
try {
payload = await response.json();
} catch {
throw new Error("Chat gateway token response was invalid.");
}
if (!isChatTokenPayload(payload)) {
throw new Error("Chat gateway token response was invalid.");
}
return payload.data.token;
};
}
function isChatTokenPayload(value: unknown): value is ChatTokenPayload {
if (!isRecord(value) || value.ok !== true || !isRecord(value.data)) return false;
const token = value.data.token;
return typeof token === "string" && token.length > 0 && token === token.trim();
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function requireNonEmpty(value: string, label: string): string {
if (value.length === 0 || value !== value.trim()) throw new Error(`Chat ${label} is invalid.`);
return value;
}
@@ -0,0 +1,6 @@
export * from "./chatChannelRealtimeReducer";
export * from "./chatInteractionControllers";
export * from "./chatRealtimeViewModel";
export * from "./chatTokenProvider";
export * from "./useChatChannelRealtime";
export * from "./useChatMessageViewport";
@@ -0,0 +1,228 @@
// @vitest-environment jsdom
import { act, renderHook, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ upload: vi.fn(), waitForScan: vi.fn() }));
vi.mock("~/utils/files/uploadFileClient", () => ({
uploadFileInChunks: (...args: unknown[]) => mocks.upload(...args),
waitForChatAttachmentScan: (...args: unknown[]) => mocks.waitForScan(...args),
}));
import { useChatAttachmentUploads } from "./useChatAttachmentUploads";
describe("useChatAttachmentUploads", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.useRealTimers();
mocks.waitForScan.mockResolvedValue(undefined);
});
it("shows an optimistic upload, reports progress, and keeps only the returned File id", async () => {
let finishUpload: (() => void) | undefined;
const uploadBarrier = new Promise<void>((resolve) => {
finishUpload = resolve;
});
mocks.upload.mockImplementation(async (input: { onProgress?: (progress: number) => void; onProcessing?: () => void }) => {
input.onProgress?.(50);
input.onProcessing?.();
await uploadBarrier;
return { id: "file_1", displayName: "photo.jpg" };
});
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
act(() => result.current.addFiles([new File(["image"], "camera.jpg", { type: "image/jpeg" })]));
expect(result.current.attachments).toHaveLength(1);
expect(result.current.attachments[0]).toMatchObject({ kind: "image", status: "processing", fileId: null });
await act(async () => finishUpload?.());
await waitFor(() => expect(result.current.attachments[0]).toMatchObject({ status: "ready", progress: 100, fileId: "file_1" }));
expect(mocks.upload).toHaveBeenCalledWith(expect.objectContaining({ tenantSlug: "acme", file: expect.any(File), signal: expect.any(AbortSignal) }));
expect(mocks.waitForScan).toHaveBeenCalledWith(expect.objectContaining({ tenantSlug: "acme", fileId: "file_1" }));
act(() => result.current.clearReady(["file_1"]));
expect(result.current.attachments).toEqual([]);
});
it("keeps failed files retryable and removes them from the queue on demand", async () => {
mocks.upload
.mockRejectedValueOnce(Object.assign(new Error("failed"), { errorKey: "files.error.mimeBlocked" }))
.mockResolvedValueOnce({ id: "file_2", displayName: "notes.txt" });
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
act(() => result.current.addFiles([new File(["notes"], "notes.txt", { type: "text/plain" })]));
await waitFor(() => expect(result.current.attachments[0]).toMatchObject({ status: "error", errorKey: "files.error.mimeBlocked" }));
const clientId = result.current.attachments[0]!.clientId;
act(() => result.current.retry(clientId));
await waitFor(() => expect(result.current.attachments[0]).toMatchObject({ status: "ready", fileId: "file_2" }));
expect(mocks.upload).toHaveBeenCalledTimes(2);
act(() => result.current.remove(clientId));
expect(result.current.attachments).toEqual([]);
});
it("reports an oversized queue selection instead of silently truncating it", () => {
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
const files = Array.from({ length: 21 }, (_, index) => new File([String(index)], `file-${index}.txt`, { type: "text/plain" }));
act(() => result.current.addFiles(files));
expect(result.current.attachments).toEqual([]);
expect(result.current.errorKey).toBe("chat.attachments.tooMany");
expect(mocks.upload).not.toHaveBeenCalled();
});
it("reserves the 20 attachment slots atomically across same-tick selections", () => {
mocks.upload.mockImplementation(() => new Promise(() => undefined));
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
const first = Array.from({ length: 11 }, (_, index) => new File([String(index)], `first-${index}.txt`, { type: "text/plain" }));
const second = Array.from({ length: 10 }, (_, index) => new File([String(index)], `second-${index}.txt`, { type: "text/plain" }));
act(() => {
result.current.addFiles(first);
result.current.addFiles(second);
});
expect(result.current.attachments).toHaveLength(11);
expect(result.current.errorKey).toBe("chat.attachments.tooMany");
expect(mocks.upload).toHaveBeenCalledTimes(11);
});
it("surfaces unsupported voice recording instead of failing silently", async () => {
vi.stubGlobal("MediaRecorder", undefined);
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
await act(() => result.current.startRecording());
expect(result.current.errorKey).toBe("chat.attachments.recordingUnsupported");
vi.unstubAllGlobals();
});
it("shows recording duration and discards a cancelled voice note before upload", async () => {
vi.useFakeTimers();
const stopTrack = vi.fn();
class FakeMediaRecorder {
static isTypeSupported(): boolean {
return true;
}
state: RecordingState = "inactive";
mimeType = "audio/webm";
ondataavailable: ((event: BlobEvent) => void) | null = null;
onstop: (() => void) | null = null;
onerror: (() => void) | null = null;
start(): void {
this.state = "recording";
}
stop(): void {
this.state = "inactive";
this.ondataavailable?.({ data: new Blob(["voice"], { type: this.mimeType }) } as BlobEvent);
this.onstop?.();
}
}
vi.stubGlobal("MediaRecorder", FakeMediaRecorder);
Object.defineProperty(navigator, "mediaDevices", {
configurable: true,
value: { getUserMedia: vi.fn().mockResolvedValue({ getTracks: () => [{ stop: stopTrack }] }) },
});
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
await act(() => result.current.startRecording());
expect(result.current.isRecording).toBe(true);
act(() => vi.advanceTimersByTime(1_250));
expect(result.current.recordingDurationSeconds).toBe(1);
act(() => result.current.cancelRecording());
expect(result.current.isRecording).toBe(false);
expect(result.current.recordingDurationSeconds).toBe(0);
expect(result.current.attachments).toEqual([]);
expect(mocks.upload).not.toHaveBeenCalled();
expect(stopTrack).toHaveBeenCalledOnce();
vi.unstubAllGlobals();
vi.useRealTimers();
});
it("does not request the microphone twice while the first permission request is pending", async () => {
let resolveStream: ((stream: MediaStream) => void) | undefined;
const streamPromise = new Promise<MediaStream>((resolve) => {
resolveStream = resolve;
});
const getUserMedia = vi.fn(() => streamPromise);
class FakeMediaRecorder {
static isTypeSupported(): boolean {
return true;
}
state: RecordingState = "inactive";
mimeType = "audio/webm;codecs=opus";
ondataavailable: ((event: BlobEvent) => void) | null = null;
onstop: (() => void) | null = null;
onerror: (() => void) | null = null;
start(): void {
this.state = "recording";
}
stop(): void {
this.state = "inactive";
this.onstop?.();
}
}
vi.stubGlobal("MediaRecorder", FakeMediaRecorder);
Object.defineProperty(navigator, "mediaDevices", { configurable: true, value: { getUserMedia } });
const stopTrack = vi.fn();
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
let firstStart: Promise<void> | undefined;
await act(async () => {
firstStart = result.current.startRecording();
await result.current.startRecording();
});
expect(result.current.isStartingRecording).toBe(true);
expect(getUserMedia).toHaveBeenCalledOnce();
resolveStream?.({ getTracks: () => [{ stop: stopTrack }] } as unknown as MediaStream);
await act(async () => firstStart);
expect(result.current.isStartingRecording).toBe(false);
expect(result.current.isRecording).toBe(true);
act(() => result.current.cancelRecording());
vi.unstubAllGlobals();
});
it("canonicalizes codec MIME parameters and keeps the voice-note duration in the optimistic item", async () => {
vi.useFakeTimers();
mocks.upload.mockImplementation(async (input: { file: File }) => ({ id: "voice-1", displayName: input.file.name }));
class FakeMediaRecorder {
static isTypeSupported(): boolean {
return true;
}
state: RecordingState = "inactive";
mimeType = "audio/webm;codecs=opus";
ondataavailable: ((event: BlobEvent) => void) | null = null;
onstop: (() => void) | null = null;
onerror: (() => void) | null = null;
start(): void {
this.state = "recording";
}
stop(): void {
this.state = "inactive";
this.ondataavailable?.({ data: new Blob(["voice"], { type: this.mimeType }) } as BlobEvent);
this.onstop?.();
}
}
vi.stubGlobal("MediaRecorder", FakeMediaRecorder);
Object.defineProperty(navigator, "mediaDevices", {
configurable: true,
value: { getUserMedia: vi.fn().mockResolvedValue({ getTracks: () => [{ stop: vi.fn() }] }) },
});
const { result } = renderHook(() => useChatAttachmentUploads({ tenantSlug: "acme", enabled: true }));
await act(() => result.current.startRecording());
act(() => vi.advanceTimersByTime(2_100));
act(() => result.current.stopRecording());
vi.useRealTimers();
await waitFor(() => expect(result.current.attachments[0]?.status).toBe("ready"));
expect(result.current.attachments[0]).toMatchObject({ mimeType: "audio/webm", durationSeconds: 2, fileId: "voice-1" });
expect(mocks.upload.mock.calls.at(-1)?.[0].file.type).toBe("audio/webm");
vi.unstubAllGlobals();
});
});
@@ -0,0 +1,331 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { FILE_UPLOAD_MAX_FILE_SIZE_BYTES } from "@hivegrid/view-models";
import { uploadFileInChunks, waitForChatAttachmentScan } from "~/utils/files/uploadFileClient";
export type ChatPendingAttachment = {
readonly clientId: string;
readonly fileId: string | null;
readonly fileName: string;
readonly mimeType: string;
readonly sizeBytes: number;
readonly kind: "file" | "image" | "voice";
readonly status: "uploading" | "processing" | "ready" | "error";
readonly progress: number;
readonly errorKey: string | null;
readonly durationSeconds: number | null;
};
export const MAX_CHAT_ATTACHMENTS = 20;
export const MAX_VOICE_RECORDING_SECONDS = 10 * 60;
export function useChatAttachmentUploads(input: { readonly tenantSlug: string; readonly enabled: boolean }): {
readonly attachments: readonly ChatPendingAttachment[];
readonly isStartingRecording: boolean;
readonly isRecording: boolean;
readonly recordingDurationSeconds: number;
readonly errorKey: string | null;
readonly addFiles: (files: FileList | readonly File[], kindHint?: "voice") => void;
readonly retry: (clientId: string) => void;
readonly remove: (clientId: string) => void;
readonly clearReady: (fileIds: readonly string[]) => void;
readonly startRecording: () => Promise<void>;
readonly stopRecording: () => void;
readonly cancelRecording: () => void;
} {
const [attachments, setAttachments] = useState<readonly ChatPendingAttachment[]>([]);
const [isStartingRecording, setIsStartingRecording] = useState(false);
const [isRecording, setIsRecording] = useState(false);
const [recordingDurationSeconds, setRecordingDurationSeconds] = useState(0);
const [errorKey, setErrorKey] = useState<string | null>(null);
const filesRef = useRef(new Map<string, File>());
const attachmentCountRef = useRef(0);
const abortRef = useRef(new Map<string, AbortController>());
const recorderRef = useRef<MediaRecorder | null>(null);
const recordingStreamRef = useRef<MediaStream | null>(null);
const recordingChunksRef = useRef<Blob[]>([]);
const recordingStartedAtRef = useRef<number | null>(null);
const recordingTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const recordingCancelledRef = useRef(false);
const recordingStartingRef = useRef(false);
const recordingBytesRef = useRef(0);
const disposedRef = useRef(false);
const enabledRef = useRef(input.enabled);
enabledRef.current = input.enabled;
const clearRecordingTimer = useCallback(() => {
if (recordingTimerRef.current !== null) clearInterval(recordingTimerRef.current);
recordingTimerRef.current = null;
recordingStartedAtRef.current = null;
}, []);
const upload = useCallback(
async (clientId: string, file: File): Promise<void> => {
const controller = new AbortController();
abortRef.current.set(clientId, controller);
setAttachments((current) => current.map((item) => (item.clientId === clientId ? { ...item, status: "uploading", progress: 0, errorKey: null } : item)));
try {
const result = await uploadFileInChunks({
tenantSlug: input.tenantSlug,
file,
signal: controller.signal,
onProgress: (progress) => setAttachments((current) => current.map((item) => (item.clientId === clientId ? { ...item, progress } : item))),
onProcessing: () =>
setAttachments((current) => current.map((item) => (item.clientId === clientId ? { ...item, status: "processing", progress: 100 } : item))),
});
setAttachments((current) =>
current.map((item) =>
item.clientId === clientId ? { ...item, fileId: result.id, fileName: result.displayName, status: "processing", progress: 100 } : item
)
);
await waitForChatAttachmentScan({
tenantSlug: input.tenantSlug,
fileId: result.id,
signal: controller.signal,
});
setAttachments((current) =>
current.map((item) =>
item.clientId === clientId ? { ...item, fileId: result.id, fileName: result.displayName, status: "ready", progress: 100 } : item
)
);
} catch (error) {
if (controller.signal.aborted) return;
const errorKey = error instanceof Error && "errorKey" in error && typeof error.errorKey === "string" ? error.errorKey : "chat.attachments.uploadFailed";
setAttachments((current) => current.map((item) => (item.clientId === clientId ? { ...item, status: "error", errorKey } : item)));
} finally {
abortRef.current.delete(clientId);
}
},
[input.tenantSlug]
);
const addFiles = useCallback(
(files: FileList | readonly File[], kindHint?: "voice", durationSeconds: number | null = null) => {
if (!input.enabled) return;
const selected = Array.from(files);
if (selected.length === 0) return;
if (selected.length > Math.max(0, MAX_CHAT_ATTACHMENTS - attachmentCountRef.current)) {
setErrorKey("chat.attachments.tooMany");
return;
}
attachmentCountRef.current += selected.length;
setErrorKey(null);
const entries = selected.map((file) => {
const clientId = createClientId();
filesRef.current.set(clientId, file);
return {
clientId,
fileId: null,
fileName: file.name,
mimeType: file.type || "application/octet-stream",
sizeBytes: file.size,
kind:
kindHint === "voice" || file.type.startsWith("audio/")
? ("voice" as const)
: file.type.startsWith("image/")
? ("image" as const)
: ("file" as const),
status: "uploading" as const,
progress: 0,
errorKey: null,
durationSeconds: kindHint === "voice" ? durationSeconds : null,
};
});
setAttachments((current) => [...current, ...entries]);
for (const entry of entries) void upload(entry.clientId, filesRef.current.get(entry.clientId)!);
},
[input.enabled, upload]
);
const remove = useCallback((clientId: string) => {
abortRef.current.get(clientId)?.abort();
abortRef.current.delete(clientId);
filesRef.current.delete(clientId);
setAttachments((current) => {
const removed = current.some((item) => item.clientId === clientId);
if (removed) attachmentCountRef.current = Math.max(0, attachmentCountRef.current - 1);
return current.filter((item) => item.clientId !== clientId);
});
setErrorKey(null);
}, []);
const retry = useCallback(
(clientId: string) => {
const file = filesRef.current.get(clientId);
if (file) void upload(clientId, file);
},
[upload]
);
const clearReady = useCallback((fileIds: readonly string[]) => {
const sent = new Set(fileIds);
setAttachments((current) => {
const removedClientIds = current.filter((item) => item.fileId && sent.has(item.fileId)).map((item) => item.clientId);
for (const clientId of removedClientIds) filesRef.current.delete(clientId);
attachmentCountRef.current = Math.max(0, attachmentCountRef.current - removedClientIds.length);
return current.filter((item) => !item.fileId || !sent.has(item.fileId));
});
}, []);
const stopRecording = useCallback(() => {
recordingCancelledRef.current = false;
if (recorderRef.current?.state === "recording") recorderRef.current.stop();
}, []);
const cancelRecording = useCallback(() => {
recordingCancelledRef.current = true;
if (recorderRef.current?.state === "recording") recorderRef.current.stop();
}, []);
const startRecording = useCallback(async () => {
if (!input.enabled || isRecording || recordingStartingRef.current || recorderRef.current) {
return;
}
if (typeof MediaRecorder === "undefined" || !navigator.mediaDevices?.getUserMedia) {
setErrorKey("chat.attachments.recordingUnsupported");
return;
}
let stream: MediaStream | null = null;
recordingStartingRef.current = true;
setIsStartingRecording(true);
try {
setErrorKey(null);
stream = await navigator.mediaDevices.getUserMedia({ audio: true });
if (disposedRef.current || !enabledRef.current) {
stream.getTracks().forEach((track) => track.stop());
return;
}
recordingStreamRef.current = stream;
recordingChunksRef.current = [];
recordingBytesRef.current = 0;
recordingCancelledRef.current = false;
setRecordingDurationSeconds(0);
const preferredMimeType = preferredRecordingMimeType();
const recorder = new MediaRecorder(stream, preferredMimeType ? { mimeType: preferredMimeType } : undefined);
recorderRef.current = recorder;
recorder.ondataavailable = (event) => {
if (event.data.size <= 0 || recordingCancelledRef.current) return;
if (recordingBytesRef.current + event.data.size > FILE_UPLOAD_MAX_FILE_SIZE_BYTES) {
recordingCancelledRef.current = true;
setErrorKey("chat.attachments.recordingTooLarge");
if (recorder.state === "recording") recorder.stop();
return;
}
recordingBytesRef.current += event.data.size;
recordingChunksRef.current.push(event.data);
};
recorder.onstop = () => {
const cancelled = recordingCancelledRef.current;
const durationSeconds = recordingStartedAtRef.current
? Math.min(MAX_VOICE_RECORDING_SECONDS, Math.max(1, Math.round((Date.now() - recordingStartedAtRef.current) / 1_000)))
: null;
const mimeType = canonicalRecordingMimeType(recorder.mimeType);
const blob = new Blob(recordingChunksRef.current, { type: mimeType });
const extension = recordingFileExtension(mimeType);
if (!cancelled && blob.size > 0 && isSupportedRecordingMimeType(mimeType)) {
addFiles([new File([blob], `voice-note-${Date.now()}.${extension}`, { type: mimeType })], "voice", durationSeconds);
} else if (!cancelled && blob.size > 0) {
setErrorKey("chat.attachments.recordingFailed");
}
recordingChunksRef.current = [];
recordingBytesRef.current = 0;
recordingCancelledRef.current = false;
clearRecordingTimer();
recordingStreamRef.current?.getTracks().forEach((track) => track.stop());
recordingStreamRef.current = null;
recorderRef.current = null;
setIsRecording(false);
setRecordingDurationSeconds(0);
};
recorder.onerror = () => {
recordingCancelledRef.current = true;
recordingChunksRef.current = [];
clearRecordingTimer();
recordingStreamRef.current?.getTracks().forEach((track) => track.stop());
recordingStreamRef.current = null;
recorderRef.current = null;
setIsRecording(false);
setRecordingDurationSeconds(0);
setErrorKey("chat.attachments.recordingFailed");
};
recorder.start(1_000);
recordingStartedAtRef.current = Date.now();
recordingTimerRef.current = setInterval(() => {
const startedAt = recordingStartedAtRef.current;
if (startedAt === null) return;
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - startedAt) / 1_000));
setRecordingDurationSeconds(Math.min(MAX_VOICE_RECORDING_SECONDS, elapsedSeconds));
if (elapsedSeconds >= MAX_VOICE_RECORDING_SECONDS && recorder.state === "recording") {
recordingCancelledRef.current = false;
recorder.stop();
}
}, 250);
setIsRecording(true);
} catch {
stream?.getTracks().forEach((track) => track.stop());
recordingStreamRef.current = null;
setIsRecording(false);
setErrorKey("chat.attachments.microphoneDenied");
} finally {
recordingStartingRef.current = false;
if (!disposedRef.current) setIsStartingRecording(false);
}
}, [addFiles, clearRecordingTimer, input.enabled, isRecording]);
useEffect(
() => () => {
disposedRef.current = true;
for (const controller of abortRef.current.values()) controller.abort();
recordingCancelledRef.current = true;
clearRecordingTimer();
if (recorderRef.current?.state === "recording") recorderRef.current.stop();
recordingStreamRef.current?.getTracks().forEach((track) => track.stop());
},
[clearRecordingTimer]
);
return {
attachments,
isStartingRecording,
isRecording,
recordingDurationSeconds,
errorKey,
addFiles,
retry,
remove,
clearReady,
startRecording,
stopRecording,
cancelRecording,
};
}
function createClientId(): string {
return typeof crypto !== "undefined" && typeof crypto.randomUUID === "function"
? crypto.randomUUID()
: `upload-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
const RECORDING_MIME_TYPES = new Set(["audio/webm", "audio/ogg", "audio/mp4", "audio/mpeg", "audio/wav"]);
function preferredRecordingMimeType(): string | undefined {
if (typeof MediaRecorder.isTypeSupported !== "function") return undefined;
return ["audio/webm;codecs=opus", "audio/ogg;codecs=opus", "audio/mp4"].find((mimeType) => MediaRecorder.isTypeSupported(mimeType));
}
function canonicalRecordingMimeType(value: string): string {
const base = (value || "audio/webm").split(";", 1)[0]?.trim().toLowerCase() || "audio/webm";
return base === "audio/x-m4a" ? "audio/mp4" : base === "audio/x-wav" ? "audio/wav" : base;
}
function isSupportedRecordingMimeType(value: string): boolean {
return RECORDING_MIME_TYPES.has(value);
}
function recordingFileExtension(mimeType: string): string {
if (mimeType === "audio/ogg") return "ogg";
if (mimeType === "audio/mp4") return "m4a";
if (mimeType === "audio/mpeg") return "mp3";
if (mimeType === "audio/wav") return "wav";
return "webm";
}
@@ -0,0 +1,388 @@
// @vitest-environment jsdom
import {
CHAT_EVENT_NAMES,
type ChatLocalEcho,
type ChatMessageCreatedEvent,
type ChatReadReceiptEvent,
type ChatRealtimeClient,
type ChatRealtimeClientOptions,
} from "@hivegrid/realtime";
import type { ChatMessageCandidate, ChatResolvedAuthorVM } from "@hivegrid/view-models";
import { act, renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import type { ChatVisibilitySource } from "./chatInteractionControllers";
import { useChatChannelRealtime, type UseChatChannelRealtimeInput } from "./useChatChannelRealtime";
const viewer: ChatResolvedAuthorVM = {
userId: "user_viewer",
displayName: "Raffael",
avatar: { imageUrl: null, fallbackLabel: "R" },
isCurrentUser: true,
};
const reader: ChatResolvedAuthorVM = {
userId: "user_reader",
displayName: "Mara",
avatar: { imageUrl: null, fallbackLabel: "M" },
isCurrentUser: false,
};
function hydratedMessage(): ChatMessageCandidate {
return {
id: "message_read",
clientMessageId: "client_read",
source: "persisted",
deliveryState: "sent",
failureReasonKey: null,
retryable: false,
author: { userId: "user_author", displayName: "Ada", avatar: { imageUrl: null, fallbackLabel: "A" }, isCurrentUser: false },
bodyMarkdown: "Ältere Nachricht",
bodyFormat: "markdown",
systemEvent: null,
createdAtIso: "2026-07-15T07:00:00.000Z",
updatedAtIso: "2026-07-15T07:00:00.000Z",
editedAtIso: null,
deletedAtIso: null,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: { readCount: 0, recipientCount: 2, readerUserIds: [], readerLabels: [], labelKey: "chat.message.read.none" },
pin: null,
actions: { canReact: false, canReply: false, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: false },
};
}
function createdEvent(clientMessageId = "client_remote"): ChatMessageCreatedEvent {
return {
event: CHAT_EVENT_NAMES.messageCreated,
cursor: "stream_1:2",
requestId: "request_remote",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:00:00.000Z",
data: {
message: {
id: "message_remote",
clientMessageId,
authorUserId: "user_missing",
body: "Realtime",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-15T08:00:00.000Z",
updatedAt: "2026-07-15T08:00:00.000Z",
editedAt: null,
deletedAt: null,
},
},
};
}
function readReceiptEvent(userId = viewer.userId): ChatReadReceiptEvent {
return {
event: CHAT_EVENT_NAMES.readReceipt,
cursor: "stream_1:3",
requestId: "request_read",
tenantId: "tenant_1",
chatId: "chat_1",
occurredAt: "2026-07-15T08:02:00.000Z",
data: { messageId: "message_read", userId, readAt: "2026-07-15T08:02:00.000Z" },
};
}
function localEcho(overrides: Partial<ChatLocalEcho> = {}): ChatLocalEcho {
return {
chatId: "chat_1",
requestId: "request_local",
clientMessageId: "client_local",
body: "Optimistisch",
mentions: [],
status: "sending",
failureI18nKey: null,
retryable: false,
attempts: 1,
createdAtMs: Date.parse("2026-07-15T08:01:00.000Z"),
canonicalMessage: null,
...overrides,
};
}
function createHarness() {
const calls: string[] = [];
let callbacks: ChatRealtimeClientOptions | null = null;
const callbackHistory: ChatRealtimeClientOptions[] = [];
const client: ChatRealtimeClient = {
status: "offline",
connect: vi.fn(() => calls.push("connect")),
retryNow: vi.fn(),
close: vi.fn(() => calls.push("close")),
subscribe: vi.fn((chatId, cursor) => calls.push(`subscribe:${chatId}:${cursor ?? ""}`)),
unsubscribe: vi.fn((chatId) => calls.push(`unsubscribe:${chatId}`)),
sendMessage: vi.fn((request) => localEcho({ chatId: request.chatId, body: request.body })),
restoreFailedMessage: vi.fn((request) =>
localEcho({
chatId: request.chatId,
body: request.body,
clientMessageId: request.clientMessageId,
requestId: request.requestId,
status: "failed",
failureI18nKey: request.failureI18nKey,
retryable: request.retryable,
createdAtMs: request.createdAtMs,
})
),
retryMessage: vi.fn(() => localEcho({ status: "sending" })),
discardMessage: vi.fn(() => true),
markRead: vi.fn(() => ({ requestId: "request_read", sent: true })),
setTyping: vi.fn(() => true),
setPresence: vi.fn(() => true),
ping: vi.fn(() => true),
getLocalEchoes: vi.fn(() => []),
getTyping: vi.fn(() => []),
getPresence: vi.fn(() => []),
getSubscriptions: vi.fn(() => []),
};
const clientFactory = vi.fn((options: ChatRealtimeClientOptions) => {
callbacks = options;
callbackHistory.push(options);
return client;
});
return {
calls,
client,
clientFactory,
getCallbacks: () => callbacks as ChatRealtimeClientOptions,
getCallbackHistory: () => callbackHistory,
};
}
function options(
harness: ReturnType<typeof createHarness>,
revalidate: ReturnType<typeof vi.fn>,
visibility: ChatVisibilitySource,
initialCursor = "stream_1:1",
tenantSlug = "hivegrid-demo",
chatId = "chat_1"
): UseChatChannelRealtimeInput {
return {
tenantSlug,
chatId,
initialCursor,
csrfToken: "csrf",
routing: { protocol: "https", apiHost: "api.example.test" },
initialMessages: [],
currentUser: viewer,
unknownAuthorLabel: "Unbekannt",
resolveAuthor: () => {
throw new Error("projection miss");
},
revalidate,
clientFactory: harness.clientFactory,
tokenProviderFactory: () => async () => "token",
visibility,
};
}
describe("useChatChannelRealtime", () => {
it("subscribes before connecting and reapplies a newer loader cursor without reconnecting", () => {
const harness = createHarness();
const visibility = fakeVisibility();
const revalidate = vi.fn();
const { rerender, unmount } = renderHook(({ cursor }) => useChatChannelRealtime(options(harness, revalidate, visibility, cursor)), {
initialProps: { cursor: "stream_1:1" },
});
expect(harness.calls.slice(0, 2)).toEqual(["subscribe:chat_1:stream_1:1", "connect"]);
rerender({ cursor: "stream_1:3" });
expect(harness.calls).toContain("subscribe:chat_1:stream_1:3");
expect(harness.client.connect).toHaveBeenCalledTimes(1);
unmount();
expect(harness.calls.slice(-2)).toEqual(["unsubscribe:chat_1", "close"]);
});
it("revalidates after reconnect and reset, and safely renders unknown event authors", async () => {
const harness = createHarness();
const visibility = fakeVisibility();
const revalidate = vi.fn();
const { result } = renderHook(() => useChatChannelRealtime(options(harness, revalidate, visibility)));
const callbacks = harness.getCallbacks();
act(() => {
callbacks.onStatus?.("reconnecting", { reconnectAttempt: 1, retryAtMs: 1_000 });
callbacks.onStatus?.("online", { reconnectAttempt: 0, retryAtMs: null });
callbacks.onResetRequired?.({ chatId: "chat_1", currentStreamId: "stream_2" });
expect(() => callbacks.onEvent?.(createdEvent(), { source: "live", reconciledClientMessageId: null })).not.toThrow();
});
await waitFor(() => expect(revalidate).toHaveBeenCalled());
expect(harness.client.setPresence).toHaveBeenCalledWith("online");
expect(result.current.connection.state).toBe("online");
expect(result.current.messages).toHaveLength(1);
expect(result.current.messages[0]?.author).toMatchObject({ userId: "user_missing", displayName: "Unbekannt" });
});
it("projects local echo, failure, acknowledgement and discard while delegating controls", () => {
const harness = createHarness();
const visibility = fakeVisibility();
const { result } = renderHook(() => useChatChannelRealtime(options(harness, vi.fn(), visibility)));
const callbacks = harness.getCallbacks();
act(() => callbacks.onLocalEcho?.(localEcho(), "created"));
expect(result.current.messages[0]).toMatchObject({ source: "local_echo", deliveryState: "sending" });
act(() => callbacks.onLocalEcho?.(localEcho({ status: "failed", retryable: true, failureI18nKey: "chat.errors.realtimeUnavailable" }), "updated"));
expect(result.current.messages[0]).toMatchObject({ deliveryState: "failed", failureReasonKey: "chat.errors.realtimeUnavailable" });
act(() =>
callbacks.onLocalEcho?.(
localEcho({
status: "sent",
canonicalMessage: { ...createdEvent("client_local").data.message, authorUserId: viewer.userId },
}),
"updated"
)
);
expect(result.current.messages[0]).toMatchObject({ source: "http_ack", deliveryState: "sent" });
expect(result.current.sendMessage("Neu")).not.toBeNull();
expect(harness.client.sendMessage).toHaveBeenCalledWith({ chatId: "chat_1", body: "Neu", mentions: [] });
expect(result.current.sendMessage("Retry", [], "persisted_client_1", "persisted_request_1")).not.toBeNull();
expect(harness.client.sendMessage).toHaveBeenCalledWith({
chatId: "chat_1",
body: "Retry",
mentions: [],
clientMessageId: "persisted_client_1",
requestId: "persisted_request_1",
});
expect(
result.current.restoreFailedMessage("Fehlgeschlagen", "persisted_client_2", "persisted_request_2", "chat.errors.realtimeUnavailable", true, 500)
).not.toBeNull();
expect(harness.client.restoreFailedMessage).toHaveBeenCalledWith({
chatId: "chat_1",
body: "Fehlgeschlagen",
mentions: [],
clientMessageId: "persisted_client_2",
requestId: "persisted_request_2",
failureI18nKey: "chat.errors.realtimeUnavailable",
retryable: true,
createdAtMs: 500,
});
expect(result.current.retryMessage("client_local")).not.toBeNull();
expect(result.current.discardMessage("client_local")).toBe(true);
result.current.retryConnection();
expect(harness.client.retryNow).toHaveBeenCalledOnce();
act(() => callbacks.onLocalEcho?.(localEcho(), "discarded"));
expect(result.current.messages).toEqual([]);
});
it("does not expose candidates from the previous tenant or channel scope", () => {
const harness = createHarness();
const visibility = fakeVisibility();
const revalidate = vi.fn();
const { result, rerender } = renderHook(
({ tenantSlug, chatId }) => useChatChannelRealtime(options(harness, revalidate, visibility, "stream_1:1", tenantSlug, chatId)),
{ initialProps: { tenantSlug: "tenant-one", chatId: "chat_1" } }
);
const oldCallbacks = harness.getCallbacks();
act(() => oldCallbacks.onEvent?.(createdEvent(), { source: "live", reconciledClientMessageId: null }));
expect(result.current.messages).toHaveLength(1);
rerender({ tenantSlug: "tenant-two", chatId: "chat_2" });
expect(result.current.messages).toEqual([]);
expect(result.current.typingLabels).toEqual([]);
expect(result.current.connection.state).toBe("offline");
act(() => oldCallbacks.onLocalEcho?.(localEcho(), "created"));
expect(result.current.messages).toEqual([]);
expect(harness.getCallbackHistory()).toHaveLength(2);
});
it("tracks begin/end visibility sessions before delegating exact read receipts", () => {
vi.useFakeTimers();
const harness = createHarness();
const visibility = fakeVisibility();
const { result, unmount } = renderHook(() => useChatChannelRealtime(options(harness, vi.fn(), visibility)));
act(() => {
result.current.beginMessageVisible("message_short", "2026-07-15T08:00:00.000Z");
vi.advanceTimersByTime(999);
result.current.endMessageVisible("message_short");
vi.advanceTimersByTime(5_000);
});
expect(harness.client.markRead).not.toHaveBeenCalled();
act(() => {
result.current.beginMessageVisible("message_read", "2026-07-15T08:01:00.000Z");
vi.advanceTimersByTime(3_000);
});
expect(harness.client.markRead).toHaveBeenCalledWith("chat_1", "message_read");
act(() => {
callbacksFor(harness).onStatus?.("reconnecting", { reconnectAttempt: 1, retryAtMs: 1_000 });
callbacksFor(harness).onStatus?.("online", { reconnectAttempt: 0, retryAtMs: null });
});
expect(harness.client.markRead).toHaveBeenLastCalledWith("chat_1", "message_read", "request_read");
act(() => {
callbacksFor(harness).onStatus?.("reconnecting", { reconnectAttempt: 1, retryAtMs: 1_000 });
callbacksFor(harness).onEvent?.(readReceiptEvent(), { source: "gap", reconciledClientMessageId: null });
callbacksFor(harness).onStatus?.("online", { reconnectAttempt: 0, retryAtMs: null });
});
expect(harness.client.markRead).toHaveBeenCalledTimes(2);
unmount();
vi.useRealTimers();
});
it("keeps live read aggregates on older hydrated messages across loader revalidation", () => {
const harness = createHarness();
const visibility = fakeVisibility();
const revalidate = vi.fn();
const { result, rerender } = renderHook(
({ revision }) => {
const base = options(harness, revalidate, visibility);
return useChatChannelRealtime({
...base,
initialMessages: [{ ...hydratedMessage(), updatedAtIso: `2026-07-15T07:00:0${revision}.000Z` }],
resolveAuthor: (userId) => (userId === reader.userId ? reader : null),
});
},
{ initialProps: { revision: 0 } }
);
act(() => callbacksFor(harness).onEvent?.(readReceiptEvent(reader.userId), { source: "live", reconciledClientMessageId: null }));
expect(result.current.messages[0]?.readAggregate).toMatchObject({
readCount: 1,
readerUserIds: [reader.userId],
readerLabels: [reader.displayName],
});
rerender({ revision: 1 });
expect(result.current.messages[0]?.readAggregate).toMatchObject({
readCount: 1,
readerUserIds: [reader.userId],
readerLabels: [reader.displayName],
});
});
});
function callbacksFor(harness: ReturnType<typeof createHarness>): ChatRealtimeClientOptions {
return harness.getCallbacks();
}
function fakeVisibility(): ChatVisibilitySource {
return {
visibilityState: "visible",
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
};
}
@@ -0,0 +1,363 @@
import {
CHAT_EVENT_NAMES,
createChatRealtimeClient,
isPersistentChatEvent,
type ChatLocalEcho,
type ChatMention,
type ChatRealtimeClient,
type ChatRealtimeClientOptions,
type ChatRealtimeMessage,
type ChatRemotePresence,
type ChatTokenProvider,
} from "@hivegrid/realtime";
import {
groupChatMessagesByDay,
reconcileChatMessages,
type ChatMessageActionsVM,
type ChatMessageCandidate,
type ChatResolvedAuthorVM,
} from "@hivegrid/view-models";
import { useCallback, useEffect, useMemo, useReducer, useRef } from "react";
import {
candidateFromChatEvent,
candidateFromLocalEcho,
chatChannelRealtimeReducer,
createChatRealtimeScopeKey,
createInitialChatChannelRealtimeState,
filterHydratedChatCandidates,
overlayChatReadReceipts,
safeResolveChatAuthor,
type ChatCandidateMapping,
} from "./chatChannelRealtimeReducer";
import {
createChatReadReceiptBatcher,
createChatTypingController,
type ChatInteractionScheduler,
type ChatReadReceiptBatcher,
type ChatTypingController,
type ChatVisibilitySource,
} from "./chatInteractionControllers";
import { buildChatWebSocketUrl, createChatTokenProvider, type ChatGatewayRouting, type ChatTokenFetch } from "./chatTokenProvider";
export type ChatRealtimeClientFactory = (options: ChatRealtimeClientOptions) => ChatRealtimeClient;
export type UseChatChannelRealtimeInput = {
readonly enabled?: boolean;
readonly tenantSlug: string;
readonly chatId: string;
readonly initialCursor: string;
readonly csrfToken: string | null;
readonly routing: ChatGatewayRouting;
readonly initialMessages: readonly ChatMessageCandidate[];
readonly currentUser: ChatResolvedAuthorVM;
readonly unknownAuthorLabel: string;
readonly resolveAuthor: (userId: string) => ChatResolvedAuthorVM | null | undefined;
readonly messageActions?: (message: ChatRealtimeMessage) => ChatMessageActionsVM;
readonly revalidate: () => void | Promise<void>;
readonly fetchImpl?: ChatTokenFetch;
readonly clientFactory?: ChatRealtimeClientFactory;
readonly tokenProviderFactory?: (input: {
readonly tenantSlug: string;
readonly csrfToken: string;
readonly fetchImpl?: ChatTokenFetch;
}) => ChatTokenProvider;
readonly visibility?: ChatVisibilitySource;
readonly interactionScheduler?: ChatInteractionScheduler;
};
export type UseChatChannelRealtimeResult = {
readonly connection: ReturnType<typeof createInitialChatChannelRealtimeState>["connection"];
readonly messages: ReturnType<typeof reconcileChatMessages>;
readonly messageGroups: ReturnType<typeof groupChatMessagesByDay>;
readonly typingLabels: readonly string[];
readonly presence: readonly ChatRemotePresence[];
readonly sendMessage: (body: string, mentions?: readonly ChatMention[], clientMessageId?: string, requestId?: string) => ChatLocalEcho | null;
readonly restoreFailedMessage: (
body: string,
clientMessageId: string,
requestId: string,
failureI18nKey: string,
retryable: boolean,
createdAtMs: number
) => ChatLocalEcho | null;
readonly retryMessage: (clientMessageId: string) => ChatLocalEcho | null;
readonly discardMessage: (clientMessageId: string) => boolean;
readonly updateTyping: (body: string) => void;
readonly stopTyping: () => void;
readonly beginMessageVisible: (messageId: string, createdAtIso: string) => void;
readonly endMessageVisible: (messageId: string) => void;
readonly retryConnection: () => void;
};
export function useChatChannelRealtime(input: UseChatChannelRealtimeInput): UseChatChannelRealtimeResult {
const initialScopeKey = createChatRealtimeScopeKey(input.tenantSlug, input.chatId);
const [state, dispatch] = useReducer(chatChannelRealtimeReducer, initialScopeKey, createInitialChatChannelRealtimeState);
const clientRef = useRef<ChatRealtimeClient | null>(null);
const typingRef = useRef<ChatTypingController | null>(null);
const readBatcherRef = useRef<ChatReadReceiptBatcher | null>(null);
const retryConnectionRef = useRef<(() => void) | null>(null);
const appliedCursorRef = useRef<string | null>(null);
const inputRef = useRef(input);
inputRef.current = input;
const chatId = input.chatId;
const tenantSlug = input.tenantSlug;
const csrfToken = input.csrfToken;
const enabled = input.enabled;
const apiHost = input.routing.apiHost;
const protocol = input.routing.protocol;
const scopeKey = createChatRealtimeScopeKey(tenantSlug, chatId);
const scopedState = useMemo(() => (state.scopeKey === scopeKey ? state : createInitialChatChannelRealtimeState(scopeKey)), [scopeKey, state]);
const messages = useMemo(() => {
const candidates = [...input.initialMessages, ...filterHydratedChatCandidates(input.initialMessages, scopedState.candidates)];
return reconcileChatMessages(
overlayChatReadReceipts(candidates, scopedState.readReceipts, {
currentUser: input.currentUser,
unknownAuthorLabel: input.unknownAuthorLabel,
resolveAuthor: input.resolveAuthor,
...(input.messageActions ? { messageActions: input.messageActions } : {}),
}),
{ allowPins: true }
);
}, [
input.currentUser,
input.initialMessages,
input.messageActions,
input.resolveAuthor,
input.unknownAuthorLabel,
scopedState.candidates,
scopedState.readReceipts,
]);
const messageGroups = useMemo(() => groupChatMessagesByDay(messages), [messages]);
useEffect(() => {
const setup = inputRef.current;
const active = enabled !== false && csrfToken !== null && csrfToken.trim().length > 0;
dispatch({ type: "reset", scopeKey });
appliedCursorRef.current = null;
if (!active) return;
let mounted = true;
let revalidationQueued = false;
let reconnectObserved = false;
const requestRevalidation = () => {
if (!mounted || revalidationQueued) return;
revalidationQueued = true;
queueMicrotask(() => {
revalidationQueued = false;
if (!mounted) return;
try {
void Promise.resolve(inputRef.current.revalidate()).catch(() => undefined);
} catch {
// Transport state must not be affected by a route revalidation error.
}
});
};
const mapping = (): ChatCandidateMapping => ({
currentUser: inputRef.current.currentUser,
unknownAuthorLabel: inputRef.current.unknownAuthorLabel,
resolveAuthor: inputRef.current.resolveAuthor,
...(inputRef.current.messageActions ? { messageActions: inputRef.current.messageActions } : {}),
});
const visibility = setup.visibility ?? getDocumentVisibility();
const clientFactory = setup.clientFactory ?? createChatRealtimeClient;
const tokenProviderFactory = setup.tokenProviderFactory ?? createChatTokenProvider;
let client: ChatRealtimeClient;
try {
client = clientFactory({
url: buildChatWebSocketUrl({ apiHost, protocol }),
tokenProvider: tokenProviderFactory({
tenantSlug,
csrfToken,
...(setup.fetchImpl ? { fetchImpl: setup.fetchImpl } : {}),
}),
onStatus(status, detail) {
if (!mounted) return;
dispatch({
type: "connection",
scopeKey,
connection: {
state: status,
reconnectAttempt: detail.reconnectAttempt,
retryAtIso: detail.retryAtMs === null ? null : new Date(detail.retryAtMs).toISOString(),
},
});
if (status === "reconnecting") reconnectObserved = true;
if (status === "online") {
clientRef.current?.setPresence(visibility.visibilityState === "visible" ? "online" : "away");
readBatcherRef.current?.retryPending();
if (reconnectObserved) requestRevalidation();
reconnectObserved = false;
}
},
onEvent(event) {
if (!mounted || event.chatId !== chatId) return;
if (event.event === CHAT_EVENT_NAMES.readReceipt) {
if (event.data.userId === inputRef.current.currentUser.userId) {
readBatcherRef.current?.acknowledge(event.chatId, event.data.messageId);
}
dispatch({ type: "read_receipt", scopeKey, receipt: { messageId: event.data.messageId, userId: event.data.userId } });
}
try {
const candidate = candidateFromChatEvent(event, mapping());
if (candidate) dispatch({ type: "upsert_candidate", scopeKey, candidate });
} catch {
// A stale or unknown projection must never tear down the stream.
}
if (isPersistentChatEvent(event)) requestRevalidation();
},
onLocalEcho(echo, reason) {
if (!mounted || echo.chatId !== chatId) return;
if (reason === "discarded" || reason === "evicted") {
dispatch({
type: "remove_candidate",
scopeKey,
authorUserId: inputRef.current.currentUser.userId,
clientMessageId: echo.clientMessageId,
});
return;
}
try {
dispatch({ type: "upsert_candidate", scopeKey, candidate: candidateFromLocalEcho(echo, mapping()) });
} catch {
// Invalid local timestamps or projections are ignored, not fatal.
}
},
onTyping(chatId, entries) {
if (!mounted || chatId !== setup.chatId) return;
const currentUserId = inputRef.current.currentUser.userId;
const labels = entries.filter((entry) => entry.userId !== currentUserId).map((entry) => safeResolveChatAuthor(entry.userId, mapping()).displayName);
dispatch({ type: "typing", scopeKey, labels });
},
onPresence(chatId, entries) {
if (mounted && chatId === setup.chatId) dispatch({ type: "presence", scopeKey, entries });
},
onResetRequired({ chatId }) {
if (mounted && chatId === setup.chatId) requestRevalidation();
},
});
} catch {
dispatch({ type: "connection", scopeKey, connection: { state: "blocked", reconnectAttempt: 0, retryAtIso: null } });
return;
}
clientRef.current = client;
typingRef.current = createChatTypingController({
chatId,
send: (chatId, status) => client.setTyping(chatId, status),
...(setup.interactionScheduler ? { scheduler: setup.interactionScheduler } : {}),
});
readBatcherRef.current = createChatReadReceiptBatcher({
send: (chatId, messageId, requestId) => (requestId ? client.markRead(chatId, messageId, requestId) : client.markRead(chatId, messageId)),
visibility,
...(setup.interactionScheduler ? { scheduler: setup.interactionScheduler } : {}),
});
retryConnectionRef.current = () => {
reconnectObserved = true;
client.retryNow();
};
// Subscribe before connect so the authenticate frame carries the resume cursor.
client.subscribe(chatId, setup.initialCursor);
appliedCursorRef.current = setup.initialCursor;
client.connect();
const onVisibilityChange = () => {
if (visibility.visibilityState === "visible") {
client.setPresence("online");
} else {
typingRef.current?.stop();
client.setPresence("away");
}
};
visibility.addEventListener("visibilitychange", onVisibilityChange);
return () => {
mounted = false;
visibility.removeEventListener("visibilitychange", onVisibilityChange);
typingRef.current?.dispose();
readBatcherRef.current?.dispose();
typingRef.current = null;
readBatcherRef.current = null;
retryConnectionRef.current = null;
client.unsubscribe(chatId);
client.close();
if (clientRef.current === client) clientRef.current = null;
};
}, [apiHost, chatId, csrfToken, enabled, protocol, scopeKey, tenantSlug]);
useEffect(() => {
const client = clientRef.current;
if (!client || appliedCursorRef.current === input.initialCursor) return;
client.subscribe(input.chatId, input.initialCursor);
appliedCursorRef.current = input.initialCursor;
}, [input.chatId, input.initialCursor]);
const sendMessage = useCallback((body: string, mentions: readonly ChatMention[] = [], clientMessageId?: string, requestId?: string) => {
const client = clientRef.current;
if (!client) return null;
typingRef.current?.stop();
return client.sendMessage({
chatId: inputRef.current.chatId,
body,
mentions,
...(clientMessageId ? { clientMessageId } : {}),
...(requestId ? { requestId } : {}),
});
}, []);
const restoreFailedMessage = useCallback(
(body: string, clientMessageId: string, requestId: string, failureI18nKey: string, retryable: boolean, createdAtMs: number) =>
clientRef.current?.restoreFailedMessage({
chatId: inputRef.current.chatId,
body,
mentions: [],
clientMessageId,
requestId,
failureI18nKey,
retryable,
createdAtMs,
}) ?? null,
[]
);
const retryMessage = useCallback((clientMessageId: string) => clientRef.current?.retryMessage(clientMessageId) ?? null, []);
const discardMessage = useCallback((clientMessageId: string) => clientRef.current?.discardMessage(clientMessageId) ?? false, []);
const updateTyping = useCallback((body: string) => typingRef.current?.update(body), []);
const stopTyping = useCallback(() => typingRef.current?.stop(), []);
const beginMessageVisible = useCallback((messageId: string, createdAtIso: string) => {
readBatcherRef.current?.beginVisible(inputRef.current.chatId, messageId, createdAtIso);
}, []);
const endMessageVisible = useCallback((messageId: string) => {
readBatcherRef.current?.endVisible(inputRef.current.chatId, messageId);
}, []);
const retryConnection = useCallback(() => retryConnectionRef.current?.(), []);
return {
connection: scopedState.connection,
messages,
messageGroups,
typingLabels: scopedState.typingLabels,
presence: scopedState.presence,
sendMessage,
restoreFailedMessage,
retryMessage,
discardMessage,
updateTyping,
stopTyping,
beginMessageVisible,
endMessageVisible,
retryConnection,
};
}
function getDocumentVisibility(): ChatVisibilitySource {
if (typeof document === "undefined") {
return {
visibilityState: "visible",
addEventListener: () => undefined,
removeEventListener: () => undefined,
};
}
return document;
}
@@ -0,0 +1,467 @@
// @vitest-environment jsdom
import { act, renderHook } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useChatDraft, type ChatDraftDelivery, type ChatDraftStorage } from "./useChatDraft";
const STORAGE_KEY = "chat:draft:v1:tenant:user:chat";
const PENDING_STORAGE_KEY = `${STORAGE_KEY}:pending`;
afterEach(() => {
vi.useRealTimers();
});
describe("useChatDraft", () => {
it("loads a channel-scoped draft and saves edits only after the debounce", () => {
vi.useFakeTimers();
const storage = createMemoryStorage();
storage.setItem(STORAGE_KEY, "Vorhanden");
const { result } = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries: [],
sendMessage: () => null,
updateTyping: vi.fn(),
storage,
})
);
expect(result.current).toMatchObject({ draft: "Vorhanden", loaded: true });
act(() => result.current.updateDraft("Neu"));
expect(storage.getItem(STORAGE_KEY)).toBe("Vorhanden");
act(() => vi.advanceTimersByTime(300));
expect(storage.getItem(STORAGE_KEY)).toBe("Neu");
});
it("keeps the draft when the realtime client cannot accept the send", () => {
const storage = createMemoryStorage();
const { result } = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries: [],
sendMessage: () => null,
updateTyping: vi.fn(),
storage,
})
);
act(() => result.current.updateDraft("Nicht verlieren"));
let accepted = true;
act(() => {
accepted = result.current.sendDraft("Nicht verlieren");
});
expect(accepted).toBe(false);
expect(result.current.draft).toBe("Nicht verlieren");
expect(storage.getItem(STORAGE_KEY)).toBe("Nicht verlieren");
});
it("rehydrates an unresolved send after navigation with the original correlation ids", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const sendMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const first = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
updateTyping: vi.fn(),
storage,
})
);
act(() => first.result.current.updateDraft("Ack abwarten"));
act(() => {
expect(first.result.current.sendDraft("Ack abwarten")).toBe(true);
});
expect(first.result.current.draft).toBe("");
expect(storage.getItem(STORAGE_KEY)).toBeNull();
expect(storage.getItem(PENDING_STORAGE_KEY)).not.toBeNull();
first.unmount();
const second = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
updateTyping: vi.fn(),
storage,
})
);
expect(second.result.current.draft).toBe("");
expect(sendMessage).toHaveBeenCalledTimes(2);
expect(sendMessage).toHaveBeenLastCalledWith("Ack abwarten", "client_1", "request_1");
deliveries = [{ clientMessageId: "client_1", isCurrentUser: true, deliveryState: "sent", failureReasonKey: null, retryable: false }];
second.rerender();
expect(second.result.current.draft).toBe("");
expect(storage.getItem(STORAGE_KEY)).toBeNull();
expect(storage.getItem(PENDING_STORAGE_KEY)).toBeNull();
});
it("rehydrates every older pending send without replacing a newer composer draft", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const sendMessage = vi
.fn()
.mockReturnValueOnce({ clientMessageId: "client_1", requestId: "request_1" })
.mockReturnValueOnce({ clientMessageId: "client_2", requestId: "request_2" })
.mockImplementation((_body: string, clientMessageId?: string, requestId?: string) =>
clientMessageId && requestId ? { clientMessageId, requestId } : null
);
const first = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
updateTyping: vi.fn(),
storage,
})
);
act(() => first.result.current.updateDraft("Nachricht A"));
act(() => {
expect(first.result.current.sendDraft("Nachricht A")).toBe(true);
first.result.current.updateDraft("Nachricht B");
expect(first.result.current.sendDraft("Nachricht B")).toBe(true);
first.result.current.updateDraft("Neuer Entwurf C");
});
first.unmount();
const second = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
updateTyping: vi.fn(),
storage,
})
);
expect(second.result.current.draft).toBe("Neuer Entwurf C");
expect(sendMessage).toHaveBeenNthCalledWith(3, "Nachricht A", "client_1", "request_1");
expect(sendMessage).toHaveBeenNthCalledWith(4, "Nachricht B", "client_2", "request_2");
deliveries = [
{ clientMessageId: "client_1", isCurrentUser: true, deliveryState: "sent", failureReasonKey: null, retryable: false },
{ clientMessageId: "client_2", isCurrentUser: true, deliveryState: "sent", failureReasonKey: null, retryable: false },
];
second.rerender();
expect(second.result.current.draft).toBe("Neuer Entwurf C");
expect(storage.getItem(STORAGE_KEY)).toBe("Neuer Entwurf C");
expect(storage.getItem(PENDING_STORAGE_KEY)).toBeNull();
});
it("dispatches an explicit retry for a failed echo that still belongs to the active client", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const sendMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const retryMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const hook = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
retryMessage,
updateTyping: vi.fn(),
storage,
})
);
act(() => hook.result.current.updateDraft("Direkt erneut versuchen"));
act(() => {
expect(hook.result.current.sendDraft("Direkt erneut versuchen")).toBe(true);
});
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.realtimeUnavailable",
retryable: true,
},
];
hook.rerender();
expect(hook.result.current.draft).toBe("Direkt erneut versuchen");
act(() => {
expect(hook.result.current.sendDraft("Direkt erneut versuchen")).toBe(true);
});
expect(retryMessage).toHaveBeenCalledWith("client_1");
expect(sendMessage).toHaveBeenCalledTimes(1);
expect(hook.result.current.draft).toBe("");
});
it("restores an observed failure as a local echo without sending it again", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const sendMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const first = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
updateTyping: vi.fn(),
storage,
})
);
act(() => first.result.current.updateDraft("Nicht automatisch senden"));
act(() => {
expect(first.result.current.sendDraft("Nicht automatisch senden")).toBe(true);
});
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.invalidInput",
retryable: false,
},
];
first.rerender();
first.unmount();
deliveries = [];
const restoreFailedMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const second = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries,
sendMessage,
restoreFailedMessage,
updateTyping: vi.fn(),
storage,
})
);
expect(sendMessage).toHaveBeenCalledTimes(1);
expect(restoreFailedMessage).toHaveBeenCalledWith(
"Nicht automatisch senden",
"client_1",
"request_1",
"chat.errors.invalidInput",
false,
expect.any(Number)
);
expect(second.result.current.draft).toBe("");
});
it("persists a later terminal retry failure with its new reason", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const sendMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const retryMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
const first = renderHook(() => useChatDraft({ storageKey: STORAGE_KEY, deliveries, sendMessage, retryMessage, updateTyping: vi.fn(), storage }));
act(() => first.result.current.updateDraft("Noch einmal"));
act(() => {
expect(first.result.current.sendDraft("Noch einmal")).toBe(true);
});
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.realtimeUnavailable",
retryable: true,
},
];
first.rerender();
act(() => {
expect(first.result.current.sendDraft("Noch einmal")).toBe(true);
});
deliveries = [{ clientMessageId: "client_1", isCurrentUser: true, deliveryState: "sending", failureReasonKey: null, retryable: false }];
first.rerender();
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.invalidInput",
retryable: false,
},
];
first.rerender();
first.unmount();
deliveries = [];
const restoreFailedMessage = vi.fn(() => ({ clientMessageId: "client_1", requestId: "request_1" }));
renderHook(() => useChatDraft({ storageKey: STORAGE_KEY, deliveries, sendMessage, restoreFailedMessage, updateTyping: vi.fn(), storage }));
expect(restoreFailedMessage).toHaveBeenCalledWith("Noch einmal", "client_1", "request_1", "chat.errors.invalidInput", false, expect.any(Number));
});
it("refuses a seventeenth unresolved send without dropping the sixteen pending messages", () => {
const storage = createMemoryStorage();
const now = Date.now();
storage.setItem(
PENDING_STORAGE_KEY,
JSON.stringify({
version: 2,
revision: 16,
pending: Array.from({ length: 16 }, (_, index) => ({
body: `Nachricht ${index + 1}`,
clientMessageId: `client_${index + 1}`,
requestId: `request_${index + 1}`,
createdAt: now - 16 + index,
failureObserved: false,
failureReasonKey: null,
retryable: false,
restored: false,
revision: index + 1,
})),
})
);
const sendMessage = vi.fn((_body: string, clientMessageId?: string, requestId?: string) =>
clientMessageId && requestId ? { clientMessageId, requestId } : { clientMessageId: "client_17", requestId: "request_17" }
);
const first = renderHook(() => useChatDraft({ storageKey: STORAGE_KEY, deliveries: [], sendMessage, updateTyping: vi.fn(), storage }));
act(() => first.result.current.updateDraft("Nachricht 17"));
act(() => {
expect(first.result.current.sendDraft("Nachricht 17")).toBe(false);
});
expect(first.result.current.draft).toBe("Nachricht 17");
expect(JSON.parse(storage.getItem(PENDING_STORAGE_KEY) ?? "{}").pending).toHaveLength(16);
expect(sendMessage).toHaveBeenCalledTimes(16);
first.unmount();
renderHook(() => useChatDraft({ storageKey: STORAGE_KEY, deliveries: [], sendMessage, updateTyping: vi.fn(), storage }));
expect(sendMessage).toHaveBeenCalledTimes(32);
expect(JSON.parse(storage.getItem(PENDING_STORAGE_KEY) ?? "{}").pending).toHaveLength(16);
});
it("restores a failed send across remounts and clears that restoration after acknowledgement", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const input = () => ({
storageKey: STORAGE_KEY,
deliveries,
sendMessage: () => ({ clientMessageId: "client_1", requestId: "request_1" }),
updateTyping: vi.fn(),
storage,
});
const first = renderHook(() => useChatDraft(input()));
act(() => first.result.current.updateDraft("Erneut versuchen"));
act(() => {
expect(first.result.current.sendDraft("Erneut versuchen")).toBe(true);
});
first.unmount();
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.realtimeUnavailable",
retryable: true,
},
];
const failed = renderHook(() => useChatDraft(input()));
expect(failed.result.current.draft).toBe("Erneut versuchen");
expect(storage.getItem(STORAGE_KEY)).toBe("Erneut versuchen");
failed.unmount();
const restored = renderHook(() => useChatDraft(input()));
expect(restored.result.current.draft).toBe("Erneut versuchen");
deliveries = [{ clientMessageId: "client_1", isCurrentUser: true, deliveryState: "sent", failureReasonKey: null, retryable: false }];
restored.rerender();
expect(restored.result.current.draft).toBe("");
expect(storage.getItem(STORAGE_KEY)).toBeNull();
expect(storage.getItem(PENDING_STORAGE_KEY)).toBeNull();
});
it("does not restore or clear a newer persisted draft when an older send settles", () => {
let deliveries: readonly ChatDraftDelivery[] = [];
const storage = createMemoryStorage();
const input = () => ({
storageKey: STORAGE_KEY,
deliveries,
sendMessage: () => ({ clientMessageId: "client_1", requestId: "request_1" }),
updateTyping: vi.fn(),
storage,
});
const first = renderHook(() =>
useChatDraft({
...input(),
})
);
act(() => first.result.current.updateDraft("Erste Nachricht"));
act(() => {
first.result.current.sendDraft("Erste Nachricht");
first.result.current.updateDraft("Nächster Entwurf");
});
first.unmount();
deliveries = [
{
clientMessageId: "client_1",
isCurrentUser: true,
deliveryState: "failed",
failureReasonKey: "chat.errors.realtimeUnavailable",
retryable: true,
},
];
const remounted = renderHook(() => useChatDraft(input()));
expect(remounted.result.current.draft).toBe("Nächster Entwurf");
deliveries = [{ clientMessageId: "client_1", isCurrentUser: true, deliveryState: "sent", failureReasonKey: null, retryable: false }];
remounted.rerender();
expect(remounted.result.current.draft).toBe("Nächster Entwurf");
expect(storage.getItem(STORAGE_KEY)).toBe("Nächster Entwurf");
expect(storage.getItem(PENDING_STORAGE_KEY)).toBeNull();
});
it.each([
["invalid JSON", "{not-json"],
[
"an oversized pending body",
JSON.stringify({
version: 2,
revision: 0,
pending: [
{
body: "x".repeat(8_001),
clientMessageId: "client_1",
createdAt: Date.now(),
failureObserved: false,
restored: false,
revision: 0,
},
],
}),
],
])("ignores %s without hiding a legacy plain-text draft", (_label, corruptMetadata) => {
const storage = createMemoryStorage();
storage.setItem(STORAGE_KEY, "Legacy-Entwurf");
storage.setItem(PENDING_STORAGE_KEY, corruptMetadata);
const { result } = renderHook(() =>
useChatDraft({
storageKey: STORAGE_KEY,
deliveries: [],
sendMessage: () => null,
updateTyping: vi.fn(),
storage,
})
);
expect(result.current.draft).toBe("Legacy-Entwurf");
expect(storage.getItem(PENDING_STORAGE_KEY)).toBeNull();
});
});
function createMemoryStorage(): ChatDraftStorage {
const values = new Map<string, string>();
return {
getItem: (key) => values.get(key) ?? null,
setItem: (key, value) => {
values.set(key, value);
},
removeItem: (key) => {
values.delete(key);
},
};
}
@@ -0,0 +1,494 @@
import { useCallback, useEffect, useRef, useState } from "react";
export type ChatDraftDelivery = {
readonly clientMessageId: string;
readonly isCurrentUser: boolean;
readonly deliveryState: "sending" | "sent" | "failed";
readonly failureReasonKey: string | null;
readonly retryable: boolean;
};
export type ChatDraftStorage = Pick<Storage, "getItem" | "setItem" | "removeItem">;
export type UseChatDraftInput = {
readonly storageKey: string | null;
readonly deliveries: readonly ChatDraftDelivery[];
readonly sendMessage: (body: string, clientMessageId?: string, requestId?: string) => { readonly clientMessageId: string; readonly requestId: string } | null;
readonly restoreFailedMessage?: (
body: string,
clientMessageId: string,
requestId: string,
failureReasonKey: string,
retryable: boolean,
createdAt: number
) => { readonly clientMessageId: string; readonly requestId: string } | null;
readonly retryMessage?: (clientMessageId: string) => { readonly clientMessageId: string; readonly requestId: string } | null;
readonly updateTyping: (body: string) => void;
readonly storage?: ChatDraftStorage | null;
readonly debounceMs?: number;
};
export type UseChatDraftResult = {
readonly draft: string;
readonly loaded: boolean;
readonly updateDraft: (body: string) => void;
readonly sendDraft: (body: string) => boolean;
readonly discardPendingDraft: (clientMessageId: string) => void;
};
type PendingDraft = {
readonly body: string;
readonly requestId: string;
readonly revision: number;
readonly storageKey: string;
readonly createdAt: number;
failureObserved: boolean;
failureReasonKey: string | null;
retryable: boolean;
restored: boolean;
};
type PendingSave = {
readonly handle: ReturnType<typeof setTimeout>;
readonly storage: ChatDraftStorage | null;
readonly storageKey: string;
readonly body: string;
};
const DEFAULT_DEBOUNCE_MS = 300;
const PENDING_STORAGE_SUFFIX = ":pending";
const PENDING_STORAGE_VERSION = 2;
const MAX_DRAFT_LENGTH = 8_000;
const MAX_CLIENT_MESSAGE_ID_LENGTH = 256;
const MAX_REQUEST_ID_LENGTH = 128;
const MAX_FAILURE_REASON_KEY_LENGTH = 256;
const MAX_PENDING_DRAFTS = 16;
const MAX_PENDING_STORAGE_LENGTH = 150_000;
const MAX_PENDING_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
type PersistedPendingDraft = {
readonly body: string;
readonly clientMessageId: string;
readonly requestId: string;
readonly createdAt: number;
readonly failureObserved: boolean;
readonly failureReasonKey: string | null;
readonly retryable: boolean;
readonly restored: boolean;
readonly revision: number;
};
type PersistedDraftState = {
readonly version: typeof PENDING_STORAGE_VERSION;
readonly revision: number;
readonly pending: readonly PersistedPendingDraft[];
};
/** Keeps the visible composer responsive while persisting drafts and accepted
* sends separately until their local echoes settle. */
export function useChatDraft(input: UseChatDraftInput): UseChatDraftResult {
const [draft, setDraft] = useState("");
const [loaded, setLoaded] = useState(false);
const draftRef = useRef("");
const revisionRef = useRef(0);
const pendingRef = useRef(new Map<string, PendingDraft>());
const pendingSaveRef = useRef<PendingSave | null>(null);
const inputRef = useRef(input);
inputRef.current = input;
const setDraftValue = useCallback((value: string) => {
draftRef.current = value;
setDraft(value);
}, []);
const clearPendingSave = useCallback((persist: boolean) => {
const pending = pendingSaveRef.current;
if (!pending) return;
clearTimeout(pending.handle);
pendingSaveRef.current = null;
if (persist) writeDraft(pending.storage, pending.storageKey, pending.body);
}, []);
useEffect(() => {
clearPendingSave(true);
pendingRef.current.clear();
setLoaded(false);
const storageKey = input.storageKey;
if (!storageKey) {
revisionRef.current = 0;
setDraftValue("");
setLoaded(true);
return () => clearPendingSave(true);
}
const storage = resolveStorage(input.storage);
const persisted = readPendingState(storage, storageKey);
revisionRef.current = persisted.revision;
for (const pending of persisted.pending) {
pendingRef.current.set(pending.clientMessageId, { ...pending, storageKey });
}
const rehydratedClientMessageIds = rehydratePendingMessages(
persisted,
inputRef.current.deliveries,
inputRef.current.sendMessage,
inputRef.current.restoreFailedMessage
);
let storedDraft = readDraft(storage, storageKey);
const restored = findRecoverableDraft(persisted, inputRef.current.deliveries, rehydratedClientMessageIds);
if (!storedDraft && restored) {
const pending = pendingRef.current.get(restored.clientMessageId);
if (pending && !pending.restored) {
pending.failureObserved = true;
pending.restored = true;
persistPendingState(storage, storageKey, persisted.revision, pendingRef.current);
}
storedDraft = restored.body;
writeDraft(storage, storageKey, storedDraft);
} else if (storedDraft && isStaleSentDraft(storedDraft, persisted)) {
storedDraft = "";
writeDraft(storage, storageKey, "");
}
setDraftValue(storedDraft);
setLoaded(true);
return () => clearPendingSave(true);
}, [clearPendingSave, input.storage, input.storageKey, setDraftValue]);
useEffect(() => {
for (const [clientMessageId, pending] of pendingRef.current) {
const delivery = input.deliveries.find((candidate) => candidate.isCurrentUser && candidate.clientMessageId === clientMessageId);
if (!delivery) continue;
if (delivery.deliveryState === "sending") {
if (!pending.failureObserved) continue;
const clearRestoredDraft = pending.restored && revisionRef.current === pending.revision && draftRef.current === pending.body;
pending.failureObserved = false;
pending.failureReasonKey = null;
pending.retryable = false;
pending.restored = false;
if (clearRestoredDraft) {
setDraftValue("");
writeDraft(resolveStorage(inputRef.current.storage), pending.storageKey, "");
}
persistPendingState(resolveStorage(inputRef.current.storage), pending.storageKey, revisionRef.current, pendingRef.current);
continue;
}
if (delivery.deliveryState === "failed") {
if (pending.failureObserved) continue;
pending.failureObserved = true;
pending.failureReasonKey = delivery.failureReasonKey;
pending.retryable = delivery.retryable;
if (delivery.retryable && revisionRef.current === pending.revision && draftRef.current.length === 0) {
pending.restored = true;
persistPendingState(resolveStorage(inputRef.current.storage), pending.storageKey, revisionRef.current, pendingRef.current);
setDraftValue(pending.body);
writeDraft(resolveStorage(inputRef.current.storage), pending.storageKey, pending.body);
} else {
persistPendingState(resolveStorage(inputRef.current.storage), pending.storageKey, revisionRef.current, pendingRef.current);
}
continue;
}
if (delivery.deliveryState !== "sent") continue;
if (pending.restored && revisionRef.current === pending.revision && draftRef.current === pending.body) {
setDraftValue("");
writeDraft(resolveStorage(inputRef.current.storage), pending.storageKey, "");
}
pendingRef.current.delete(clientMessageId);
persistPendingState(resolveStorage(inputRef.current.storage), pending.storageKey, revisionRef.current, pendingRef.current);
}
}, [input.deliveries, setDraftValue]);
const updateDraft = useCallback(
(body: string) => {
revisionRef.current += 1;
setDraftValue(body);
inputRef.current.updateTyping(body);
clearPendingSave(false);
const storageKey = inputRef.current.storageKey;
if (!storageKey) return;
const delay = normalizeDebounce(inputRef.current.debounceMs);
const storage = resolveStorage(inputRef.current.storage);
persistPendingState(storage, storageKey, revisionRef.current, pendingRef.current);
const handle = setTimeout(() => {
const pending = pendingSaveRef.current;
if (!pending || pending.handle !== handle) return;
pendingSaveRef.current = null;
writeDraft(pending.storage, pending.storageKey, pending.body);
}, delay);
pendingSaveRef.current = { handle, storage, storageKey, body };
},
[clearPendingSave, setDraftValue]
);
const sendDraft = useCallback(
(body: string): boolean => {
const storageKey = inputRef.current.storageKey;
if (!storageKey) return false;
clearPendingSave(false);
writeDraft(resolveStorage(inputRef.current.storage), storageKey, body);
const restored = findPendingRetry(pendingRef.current, revisionRef.current, body);
if (!restored && pendingRef.current.size >= MAX_PENDING_DRAFTS) return false;
const failedInCurrentClient =
restored !== null &&
inputRef.current.deliveries.some(
(delivery) => delivery.isCurrentUser && delivery.clientMessageId === restored.clientMessageId && delivery.deliveryState === "failed"
);
const echo = failedInCurrentClient
? (inputRef.current.retryMessage?.(restored.clientMessageId) ?? null)
: inputRef.current.sendMessage(body, restored?.clientMessageId, restored?.requestId);
if (!echo) return false;
const storage = resolveStorage(inputRef.current.storage);
if (isValidClientMessageId(echo.clientMessageId) && isValidDraft(body)) {
pendingRef.current.set(echo.clientMessageId, {
body,
requestId: echo.requestId,
revision: revisionRef.current,
storageKey,
createdAt: Date.now(),
failureObserved: false,
failureReasonKey: null,
retryable: false,
restored: false,
});
persistPendingState(storage, storageKey, revisionRef.current, pendingRef.current);
}
setDraftValue("");
writeDraft(storage, storageKey, "");
return true;
},
[clearPendingSave, setDraftValue]
);
const discardPendingDraft = useCallback((clientMessageId: string) => {
const pending = pendingRef.current.get(clientMessageId);
if (!pending) return;
pendingRef.current.delete(clientMessageId);
persistPendingState(resolveStorage(inputRef.current.storage), pending.storageKey, revisionRef.current, pendingRef.current);
}, []);
return { draft, loaded, updateDraft, sendDraft, discardPendingDraft };
}
function resolveStorage(storage: ChatDraftStorage | null | undefined): ChatDraftStorage | null {
if (storage !== undefined) return storage;
return typeof window === "undefined" ? null : window.localStorage;
}
function readDraft(storage: ChatDraftStorage | null, storageKey: string): string {
try {
const draft = storage?.getItem(storageKey) ?? "";
if (isValidDraft(draft)) return draft;
storage?.removeItem(storageKey);
return "";
} catch {
return "";
}
}
function writeDraft(storage: ChatDraftStorage | null, storageKey: string, draft: string): void {
try {
if (draft && isValidDraft(draft)) storage?.setItem(storageKey, draft);
else storage?.removeItem(storageKey);
} catch {
// Local persistence must never block delivery or composer input.
}
}
function normalizeDebounce(value: number | undefined): number {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : DEFAULT_DEBOUNCE_MS;
}
function pendingStorageKey(storageKey: string): string {
return `${storageKey}${PENDING_STORAGE_SUFFIX}`;
}
function readPendingState(storage: ChatDraftStorage | null, storageKey: string): PersistedDraftState {
const empty = emptyPendingState();
try {
const key = pendingStorageKey(storageKey);
const raw = storage?.getItem(key);
if (!raw) return empty;
if (raw.length > MAX_PENDING_STORAGE_LENGTH) {
storage?.removeItem(key);
return empty;
}
const parsed: unknown = JSON.parse(raw);
if (!isRecord(parsed) || parsed.version !== PENDING_STORAGE_VERSION || !isRevision(parsed.revision) || !Array.isArray(parsed.pending)) {
storage?.removeItem(key);
return empty;
}
const now = Date.now();
const pending: PersistedPendingDraft[] = [];
const seen = new Set<string>();
for (const candidate of parsed.pending) {
const normalized = normalizePersistedPending(candidate, parsed.revision, now);
if (!normalized || seen.has(normalized.clientMessageId)) continue;
seen.add(normalized.clientMessageId);
pending.push(normalized);
}
pending.sort((left, right) => left.createdAt - right.createdAt);
const bounded = pending.slice(-MAX_PENDING_DRAFTS);
const state: PersistedDraftState = { version: PENDING_STORAGE_VERSION, revision: parsed.revision, pending: bounded };
if (bounded.length === 0 || bounded.length !== parsed.pending.length) {
persistPendingState(storage, storageKey, state.revision, toPendingMap(state, storageKey));
}
return state;
} catch {
try {
storage?.removeItem(pendingStorageKey(storageKey));
} catch {
// Corrupt or inaccessible local persistence must not block the composer.
}
return empty;
}
}
function persistPendingState(storage: ChatDraftStorage | null, storageKey: string, revision: number, pendingDrafts: ReadonlyMap<string, PendingDraft>): void {
try {
const key = pendingStorageKey(storageKey);
const pending = [...pendingDrafts.entries()]
.filter(([, candidate]) => candidate.storageKey === storageKey)
.sort(([, left], [, right]) => left.createdAt - right.createdAt)
.slice(-MAX_PENDING_DRAFTS)
.map(([clientMessageId, candidate]) => ({
body: candidate.body,
clientMessageId,
requestId: candidate.requestId,
createdAt: candidate.createdAt,
failureObserved: candidate.failureObserved,
failureReasonKey: candidate.failureReasonKey,
retryable: candidate.retryable,
restored: candidate.restored,
revision: candidate.revision,
}));
if (pending.length === 0) {
storage?.removeItem(key);
return;
}
const serialized = JSON.stringify({ version: PENDING_STORAGE_VERSION, revision, pending } satisfies PersistedDraftState);
if (serialized.length <= MAX_PENDING_STORAGE_LENGTH) storage?.setItem(key, serialized);
else storage?.removeItem(key);
} catch {
// Local persistence must never block delivery or composer input.
}
}
function normalizePersistedPending(candidate: unknown, currentRevision: number, now: number): PersistedPendingDraft | null {
if (!isRecord(candidate)) return null;
if (!isValidClientMessageId(candidate.clientMessageId) || !isValidDraft(candidate.body)) return null;
if (!isValidRequestId(candidate.requestId)) return null;
if (!isRevision(candidate.revision) || candidate.revision > currentRevision) return null;
if (!isTimestamp(candidate.createdAt, now)) return null;
if (typeof candidate.failureObserved !== "boolean" || typeof candidate.restored !== "boolean") return null;
if (candidate.failureReasonKey !== null && !isValidFailureReasonKey(candidate.failureReasonKey)) return null;
if (typeof candidate.retryable !== "boolean") return null;
if (!candidate.failureObserved && (candidate.failureReasonKey !== null || candidate.retryable)) return null;
if (candidate.restored && !candidate.failureObserved) return null;
return {
body: candidate.body,
clientMessageId: candidate.clientMessageId,
requestId: candidate.requestId,
createdAt: candidate.createdAt,
failureObserved: candidate.failureObserved,
failureReasonKey: candidate.failureReasonKey,
retryable: candidate.retryable,
restored: candidate.restored,
revision: candidate.revision,
};
}
function emptyPendingState(): PersistedDraftState {
return { version: PENDING_STORAGE_VERSION, revision: 0, pending: [] };
}
function rehydratePendingMessages(
state: PersistedDraftState,
deliveries: readonly ChatDraftDelivery[],
sendMessage: UseChatDraftInput["sendMessage"],
restoreFailedMessage: UseChatDraftInput["restoreFailedMessage"]
): ReadonlySet<string> {
const rehydrated = new Set<string>();
for (const pending of state.pending) {
const alreadyVisible = deliveries.some((delivery) => delivery.isCurrentUser && delivery.clientMessageId === pending.clientMessageId);
if (alreadyVisible) continue;
const echo = pending.failureObserved
? (restoreFailedMessage?.(
pending.body,
pending.clientMessageId,
pending.requestId,
pending.failureReasonKey ?? "chat.message.sendFailed",
pending.retryable,
pending.createdAt
) ?? null)
: sendMessage(pending.body, pending.clientMessageId, pending.requestId);
if (echo?.clientMessageId === pending.clientMessageId && echo.requestId === pending.requestId) {
rehydrated.add(pending.clientMessageId);
}
}
return rehydrated;
}
function findRecoverableDraft(
state: PersistedDraftState,
deliveries: readonly ChatDraftDelivery[],
rehydratedClientMessageIds: ReadonlySet<string>
): PersistedPendingDraft | null {
return (
[...state.pending]
.reverse()
.find(
(pending) =>
!rehydratedClientMessageIds.has(pending.clientMessageId) &&
pending.revision === state.revision &&
(pending.restored || !deliveries.some((delivery) => delivery.isCurrentUser && delivery.clientMessageId === pending.clientMessageId))
) ?? null
);
}
function findPendingRetry(
pendingDrafts: ReadonlyMap<string, PendingDraft>,
revision: number,
body: string
): { readonly clientMessageId: string; readonly requestId: string } | null {
const match = [...pendingDrafts.entries()].reverse().find(([, pending]) => pending.restored && pending.revision === revision && pending.body === body);
return match ? { clientMessageId: match[0], requestId: match[1].requestId } : null;
}
function isStaleSentDraft(draft: string, state: PersistedDraftState): boolean {
return state.pending.some((pending) => !pending.restored && pending.revision === state.revision && pending.body === draft);
}
function toPendingMap(state: PersistedDraftState, storageKey: string): Map<string, PendingDraft> {
return new Map(state.pending.map((pending) => [pending.clientMessageId, { ...pending, storageKey }]));
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isRevision(value: unknown): value is number {
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
}
function isTimestamp(value: unknown, now: number): value is number {
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 && value <= now && value >= now - MAX_PENDING_AGE_MS;
}
function isValidClientMessageId(value: unknown): value is string {
return typeof value === "string" && value.length > 0 && value.length <= MAX_CLIENT_MESSAGE_ID_LENGTH;
}
function isValidRequestId(value: unknown): value is string {
return typeof value === "string" && value.length > 0 && value.length <= MAX_REQUEST_ID_LENGTH && /^[A-Za-z0-9][A-Za-z0-9._:~-]*$/.test(value);
}
function isValidFailureReasonKey(value: unknown): value is string {
return typeof value === "string" && value.length > 0 && value.length <= MAX_FAILURE_REASON_KEY_LENGTH;
}
function isValidDraft(value: unknown): value is string {
return typeof value === "string" && value.length <= MAX_DRAFT_LENGTH;
}
@@ -0,0 +1,267 @@
// @vitest-environment jsdom
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { type ChatViewportMessage, useChatMessageViewport } from "./useChatMessageViewport";
type ScrollMetrics = {
scrollTop: number;
scrollHeight: number;
clientHeight: number;
};
type ViewportHarness = {
readonly logRoot: HTMLDivElement;
readonly main: HTMLElement;
readonly metrics: ScrollMetrics;
readonly scrollTo: ReturnType<typeof vi.fn>;
readonly dispatchScroll: () => void;
};
const remoteMessage = (key: string): ChatViewportMessage => ({ key, isCurrentUser: false });
const ownMessage = (key: string): ChatViewportMessage => ({ key, isCurrentUser: true });
beforeEach(() => {
sessionStorage.clear();
vi.stubGlobal(
"matchMedia",
vi.fn(() => ({
matches: false,
media: "(prefers-reduced-motion: reduce)",
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
);
});
afterEach(() => {
document.body.replaceChildren();
vi.unstubAllGlobals();
});
describe("useChatMessageViewport", () => {
it("places the initial message log at the document end without animation", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
const { result } = renderHook(() => useChatMessageViewport({ messages: [remoteMessage("message_1")] }));
act(() => result.current.logRootRef(harness.logRoot));
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 700, behavior: "auto" });
expect(harness.metrics.scrollTop).toBe(700);
expect(result.current.latestRemoteAnnouncementKey).toBeNull();
expect(result.current.newMessageCount).toBe(0);
});
it("restores and persists a tenant-user-channel scroll position", () => {
const storageKey = "hivegrid:chat:scroll:v1:demo:user-1:chat-1";
sessionStorage.setItem(storageKey, JSON.stringify({ scrollTop: 240, nearBottom: false }));
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
const { result, unmount } = renderHook(() => useChatMessageViewport({ messages: [remoteMessage("message_1")], storageKey }));
act(() => result.current.logRootRef(harness.logRoot));
expect(harness.scrollTo).not.toHaveBeenCalled();
expect(harness.metrics.scrollTop).toBe(240);
act(() => {
harness.metrics.scrollTop = 320;
harness.dispatchScroll();
});
unmount();
expect(JSON.parse(sessionStorage.getItem(storageKey) ?? "null")).toEqual({ scrollTop: 320, nearBottom: false });
});
it("announces the first remote message that arrives after an initially empty channel", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 300, clientHeight: 300 });
let messages: readonly ChatViewportMessage[] = [];
const { result, rerender } = renderHook(() => useChatMessageViewport({ messages }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
harness.metrics.scrollHeight = 400;
messages = [remoteMessage("message_remote")];
rerender();
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 100, behavior: "smooth" });
expect(result.current.latestRemoteAnnouncementKey).toBe("message_remote");
harness.metrics.scrollHeight = 500;
messages = [...messages, ownMessage("message_own")];
rerender();
expect(result.current.latestRemoteAnnouncementKey).toBeNull();
});
it("preserves the visual anchor when older messages are prepended", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
let messages = [remoteMessage("message_2"), remoteMessage("message_3")];
const { result, rerender } = renderHook(() => useChatMessageViewport({ messages }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
act(() => {
harness.metrics.scrollTop = 200;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_400;
messages = [remoteMessage("message_1"), ...messages];
rerender();
expect(harness.metrics.scrollTop).toBe(600);
expect(harness.scrollTo).not.toHaveBeenCalled();
});
it("auto-scrolls a remote append only when the viewport was near the end", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
let messages = [remoteMessage("message_1")];
const { result, rerender } = renderHook(() => useChatMessageViewport({ messages }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
act(() => {
harness.metrics.scrollTop = 695;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_100;
messages = [...messages, remoteMessage("message_2")];
rerender();
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 800, behavior: "smooth" });
expect(result.current.latestRemoteAnnouncementKey).toBe("message_2");
expect(result.current.newMessageCount).toBe(0);
harness.scrollTo.mockClear();
act(() => {
harness.metrics.scrollTop = 100;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_200;
messages = [...messages, remoteMessage("message_3")];
rerender();
expect(harness.scrollTo).not.toHaveBeenCalled();
expect(result.current.latestRemoteAnnouncementKey).toBeNull();
expect(result.current.newMessageCount).toBe(1);
});
it("always follows an appended local echo and clears a pending remote count", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
let messages = [remoteMessage("message_1")];
const { result, rerender } = renderHook(() => useChatMessageViewport({ messages }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
act(() => {
harness.metrics.scrollTop = 100;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_100;
messages = [...messages, remoteMessage("message_2")];
rerender();
expect(result.current.newMessageCount).toBe(1);
harness.metrics.scrollHeight = 1_200;
messages = [...messages, ownMessage("local_echo_1")];
rerender();
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 900, behavior: "smooth" });
expect(result.current.latestRemoteAnnouncementKey).toBeNull();
expect(result.current.newMessageCount).toBe(0);
});
it("jumps to pending messages and also clears their count after a manual scroll to the end", () => {
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
let messages = [remoteMessage("message_1")];
const { result, rerender } = renderHook(() => useChatMessageViewport({ messages }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
act(() => {
harness.metrics.scrollTop = 100;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_100;
messages = [...messages, remoteMessage("message_2")];
rerender();
expect(result.current.newMessageCount).toBe(1);
act(() => result.current.jumpToLatest());
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 800, behavior: "smooth" });
expect(result.current.newMessageCount).toBe(0);
act(() => {
harness.metrics.scrollTop = 100;
harness.dispatchScroll();
});
harness.metrics.scrollHeight = 1_200;
messages = [...messages, remoteMessage("message_3")];
rerender();
expect(result.current.newMessageCount).toBe(1);
act(() => {
harness.metrics.scrollTop = 900;
harness.dispatchScroll();
});
expect(result.current.newMessageCount).toBe(0);
});
it("uses immediate scrolling when reduced motion is requested", () => {
vi.stubGlobal(
"matchMedia",
vi.fn(() => ({
matches: true,
media: "(prefers-reduced-motion: reduce)",
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}))
);
const harness = createViewportHarness({ scrollTop: 0, scrollHeight: 1_000, clientHeight: 300 });
const { result } = renderHook(() => useChatMessageViewport({ messages: [remoteMessage("message_1")] }));
act(() => result.current.logRootRef(harness.logRoot));
harness.scrollTo.mockClear();
act(() => result.current.jumpToLatest());
expect(harness.scrollTo).toHaveBeenCalledWith({ top: 700, behavior: "auto" });
});
});
function createViewportHarness(initialMetrics: ScrollMetrics): ViewportHarness {
const main = document.createElement("main");
const logRoot = document.createElement("div");
const metrics = { ...initialMetrics };
const scrollTo = vi.fn((options: ScrollToOptions) => {
if (typeof options.top === "number") metrics.scrollTop = options.top;
});
Object.defineProperties(main, {
scrollTop: {
configurable: true,
get: () => metrics.scrollTop,
set: (value: number) => {
metrics.scrollTop = value;
},
},
scrollHeight: { configurable: true, get: () => metrics.scrollHeight },
clientHeight: { configurable: true, get: () => metrics.clientHeight },
scrollTo: { configurable: true, value: scrollTo },
});
main.append(logRoot);
document.body.append(main);
return {
logRoot,
main,
metrics,
scrollTo,
dispatchScroll: () => main.dispatchEvent(new Event("scroll")),
};
}
@@ -0,0 +1,218 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
export type ChatViewportMessage = {
readonly key: string;
readonly isCurrentUser: boolean;
};
export type UseChatMessageViewportInput = {
readonly messages: readonly ChatViewportMessage[];
readonly nearBottomThresholdPx?: number;
readonly storageKey?: string;
};
export type UseChatMessageViewportResult = {
readonly logRootRef: (node: HTMLElement | null) => void;
readonly latestRemoteAnnouncementKey: string | null;
readonly newMessageCount: number;
readonly jumpToLatest: () => void;
};
type ViewportSnapshot = {
readonly container: HTMLElement;
readonly keys: readonly string[];
readonly scrollHeight: number;
readonly scrollTop: number;
readonly nearBottom: boolean;
};
const DEFAULT_NEAR_BOTTOM_THRESHOLD_PX = 96;
export function useChatMessageViewport(input: UseChatMessageViewportInput): UseChatMessageViewportResult {
const [logRoot, setLogRoot] = useState<HTMLElement | null>(null);
const [latestRemoteAnnouncementKey, setLatestRemoteAnnouncementKey] = useState<string | null>(null);
const [newMessageCount, setNewMessageCount] = useState(0);
const snapshotRef = useRef<ViewportSnapshot | null>(null);
const messagesRef = useRef(input.messages);
messagesRef.current = input.messages;
const thresholdPx = normalizeThreshold(input.nearBottomThresholdPx);
const messageSignature = useMemo(
() => input.messages.map((message) => `${message.key.length}:${message.key}:${message.isCurrentUser ? "1" : "0"}`).join("|"),
[input.messages]
);
const scrollContainer = useMemo(() => resolveScrollContainer(logRoot), [logRoot]);
useLayoutEffect(() => {
if (!scrollContainer) return;
const messages = messagesRef.current;
const nextKeys = messages.map((message) => message.key);
const previousSnapshot = snapshotRef.current;
const previous = previousSnapshot?.container === scrollContainer ? previousSnapshot : null;
let commandedBottom = false;
if (!previous) {
const stored = readStoredViewport(input.storageKey);
if (stored && !stored.nearBottom) {
scrollContainer.scrollTop = Math.min(stored.scrollTop, Math.max(0, scrollContainer.scrollHeight - scrollContainer.clientHeight));
} else {
scrollToBottom(scrollContainer, "auto");
commandedBottom = true;
}
setLatestRemoteAnnouncementKey(null);
setNewMessageCount(0);
} else {
const sequenceIndex = findSequenceIndex(nextKeys, previous.keys);
if (sequenceIndex >= 0) {
const prependedCount = sequenceIndex;
const appendedMessages = messages.slice(sequenceIndex + previous.keys.length);
if (prependedCount > 0) {
const heightDelta = scrollContainer.scrollHeight - previous.scrollHeight;
scrollContainer.scrollTop = previous.scrollTop + heightDelta;
}
if (appendedMessages.length > 0) {
const ownMessageAppended = appendedMessages.some((message) => message.isCurrentUser);
const latestRemoteMessage = appendedMessages
.slice()
.reverse()
.find((message) => !message.isCurrentUser);
if (ownMessageAppended || previous.nearBottom) {
scrollToBottom(scrollContainer, preferredMotionBehavior());
commandedBottom = true;
setLatestRemoteAnnouncementKey(latestRemoteMessage?.key ?? null);
setNewMessageCount(0);
} else {
setLatestRemoteAnnouncementKey(null);
setNewMessageCount((current) => current + appendedMessages.length);
}
}
}
}
snapshotRef.current = {
container: scrollContainer,
keys: nextKeys,
scrollHeight: scrollContainer.scrollHeight,
scrollTop: scrollContainer.scrollTop,
nearBottom: commandedBottom || isNearBottom(scrollContainer, thresholdPx),
};
}, [input.storageKey, messageSignature, scrollContainer, thresholdPx]);
useEffect(() => {
if (!scrollContainer) return;
const onScroll = () => {
const nearBottom = isNearBottom(scrollContainer, thresholdPx);
const current = snapshotRef.current;
if (current) {
snapshotRef.current = {
...current,
container: scrollContainer,
scrollHeight: scrollContainer.scrollHeight,
scrollTop: scrollContainer.scrollTop,
nearBottom,
};
}
if (nearBottom) setNewMessageCount(0);
persistViewport(input.storageKey, scrollContainer.scrollTop, nearBottom);
};
scrollContainer.addEventListener("scroll", onScroll, { passive: true });
return () => {
scrollContainer.removeEventListener("scroll", onScroll);
persistViewport(input.storageKey, scrollContainer.scrollTop, isNearBottom(scrollContainer, thresholdPx));
};
}, [input.storageKey, scrollContainer, thresholdPx]);
const jumpToLatest = useCallback(() => {
const container = resolveScrollContainer(logRoot);
if (!container) return;
scrollToBottom(container, preferredMotionBehavior());
const current = snapshotRef.current;
if (current) {
snapshotRef.current = {
...current,
container,
scrollHeight: container.scrollHeight,
scrollTop: container.scrollTop,
nearBottom: true,
};
}
setNewMessageCount(0);
persistViewport(input.storageKey, container.scrollTop, true);
}, [input.storageKey, logRoot]);
return {
logRootRef: setLogRoot,
latestRemoteAnnouncementKey,
newMessageCount,
jumpToLatest,
};
}
function resolveScrollContainer(logRoot: HTMLElement | null): HTMLElement | null {
if (!logRoot) return null;
const nearestMain = logRoot.closest("main");
if (nearestMain instanceof HTMLElement) return nearestMain;
if (typeof document === "undefined") return null;
return document.scrollingElement instanceof HTMLElement ? document.scrollingElement : null;
}
function scrollToBottom(container: HTMLElement, behavior: ScrollBehavior): void {
const top = Math.max(0, container.scrollHeight - container.clientHeight);
if (typeof container.scrollTo === "function") {
container.scrollTo({ top, behavior });
return;
}
container.scrollTop = top;
}
function isNearBottom(container: HTMLElement, thresholdPx: number): boolean {
return container.scrollHeight - container.clientHeight - container.scrollTop <= thresholdPx;
}
function findSequenceIndex(nextKeys: readonly string[], previousKeys: readonly string[]): number {
if (previousKeys.length === 0) return 0;
const lastStart = nextKeys.length - previousKeys.length;
for (let start = 0; start <= lastStart; start += 1) {
let matches = true;
for (let offset = 0; offset < previousKeys.length; offset += 1) {
if (nextKeys[start + offset] !== previousKeys[offset]) {
matches = false;
break;
}
}
if (matches) return start;
}
return -1;
}
function preferredMotionBehavior(): ScrollBehavior {
if (typeof matchMedia !== "function") return "smooth";
return matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth";
}
function normalizeThreshold(value: number | undefined): number {
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : DEFAULT_NEAR_BOTTOM_THRESHOLD_PX;
}
type StoredViewport = Readonly<{ scrollTop: number; nearBottom: boolean }>;
function readStoredViewport(storageKey: string | undefined): StoredViewport | null {
if (!storageKey || typeof sessionStorage === "undefined") return null;
try {
const parsed = JSON.parse(sessionStorage.getItem(storageKey) ?? "null") as Partial<StoredViewport> | null;
if (!parsed || typeof parsed.scrollTop !== "number" || !Number.isFinite(parsed.scrollTop) || typeof parsed.nearBottom !== "boolean") {
return null;
}
return { scrollTop: Math.max(0, parsed.scrollTop), nearBottom: parsed.nearBottom };
} catch {
return null;
}
}
function persistViewport(storageKey: string | undefined, scrollTop: number, nearBottom: boolean): void {
if (!storageKey || typeof sessionStorage === "undefined") return;
try {
sessionStorage.setItem(storageKey, JSON.stringify({ scrollTop: Math.max(0, scrollTop), nearBottom } satisfies StoredViewport));
} catch {
// Private mode or a full storage quota must never break chat scrolling.
}
}
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import { buildChatMessageDiscoveryVM } from "@hivegrid/view-models";
import { mergeChatMessageDiscoveryPages } from "./ChatMessageDiscoveryRouteView";
const hrefs = { chat: "/demo/chat", search: "/demo/chat/search", mentions: "/demo/chat/mentions" } as const;
function row(id: string) {
return {
id,
chatId: "chat_1",
channelKind: "group" as const,
channelTitle: "Montage",
authorLabel: "Ada Lovelace",
authorAvatar: { imageUrl: null, fallbackLabel: "AL" },
body: `Message ${id}`,
createdAtIso: "2026-07-16T11:00:00.000Z",
detailHref: `/demo/chat/chat_1?message=${id}`,
isThreadReply: false,
};
}
describe("chat message discovery pagination", () => {
it("appends cursor pages once and keeps the incoming next cursor", () => {
const first = buildChatMessageDiscoveryVM({ mode: "search", query: "heat", rows: [row("m2")], nextCursor: "cursor_2", hrefs });
const second = buildChatMessageDiscoveryVM({
mode: "search",
query: "heat",
rows: [row("m2"), row("m1")],
nextCursor: null,
hrefs,
});
const merged = mergeChatMessageDiscoveryPages(first, second);
expect(merged.status === "ready" && merged.data.rows.map(({ id }) => id)).toEqual(["m2", "m1"]);
expect(merged.status === "ready" && merged.data.nextCursor).toBeNull();
});
it("does not mix pages from different queries", () => {
const first = buildChatMessageDiscoveryVM({ mode: "search", query: "heat", rows: [row("m2")], hrefs });
const other = buildChatMessageDiscoveryVM({ mode: "search", query: "solar", rows: [row("m1")], hrefs });
expect(mergeChatMessageDiscoveryPages(first, other)).toEqual(other);
});
});
@@ -0,0 +1,108 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useFetcher, useNavigate, useRevalidator } from "react-router";
import type { ChatMessageDiscoveryData, ChatMessageDiscoveryVM } from "@hivegrid/view-models";
import { ChatMessageDiscoveryPage } from "~/components/screens/chat/ChatMessageDiscoveryPage";
import type { ChatMessageDiscoveryLoaderData } from "./chatMessageDiscoveryRouteTypes";
const QUERY_DEBOUNCE_MS = 250;
export function ChatMessageDiscoveryRouteView({ data }: { readonly data: ChatMessageDiscoveryLoaderData }) {
const navigate = useNavigate();
const revalidator = useRevalidator();
const pageFetcher = useFetcher<ChatMessageDiscoveryLoaderData>();
const requestedCursor = useRef<string | null>(null);
const queryTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const [display, setDisplay] = useState<{ readonly source: ChatMessageDiscoveryVM; readonly vm: ChatMessageDiscoveryVM }>({
source: data.vm,
vm: data.vm,
});
useEffect(() => {
requestedCursor.current = null;
setDisplay({ source: data.vm, vm: data.vm });
}, [data.vm]);
useEffect(() => {
if (pageFetcher.state !== "idle" || !requestedCursor.current || !pageFetcher.data) return;
const requested = requestedCursor.current;
requestedCursor.current = null;
if (pageFetcher.data.pageCursor !== requested || !sameDiscovery(data.vm, pageFetcher.data.vm)) return;
setDisplay((current) => ({ source: data.vm, vm: mergePages(current.source === data.vm ? current.vm : data.vm, pageFetcher.data!.vm) }));
}, [data.vm, pageFetcher.data, pageFetcher.state]);
useEffect(
() => () => {
if (queryTimer.current) clearTimeout(queryTimer.current);
},
[]
);
const vm = display.source === data.vm ? display.vm : data.vm;
const navigateToQuery = useCallback(
(query: string) => {
const params = new URLSearchParams();
const normalized = query.trim().slice(0, 200);
if (normalized) params.set("q", normalized);
void navigate(`${discoveryBasePath(data.vm)}${params.size ? `?${params.toString()}` : ""}`, { replace: true });
},
[data.vm, navigate]
);
return (
<ChatMessageDiscoveryPage
vm={vm}
actions={{
onBack: (href) => void navigate(href),
onSwitchMode: (href) => void navigate(href),
onOpenResult: (row) => void navigate(row.detailHref),
onQueryChange: (query) => {
setDisplay((current) => ({ source: current.source, vm: withQuery(current.source, query) }));
if (queryTimer.current) clearTimeout(queryTimer.current);
queryTimer.current = setTimeout(() => {
queryTimer.current = null;
navigateToQuery(query);
}, QUERY_DEBOUNCE_MS);
},
onLoadMore: (cursor) => {
if (pageFetcher.state !== "idle" || requestedCursor.current) return;
requestedCursor.current = cursor;
const ready = readyData(vm);
const params = new URLSearchParams({ cursor });
if (ready?.mode === "search" && ready.query) params.set("q", ready.query);
void pageFetcher.load(`${discoveryBasePath(vm)}?${params.toString()}`);
},
onRetry: () => revalidator.revalidate(),
}}
/>
);
}
export function mergeChatMessageDiscoveryPages(current: ChatMessageDiscoveryVM, incoming: ChatMessageDiscoveryVM): ChatMessageDiscoveryVM {
if (!sameDiscovery(current, incoming) || current.status !== "ready" || incoming.status !== "ready") return incoming;
const rows = new Map(current.data.rows.map((row) => [row.id, row]));
for (const row of incoming.data.rows) rows.set(row.id, row);
return { ...incoming, data: { ...incoming.data, rows: [...rows.values()] } };
}
function mergePages(current: ChatMessageDiscoveryVM, incoming: ChatMessageDiscoveryVM): ChatMessageDiscoveryVM {
return mergeChatMessageDiscoveryPages(current, incoming);
}
function sameDiscovery(left: ChatMessageDiscoveryVM, right: ChatMessageDiscoveryVM): boolean {
return left.status === "ready" && right.status === "ready" && left.data.mode === right.data.mode && left.data.query === right.data.query;
}
function withQuery(vm: ChatMessageDiscoveryVM, query: string): ChatMessageDiscoveryVM {
if (vm.status !== "ready" || vm.data.mode !== "search") return vm;
if (query === vm.data.query) return vm;
return { ...vm, data: { ...vm.data, query, rows: [], nextCursor: null } };
}
function discoveryBasePath(vm: ChatMessageDiscoveryVM): string {
const data = readyData(vm);
return data?.mode === "mentions" ? (data.hrefs.mentions) : (data?.hrefs.search ?? "");
}
function readyData(vm: ChatMessageDiscoveryVM): ChatMessageDiscoveryData | null {
return vm.status === "ready" ? vm.data : null;
}
@@ -0,0 +1,140 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { CatalogError } from "@hivegrid/foundation";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
const mocks = vi.hoisted(() => ({
requireAuth: vi.fn(),
getTenantIdFromUrl: vi.fn(),
getUserInfo: vi.fn(),
tenantHasModule: vi.fn(),
getPermissionsByUser: vi.fn(),
membership: { id: "tenant-user-1" } as { id: string } | null,
tx: {
tenantUser: {
findFirst: vi.fn(),
},
},
}));
vi.mock("~/utils/loaders.middleware", () => ({ requireAuth: (...args: unknown[]) => mocks.requireAuth(...args) }));
vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: (...args: unknown[]) => mocks.getTenantIdFromUrl(...args) }));
vi.mock("~/utils/session.server", () => ({ getUserInfo: (...args: unknown[]) => mocks.getUserInfo(...args) }));
vi.mock("~/utils/connector/tenantConnector.server", () => ({ tenantHasModule: (...args: unknown[]) => mocks.tenantHasModule(...args) }));
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({ getPermissionsByUser: (...args: unknown[]) => mocks.getPermissionsByUser(...args) }));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: (_tenantId: string, callback: (tx: typeof mocks.tx) => Promise<unknown>) => callback(mocks.tx),
}));
import {
chatHasPermission,
loadChatContext,
requireChatChannelAdminAccess,
requireChatChannelReadAccess,
requireChatChannelWriteAccess,
requireChatPermission,
type ChatChannelAccessSnapshot,
type ChatRouteContext,
} from "./chatAccess.server";
const activeMember: ChatChannelAccessSnapshot = {
isActiveMember: true,
isChannelAdmin: false,
isArchived: false,
};
function context(permissions: readonly string[]): ChatRouteContext {
return {
tenantId: "tenant-1",
userId: "user-1",
tenantUserId: "tenant-user-1",
permissions,
hasModule: true,
};
}
describe("chat access", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.requireAuth.mockResolvedValue(undefined);
mocks.getTenantIdFromUrl.mockResolvedValue("tenant-1");
mocks.getUserInfo.mockResolvedValue({ userId: "user-1" });
mocks.tenantHasModule.mockResolvedValue(true);
mocks.getPermissionsByUser.mockResolvedValue([CHAT_PERMISSIONS.readOwnChannels]);
mocks.tx.tenantUser.findFirst.mockImplementation(async () => mocks.membership);
mocks.membership = { id: "tenant-user-1" };
});
it("loads an authenticated, tenant-scoped module context", async () => {
const request = new Request("http://app.localhost/acme/chat");
await expect(loadChatContext({ request, params: { tenant: "acme" } })).resolves.toEqual({
tenantId: "tenant-1",
userId: "user-1",
tenantUserId: "tenant-user-1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
hasModule: true,
});
expect(mocks.tenantHasModule).toHaveBeenCalledWith({ tenantId: "tenant-1", userId: "user-1", moduleKey: "chat" });
expect(mocks.tx.tenantUser.findFirst).toHaveBeenCalledWith({
where: {
tenantId: "tenant-1",
userId: "user-1",
status: TenantUserStatus.ACTIVE,
user: { active: true },
tenant: { active: true },
},
select: { id: true },
});
});
it("fails closed when the chat module is disabled", async () => {
mocks.tenantHasModule.mockResolvedValue(false);
const request = new Request("http://app.localhost/acme/chat");
await expect(loadChatContext({ request, params: { tenant: "acme" } })).rejects.toBeInstanceOf(CatalogError);
});
it("rejects a session without an active tenant membership", async () => {
mocks.membership = null;
await expect(loadChatContext({ request: new Request("http://app.localhost/acme/chat"), params: { tenant: "acme" } })).rejects.toBeInstanceOf(CatalogError);
});
it("requires exact permissions without making chat.admin an audit capability", () => {
const admin = context([CHAT_PERMISSIONS.admin]);
expect(chatHasPermission(admin, CHAT_PERMISSIONS.admin)).toBe(true);
expect(chatHasPermission(admin, CHAT_PERMISSIONS.readAllChannels)).toBe(false);
expect(() => requireChatPermission(admin, CHAT_PERMISSIONS.readAllChannels)).toThrow(CatalogError);
});
it("allows active members to read and keeps audit reads behind the dedicated audit-session service", () => {
expect(requireChatChannelReadAccess(context([CHAT_PERMISSIONS.readOwnChannels]), activeMember)).toBe("member");
const outsider = { ...activeMember, isActiveMember: false };
expect(() => requireChatChannelReadAccess(context([CHAT_PERMISSIONS.readAllChannels]), outsider)).toThrow(CatalogError);
expect(() => requireChatChannelReadAccess(context([CHAT_PERMISSIONS.admin]), outsider)).toThrow(CatalogError);
});
it("never lets audit mode or archived membership write", () => {
const auditOnly = context([CHAT_PERMISSIONS.readAllChannels]);
expect(() => requireChatChannelWriteAccess(auditOnly, { ...activeMember, isActiveMember: false })).toThrow(CatalogError);
expect(() => requireChatChannelWriteAccess(context([CHAT_PERMISSIONS.write]), { ...activeMember, isArchived: true })).toThrow(CatalogError);
expect(requireChatChannelWriteAccess(context([CHAT_PERMISSIONS.write]), activeMember)).toMatchObject({ userId: "user-1" });
});
it("allows channel admins only as members while global chat admins override membership", () => {
expect(requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.readOwnChannels]), { ...activeMember, isChannelAdmin: true })).toMatchObject({
userId: "user-1",
});
expect(requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.readOwnChannels, CHAT_PERMISSIONS.admin]), activeMember)).toMatchObject({
userId: "user-1",
});
expect(
requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.admin]), {
...activeMember,
isActiveMember: false,
})
).toMatchObject({ userId: "user-1" });
expect(() => requireChatChannelAdminAccess(context([CHAT_PERMISSIONS.readOwnChannels]), activeMember)).toThrow(CatalogError);
});
});
@@ -0,0 +1,108 @@
import { CHAT_PERMISSIONS, type ChatPermission } from "@hivegrid/chat";
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { getUserInfo } from "~/utils/session.server";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { CHAT_MODULE_KEY } from "./chatRoutePaths";
export type ChatRouteContext = {
tenantId: string;
userId: string;
tenantUserId: string;
permissions: readonly string[];
hasModule: true;
};
export type ChatChannelAccessSnapshot = {
isActiveMember: boolean;
isChannelAdmin: boolean;
isArchived: boolean;
};
export type ChatChannelReadMode = "member";
export async function loadChatContext({ request, params }: { request: Request; params: Record<string, string | undefined> }): Promise<ChatRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions, membership] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: CHAT_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
withTenantRLS(tenantId, (tx) =>
tx.tenantUser.findFirst({
where: {
tenantId,
userId: userInfo.userId,
status: TenantUserStatus.ACTIVE,
user: { active: true },
tenant: { active: true },
},
select: { id: true },
})
),
]);
if (!membership || !hasModule) {
throw new CatalogError(foundationErrors.notFound, !hasModule ? { module: CHAT_MODULE_KEY } : undefined);
}
return {
tenantId,
userId: userInfo.userId,
tenantUserId: membership.id,
permissions,
hasModule: true,
};
}
export function chatHasPermission(ctx: ChatRouteContext, permission: ChatPermission): boolean {
return ctx.permissions.includes(permission);
}
export function requireChatPermission(ctx: ChatRouteContext, permission: ChatPermission): ChatRouteContext {
if (!chatHasPermission(ctx, permission)) {
throw new CatalogError(foundationErrors.notFound, { permission });
}
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, permission);
return ctx;
}
export function requireChatChannelReadAccess(ctx: ChatRouteContext, channel: ChatChannelAccessSnapshot): ChatChannelReadMode {
if (channel.isActiveMember && chatHasPermission(ctx, CHAT_PERMISSIONS.readOwnChannels)) {
return "member";
}
throw new CatalogError(foundationErrors.notFound, { chat: "not-visible" });
}
export function requireChatChannelWriteAccess(ctx: ChatRouteContext, channel: ChatChannelAccessSnapshot): ChatRouteContext {
if (channel.isActiveMember && !channel.isArchived && chatHasPermission(ctx, CHAT_PERMISSIONS.write)) {
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, CHAT_PERMISSIONS.write);
return ctx;
}
throw new CatalogError(foundationErrors.notFound, { chat: "not-writable" });
}
export function requireChatChannelAdminAccess(ctx: ChatRouteContext, channel: ChatChannelAccessSnapshot): ChatRouteContext {
if (chatHasPermission(ctx, CHAT_PERMISSIONS.admin)) {
requirePermission({ tenantId: ctx.tenantId, userId: ctx.userId, permissions: ctx.permissions }, CHAT_PERMISSIONS.admin);
return ctx;
}
if (channel.isActiveMember && channel.isChannelAdmin && chatHasPermission(ctx, CHAT_PERMISSIONS.readOwnChannels)) {
return ctx;
}
throw new CatalogError(foundationErrors.notFound, { chat: "not-administerable" });
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import {
chatChannelListFilterHref,
chatChannelListPageHref,
normalizeChatChannelQuery,
parseChatChannelListCursor,
parseChatChannelListFilter,
} from "./chatListFilter";
describe("chat list filter", () => {
it("parses supported filters and rejects unknown views", () => {
expect(parseChatChannelListFilter(new URL("https://app.test/demo/chat?q=%20Montage%20&view=unread&archived=1"))).toEqual({
query: "Montage",
view: "unread",
showArchived: true,
});
expect(parseChatChannelListFilter(new URL("https://app.test/demo/chat?view=admin"))).toEqual({
query: "",
view: "all",
showArchived: false,
});
});
it("serializes only non-default filter state", () => {
expect(chatChannelListFilterHref("demo", { query: "", view: "all", showArchived: false })).toBe("/demo/chat");
expect(chatChannelListFilterHref("demo", { query: "Ada", view: "direct", showArchived: true })).toBe("/demo/chat?q=Ada&view=direct&archived=1");
});
it("round-trips a page cursor while filter navigation resets it", () => {
const filter = { query: "Ada", view: "direct" as const, showArchived: true };
const href = chatChannelListPageHref("demo", filter, "cursor.page_2");
const url = new URL(href, "https://app.test");
expect(parseChatChannelListCursor(url)).toBe("cursor.page_2");
expect(chatChannelListFilterHref("demo", filter)).toBe("/demo/chat?q=Ada&view=direct&archived=1");
expect(chatChannelListFilterHref("demo", parseChatChannelListFilter(url))).not.toContain("cursor");
});
it("treats an empty page cursor as absent", () => {
expect(parseChatChannelListCursor(new URL("https://app.test/demo/chat?cursor=%20%20"))).toBeUndefined();
});
it("uses the same bounded query normalization for local and URL state", () => {
expect(normalizeChatChannelQuery(" Montage ")).toBe("Montage");
expect(normalizeChatChannelQuery("x".repeat(250))).toHaveLength(200);
});
});
@@ -0,0 +1,40 @@
import { chatChannelListViewSchema, type ChatChannelListFilterState } from "@hivegrid/view-models";
const MAX_CHANNEL_QUERY_LENGTH = 200;
const MAX_CHANNEL_CURSOR_LENGTH = 2_048;
export function parseChatChannelListFilter(url: URL): ChatChannelListFilterState {
const parsedView = chatChannelListViewSchema.safeParse(url.searchParams.get("view") ?? "all");
const showArchivedValue = url.searchParams.get("archived");
return {
query: normalizeChatChannelQuery(url.searchParams.get("q") ?? ""),
view: parsedView.success ? parsedView.data : "all",
showArchived: showArchivedValue === "1" || showArchivedValue === "true",
};
}
export function normalizeChatChannelQuery(query: string): string {
return query.trim().slice(0, MAX_CHANNEL_QUERY_LENGTH);
}
export function chatChannelListFilterHref(tenantSlug: string, filter: ChatChannelListFilterState): string {
return chatChannelListPageHref(tenantSlug, filter);
}
export function parseChatChannelListCursor(url: URL): string | undefined {
const cursor = url.searchParams.get("cursor")?.trim();
if (!cursor) return undefined;
return cursor.slice(0, MAX_CHANNEL_CURSOR_LENGTH);
}
export function chatChannelListPageHref(tenantSlug: string, filter: ChatChannelListFilterState, cursor?: string): string {
const params = new URLSearchParams();
const query = normalizeChatChannelQuery(filter.query);
if (query) params.set("q", query);
if (filter.view !== "all") params.set("view", filter.view);
if (filter.showArchived) params.set("archived", "1");
const normalizedCursor = cursor?.trim().slice(0, MAX_CHANNEL_CURSOR_LENGTH);
if (normalizedCursor) params.set("cursor", normalizedCursor);
const search = params.toString();
return `/${encodeURIComponent(tenantSlug)}/chat${search ? `?${search}` : ""}`;
}
@@ -0,0 +1,86 @@
import { buildChatChannelListVM, type ChatChannelListFilterState, type ChatChannelListRowInput } from "@hivegrid/view-models";
import { describe, expect, it } from "vitest";
import { mergeChatChannelListPages, sameChatChannelListFilter } from "./chatListPagination";
const DEFAULT_FILTER: ChatChannelListFilterState = { query: "", view: "all", showArchived: false };
function row(id: string, unreadCount: number): ChatChannelListRowInput {
return {
id,
kind: "group",
title: id,
subtitle: null,
detailHref: `/demo/chat/${id}`,
avatar: { imageUrl: null, fallbackLabel: id.slice(0, 1) },
project: null,
lastMessage: null,
typingLabels: [],
unreadCount,
hasMention: unreadCount > 1,
isPinned: false,
isPrivate: false,
notificationPreference: "all_messages",
archivedAtIso: null,
memberCount: 2,
canManage: false,
};
}
function page(rows: readonly ChatChannelListRowInput[], nextCursor: string | null, filter = DEFAULT_FILTER) {
return buildChatChannelListVM({
rows,
discoverRows: [],
filter,
permissions: {
canWrite: false,
canCreateGroup: false,
canCreateDm: false,
canDiscover: false,
canViewMentions: false,
canSearch: true,
canViewArchived: true,
canAdmin: false,
},
hrefs: {
newChannel: "/demo/chat/new",
newDm: "/demo/chat/new?kind=dm",
search: "/demo/chat/search",
mentions: "/demo/chat/mentions",
archived: "/demo/chat?archived=1",
},
totals: {
unread: rows.reduce((total, entry) => total + entry.unreadCount, 0),
mentions: rows.filter((entry) => entry.hasMention).length,
},
nextCursor,
});
}
describe("chat list pagination", () => {
it("appends in server order, refreshes duplicate boundary rows, and adopts the incoming cursor", () => {
const merged = mergeChatChannelListPages(page([row("chat_1", 1), row("chat_2", 0)], "cursor_2"), page([row("chat_2", 3), row("chat_3", 2)], null));
expect(merged.status).toBe("ready");
if (merged.status !== "ready") return;
expect(merged.data.rows.map((entry) => [entry.id, entry.unreadCount])).toEqual([
["chat_1", 1],
["chat_2", 3],
["chat_3", 2],
]);
expect(merged.data.totals).toEqual({ unread: 6, mentions: 2 });
expect(merged.data.nextCursor).toBeNull();
});
it("resets to the incoming page when the normalized server filter changes", () => {
const unreadFilter = { ...DEFAULT_FILTER, view: "unread" as const };
const reset = mergeChatChannelListPages(page([row("chat_old", 1)], "old_cursor"), page([row("chat_new", 2)], "new_cursor", unreadFilter));
expect(sameChatChannelListFilter(DEFAULT_FILTER, unreadFilter)).toBe(false);
expect(reset.status).toBe("ready");
if (reset.status !== "ready") return;
expect(reset.data.rows.map((entry) => entry.id)).toEqual(["chat_new"]);
expect(reset.data.filter).toEqual(unreadFilter);
expect(reset.data.nextCursor).toBe("new_cursor");
});
});
@@ -0,0 +1,29 @@
import type { ChatChannelListFilterState, ChatChannelListRowVM, ChatChannelListVM } from "@hivegrid/view-models";
export function sameChatChannelListFilter(left: ChatChannelListFilterState, right: ChatChannelListFilterState): boolean {
return left.query === right.query && left.view === right.view && left.showArchived === right.showArchived;
}
/** Appends one server-filtered keyset page without changing the server order.
* Repeated boundary rows are refreshed in place and never rendered twice. */
export function mergeChatChannelListPages(current: ChatChannelListVM, incoming: ChatChannelListVM): ChatChannelListVM {
if (incoming.status !== "ready") return current;
if (current.status !== "ready" || !sameChatChannelListFilter(current.data.filter, incoming.data.filter)) return incoming;
const rowsById = new Map<string, ChatChannelListRowVM>(current.data.rows.map((row) => [row.id, row]));
for (const row of incoming.data.rows) rowsById.set(row.id, row);
const rows = [...rowsById.values()];
return {
...current,
data: {
...current.data,
rows,
totals: {
unread: rows.reduce((total, row) => total + row.unreadCount, 0),
mentions: rows.filter((row) => row.hasMention).length,
},
nextCursor: incoming.data.nextCursor,
},
};
}
@@ -0,0 +1,67 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { buildChatMessageDiscoveryVM } from "@hivegrid/view-models";
const mocks = vi.hoisted(() => ({
getTranslations: vi.fn(),
loadContext: vi.fn(),
loadDiscovery: vi.fn(),
}));
vi.mock("~/locale/i18next.server", () => ({ getTranslations: (...args: unknown[]) => mocks.getTranslations(...args) }));
vi.mock("./chatAccess.server", () => ({ loadChatContext: (...args: unknown[]) => mocks.loadContext(...args) }));
vi.mock("~/modules/chat/services/ChatMessageDiscoveryService.server", () => ({
loadChatMessageDiscovery: (...args: unknown[]) => mocks.loadDiscovery(...args),
}));
import { loadChatMessageDiscoveryRoute } from "./chatMessageDiscoveryLoader.server";
const context = {
tenantId: "tenant_1",
userId: "viewer_1",
tenantUserId: "tenant_user_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
hasModule: true,
} as const;
const hrefs = { chat: "/demo/chat", search: "/demo/chat/search", mentions: "/demo/chat/mentions" } as const;
describe("chat message discovery route loader", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.getTranslations.mockResolvedValue({ t: (key: string) => `t:${key}` });
mocks.loadContext.mockResolvedValue(context);
mocks.loadDiscovery.mockResolvedValue(buildChatMessageDiscoveryVM({ mode: "search", query: "heat", rows: [], hrefs }));
});
it("normalizes search query and forwards the opaque cursor", async () => {
const request = new Request("http://app.localhost:3000/demo/chat/search?q=%20heat%20&cursor=cursor_1");
const result = await loadChatMessageDiscoveryRoute({ request, params: { tenant: "demo" }, context: {} } as never, "search");
expect(mocks.loadDiscovery).toHaveBeenCalledWith({
context,
tenantSlug: "demo",
mode: "search",
query: "heat",
beforeCursor: "cursor_1",
limit: 30,
labels: {
directMessage: "t:chat.channel.fallback.directMessage",
unnamedGroup: "t:chat.channel.fallback.group",
unnamedProject: "t:chat.channel.fallback.project",
unknownUser: "t:chat.participant.unknown",
},
});
expect(result.pageCursor).toBe("cursor_1");
expect(result.title).toContain("t:chat.messageDiscovery.search.title");
});
it("keeps mentions query-free even when the URL contains q", async () => {
mocks.loadDiscovery.mockResolvedValue(buildChatMessageDiscoveryVM({ mode: "mentions", rows: [], hrefs }));
const request = new Request("http://app.localhost:3000/demo/chat/mentions?q=ignored");
await loadChatMessageDiscoveryRoute({ request, params: { tenant: "demo" }, context: {} } as never, "mentions");
expect(mocks.loadDiscovery).toHaveBeenCalledWith(expect.not.objectContaining({ query: expect.anything() }));
});
});
@@ -0,0 +1,50 @@
import type { LoaderFunctionArgs } from "react-router";
import type { ChatMessageDiscoveryMode } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { loadChatMessageDiscovery } from "~/modules/chat/services/ChatMessageDiscoveryService.server";
import { loadChatContext } from "./chatAccess.server";
import type { ChatMessageDiscoveryLoaderData } from "./chatMessageDiscoveryRouteTypes";
const PAGE_LIMIT = 30;
export async function loadChatMessageDiscoveryRoute(
args: LoaderFunctionArgs,
mode: ChatMessageDiscoveryMode
): Promise<ChatMessageDiscoveryLoaderData> {
const [{ t }, context] = await Promise.all([getTranslations(args.request), loadChatContext(args)]);
const url = new URL(args.request.url);
const tenantSlug = args.params.tenant ?? "";
const pageCursor = normalizeCursor(url.searchParams.get("cursor"));
const query = mode === "search" ? normalizeQuery(url.searchParams.get("q")) : undefined;
const vm = await loadChatMessageDiscovery({
context,
tenantSlug,
mode,
...(query !== undefined ? { query } : {}),
...(pageCursor ? { beforeCursor: pageCursor } : {}),
limit: PAGE_LIMIT,
labels: {
directMessage: t("chat.channel.fallback.directMessage"),
unnamedGroup: t("chat.channel.fallback.group"),
unnamedProject: t("chat.channel.fallback.project"),
unknownUser: t("chat.participant.unknown"),
},
});
return {
title: `${t(mode === "search" ? "chat.messageDiscovery.search.title" : "chat.messageDiscovery.mentions.title")} | ${process.env.APP_NAME}`,
tenantSlug,
pageCursor,
vm,
};
}
function normalizeQuery(value: string | null): string {
return (value ?? "").trim().slice(0, 200);
}
function normalizeCursor(value: string | null): string | null {
const normalized = value?.trim() ?? "";
return normalized ? normalized.slice(0, 2_048) : null;
}
@@ -0,0 +1,8 @@
import type { ChatMessageDiscoveryVM } from "@hivegrid/view-models";
export type ChatMessageDiscoveryLoaderData = Readonly<{
title: string;
tenantSlug: string;
pageCursor: string | null;
vm: ChatMessageDiscoveryVM;
}>;
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import {
CHAT_MODULE_KEY,
chatArchivedPath,
chatAuditAttachmentPath,
chatAuditPath,
chatChannelInfoPath,
chatChannelPath,
chatChannelSettingsPath,
chatFilesPath,
chatIndexPath,
chatMentionsPath,
chatNewPath,
chatNotFoundResponse,
chatPinnedPath,
chatSearchPath,
chatThreadPath,
} from "./chatRoutePaths";
describe("chat route paths", () => {
it("uses the canonical chat module key and tenant-scoped collection paths", () => {
expect(CHAT_MODULE_KEY).toBe("chat");
expect(chatIndexPath("acme")).toBe("/acme/chat");
expect(chatNewPath("acme")).toBe("/acme/chat/new");
expect(chatMentionsPath("acme")).toBe("/acme/chat/mentions");
expect(chatSearchPath("acme")).toBe("/acme/chat/search");
expect(chatArchivedPath("acme")).toBe("/acme/chat/archived");
});
it("builds channel, thread, pin, and file paths without changing identifiers", () => {
expect(chatChannelPath("acme", "chat_1")).toBe("/acme/chat/chat_1");
expect(chatChannelSettingsPath("acme", "chat_1")).toBe("/acme/chat/chat_1/settings");
expect(chatChannelInfoPath("acme", "chat_1")).toBe("/acme/chat/chat_1/info");
expect(chatThreadPath("acme", "chat_1", "thread_1")).toBe("/acme/chat/chat_1/thread/thread_1");
expect(chatPinnedPath("acme", "chat_1")).toBe("/acme/chat/chat_1/pinned");
expect(chatFilesPath("acme", "chat_1")).toBe("/acme/chat/chat_1/files");
});
it("uses the compliance hub for audit screens while keeping the published attachment endpoint stable", () => {
expect(chatAuditPath("acme")).toBe("/acme/settings/compliance/chat");
expect(chatAuditAttachmentPath("acme", "chat/1", "file/1", "preview")).toBe(
"/acme/settings/chat/audit/chat%2F1/attachments/file%2F1/preview"
);
});
it("provides the standard opaque not-found response", async () => {
const response = chatNotFoundResponse();
expect(response.status).toBe(404);
expect(await response.text()).toBe("Not Found");
});
});
@@ -0,0 +1,62 @@
export const CHAT_MODULE_KEY = "chat";
export function chatIndexPath(tenantSlug: string): string {
return `/${tenantSlug}/chat`;
}
export function chatNewPath(tenantSlug: string): string {
return `/${tenantSlug}/chat/new`;
}
export function chatMentionsPath(tenantSlug: string): string {
return `/${tenantSlug}/chat/mentions`;
}
export function chatSearchPath(tenantSlug: string): string {
return `/${tenantSlug}/chat/search`;
}
export function chatArchivedPath(tenantSlug: string): string {
return `/${tenantSlug}/chat/archived`;
}
export function chatChannelPath(tenantSlug: string, chatId: string): string {
return `/${tenantSlug}/chat/${chatId}`;
}
export function chatChannelSettingsPath(tenantSlug: string, chatId: string): string {
return `/${tenantSlug}/chat/${chatId}/settings`;
}
export function chatChannelInfoPath(tenantSlug: string, chatId: string): string {
return `/${tenantSlug}/chat/${chatId}/info`;
}
export function chatThreadPath(tenantSlug: string, chatId: string, threadId: string): string {
return `/${tenantSlug}/chat/${chatId}/thread/${threadId}`;
}
export function chatPinnedPath(tenantSlug: string, chatId: string): string {
return `/${tenantSlug}/chat/${chatId}/pinned`;
}
export function chatFilesPath(tenantSlug: string, chatId: string): string {
return `/${tenantSlug}/chat/${chatId}/files`;
}
export function chatAuditPath(tenantSlug: string): string {
return `/${tenantSlug}/settings/compliance/chat`;
}
export function chatAuditAttachmentPath(
tenantSlug: string,
chatId: string,
fileId: string,
variant: "original" | "preview"
): string {
return `/${tenantSlug}/settings/chat/audit/${encodeURIComponent(chatId)}/attachments/${encodeURIComponent(fileId)}/${variant}`;
}
export function chatNotFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
@@ -0,0 +1,293 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
listChannels: vi.fn(),
getDetail: vi.fn(),
getAdministration: vi.fn(),
recordSession: vi.fn(),
archiveChannel: vi.fn(),
setMemberRole: vi.fn(),
removeMember: vi.fn(),
getAttachment: vi.fn(),
}));
vi.mock("@hivegrid/chat/audit.server", () => ({
listChatAuditChannels: mocks.listChannels,
getChatAuditChannelDetail: mocks.getDetail,
getChatAuditAdministration: mocks.getAdministration,
recordChatAuditSessionStarted: mocks.recordSession,
forceArchiveChatAuditChannel: mocks.archiveChannel,
forceSetChatAuditMemberRole: mocks.setMemberRole,
forceRemoveChatAuditMember: mocks.removeMember,
getChatAuditAttachmentDownload: mocks.getAttachment,
}));
import {
archiveChatAuditChannel,
loadChatAuditChannel,
loadChatAuditAttachment,
loadChatAuditOverview,
removeChatAuditMember,
setChatAuditMemberRole,
startChatAuditSession,
} from "./ChatAuditService.server";
const context = {
tenantId: "tenant-1",
userId: "admin-1",
tenantUserId: "tenant-user-1",
permissions: ["chat.read_all_channels"],
hasModule: true as const,
};
const session = {
id: "session-1",
tenantId: "tenant-1",
userId: "admin-1",
reason: "Kundenreklamation prüfen",
issuedAt: Date.parse("2026-07-16T10:00:00.000Z"),
expiresAt: Date.parse("2026-07-16T10:15:00.000Z"),
};
const labels = {
directMessage: "Direktnachricht",
unnamedGroup: "Gruppe",
unnamedProject: "Projekt",
unknownUser: "Unbekannt",
unknownMention: "Unbekannte Erwähnung",
};
describe("AK-P15b chat audit service", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.listChannels.mockResolvedValue([]);
mocks.getAdministration.mockResolvedValue({
channel: { id: "dm-1", kind: "dm", archivedAtIso: null },
canAdminister: true,
members: [
{ userId: "user-a", displayName: "Anna Adler", avatarUrl: null, roleInChat: "admin" },
{ userId: "user-b", displayName: "Ben Bauer", avatarUrl: null, roleInChat: "member" },
],
});
});
it("does not load tenant channels before a justified session exists", async () => {
const vm = await loadChatAuditOverview({ context, tenantSlug: "demo", session: null, labels });
expect(mocks.listChannels).not.toHaveBeenCalled();
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.requiresReason).toBe(true);
});
it("audits the overview read with the active reason session", async () => {
const vm = await loadChatAuditOverview({
context,
tenantSlug: "demo",
session,
requestId: "overview-read-1",
labels,
});
expect(mocks.listChannels).toHaveBeenCalledWith(
expect.objectContaining({
requestId: "overview-read-1",
auditSession: expect.objectContaining({
sessionId: "session-1",
reason: "Kundenreklamation prüfen",
}),
})
);
expect(vm.status).toBe("ready");
});
it("records the session reason with the canonical read-all permission boundary", async () => {
await startChatAuditSession({ context, session, requestId: "request-1" });
expect(mocks.recordSession).toHaveBeenCalledWith({
tenantId: "tenant-1",
userId: "admin-1",
permissions: ["chat.read_all_channels"],
requestId: "request-1",
auditSession: {
sessionId: "session-1",
reason: "Kundenreklamation prüfen",
expiresAtIso: "2026-07-16T10:15:00.000Z",
},
});
});
it("renders direct messages with the mandatory audit banner and no write affordance", async () => {
mocks.getDetail.mockResolvedValue(detailFixture());
const result = await loadChatAuditChannel({
context,
tenantSlug: "demo",
chatId: "dm-1",
session,
requestId: "open-1",
labels,
});
expect(mocks.getDetail).toHaveBeenCalledWith(expect.objectContaining({ tenantId: "tenant-1", chatId: "dm-1" }));
if (result.vm.status !== "ready") throw new Error("expected ready");
expect(result.vm.data.header).toMatchObject({
isAuditMode: true,
dmAuditBannerKey: "chat.audit.dmBanner",
title: "Anna Adler · Ben Bauer",
canManage: false,
settingsHref: null,
});
expect(result.vm.data.composer).toMatchObject({ enabled: false, canSend: false, disabledReasonKey: "chat.composer.auditReadOnly" });
expect(result.vm.data.messages[0]?.actions).toEqual({
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
});
expect(result.vm.data.messages[0]?.attachments[0]).toMatchObject({
downloadHref: "/demo/settings/chat/audit/dm-1/attachments/file-1/original",
previewHref: "/demo/settings/chat/audit/dm-1/attachments/file-1/preview",
});
if (result.administrationVm.status !== "ready") throw new Error("expected ready");
expect(result.administrationVm.data).toMatchObject({ canAdminister: true, canArchive: true });
});
it("keeps attachment delivery inside the active audit session", async () => {
mocks.getAttachment.mockResolvedValue({ fileId: "file-1", storageKey: "tenant/file-1" });
await loadChatAuditAttachment({
context,
chatId: "dm-1",
fileId: "file-1",
variant: "original",
session,
requestId: "download-1",
});
expect(mocks.getAttachment).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant-1",
userId: "admin-1",
chatId: "dm-1",
fileId: "file-1",
variant: "original",
requestId: "download-1",
auditSession: expect.objectContaining({ sessionId: "session-1", reason: session.reason }),
})
);
});
it("routes cleanup and force-member mutations through both admin permissions and the active reason", async () => {
const adminContext = { ...context, permissions: ["chat.read_own_channels", "chat.read_all_channels", "chat.admin"] };
await archiveChatAuditChannel({ context: adminContext, chatId: "dm-1", session, requestId: "archive-1" });
await setChatAuditMemberRole({
context: adminContext,
chatId: "dm-1",
memberUserId: "user-b",
roleInChat: "admin",
session,
requestId: "role-1",
});
await removeChatAuditMember({
context: adminContext,
chatId: "dm-1",
memberUserId: "user-b",
session,
requestId: "remove-1",
});
const reasonContext = {
tenantId: "tenant-1",
permissions: adminContext.permissions,
};
expect(mocks.archiveChannel).toHaveBeenCalledWith(
expect.objectContaining({
...reasonContext,
requestId: "archive-1",
auditSession: expect.objectContaining({ sessionId: "session-1", reason: "Kundenreklamation prüfen" }),
})
);
expect(mocks.setMemberRole).toHaveBeenCalledWith(
expect.objectContaining({
...reasonContext,
memberUserId: "user-b",
roleInChat: "admin",
requestId: "role-1",
auditSession: expect.objectContaining({ sessionId: "session-1", reason: "Kundenreklamation prüfen" }),
})
);
expect(mocks.removeMember).toHaveBeenCalledWith(
expect.objectContaining({
...reasonContext,
memberUserId: "user-b",
requestId: "remove-1",
auditSession: expect.objectContaining({ sessionId: "session-1", reason: "Kundenreklamation prüfen" }),
})
);
});
});
function detailFixture() {
return {
channel: {
id: "dm-1",
kind: "dm",
name: null,
description: null,
projektId: null,
isPrivate: true,
archivedAtIso: null,
lastMessageAtIso: "2026-07-16T09:00:00.000Z",
eventStreamId: "stream-1",
eventCursor: "stream-1:1",
member: {
roleInChat: "member",
notificationPreference: "muted",
lastReadMessageId: null,
lastReadAtIso: null,
isPinned: false,
canWrite: false,
},
memberCount: 2,
participants: [
{ userId: "user-a", displayName: "Anna Adler", avatarUrl: null },
{ userId: "user-b", displayName: "Ben Bauer", avatarUrl: null },
],
unreadCount: 0,
hasUnreadMention: false,
lastMessage: null,
},
messages: [
{
id: "message-1",
clientMessageId: "client-1",
authorUserId: "user-a",
body: "Vertrauliche Nachricht",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [],
attachmentIds: ["file-1"],
linkPreviews: [],
createdAt: "2026-07-16T09:00:00.000Z",
updatedAt: "2026-07-16T09:00:00.000Z",
editedAt: null,
deletedAt: null,
},
],
readReceipts: [],
messageFeatures: [],
attachments: [
{
messageId: "message-1",
fileId: "file-1",
displayName: "foto.png",
mimeType: "image/png",
sizeBytes: 42,
linkRole: "image",
previewStatus: "ready",
scanStatus: "clean",
},
],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream-1:1",
};
}
@@ -0,0 +1,290 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import {
forceArchiveChatAuditChannel,
forceRemoveChatAuditMember,
forceSetChatAuditMemberRole,
getChatAuditAdministration,
getChatAuditAttachmentDownload,
getChatAuditChannelDetail,
listChatAuditChannels,
recordChatAuditSessionStarted,
type ChatAuditAttachmentDownload,
type ChatAuditAttachmentVariant,
} from "@hivegrid/chat/audit.server";
import {
buildChatAuditAdministrationVM,
buildChatAuditOverviewVM,
buildChatChannelDetailVM,
type ChatAuditAdministrationVM,
type ChatAuditOverviewVM,
type ChatChannelDetailVM,
type ChatResolvedAuthorVM,
} from "@hivegrid/view-models";
import { requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
import { chatAuditAttachmentPath, chatAuditPath } from "../routes/chatRoutePaths";
import { buildChatResolvedAuthors, buildMemberChatChannelDetailVM } from "./chatViewModel.server";
import type { ChatAuditSession } from "./chatAuditSession.server";
export type ChatAuditLabels = Readonly<{
directMessage: string;
unnamedGroup: string;
unnamedProject: string;
unknownUser: string;
unknownMention: string;
}>;
export async function loadChatAuditOverview(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly session: ChatAuditSession | null;
readonly requestId?: string;
readonly labels: Pick<ChatAuditLabels, "directMessage" | "unnamedGroup" | "unnamedProject">;
}): Promise<ChatAuditOverviewVM> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readAllChannels);
const channels = input.session
? await listChatAuditChannels({
...repositoryContext(context),
requestId: input.requestId ?? crypto.randomUUID(),
auditSession: auditSessionContext(input.session),
})
: [];
return buildChatAuditOverviewVM({
canAdminister: context.permissions.includes(CHAT_PERMISSIONS.admin),
session: input.session
? {
id: input.session.id,
reason: input.session.reason,
expiresAtIso: new Date(input.session.expiresAt).toISOString(),
}
: null,
channels: channels.map((channel) => ({
id: channel.id,
kind: channel.kind,
title: resolveAuditTitle(channel, input.labels),
description: channel.description,
participantLabels: channel.participants.map((participant) => participant.displayName),
memberCount: channel.memberCount,
isPrivate: channel.isPrivate,
archivedAtIso: channel.archivedAtIso,
lastMessageAtIso: channel.lastMessageAtIso,
detailHref: `${chatAuditPath(input.tenantSlug)}/${encodeURIComponent(channel.id)}`,
})),
});
}
export async function startChatAuditSession(input: {
readonly context: ChatRouteContext;
readonly session: ChatAuditSession;
readonly requestId: string;
}): Promise<void> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readAllChannels);
await recordChatAuditSessionStarted({
...repositoryContext(context),
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
});
}
export async function loadChatAuditChannel(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly session: ChatAuditSession;
readonly requestId: string;
readonly beforeMessageCursor?: string;
readonly labels: ChatAuditLabels;
}): Promise<{
readonly vm: ChatChannelDetailVM;
readonly administrationVm: ChatAuditAdministrationVM;
readonly authors: readonly ChatResolvedAuthorVM[];
}> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readAllChannels);
const [detail, administration] = await Promise.all([
getChatAuditChannelDetail({
...repositoryContext(context),
chatId: input.chatId,
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
...(input.beforeMessageCursor ? { beforeMessageCursor: input.beforeMessageCursor } : {}),
}),
getChatAuditAdministration({ ...repositoryContext(context), chatId: input.chatId }),
]);
const baseVm = buildMemberChatChannelDetailVM({
detail,
tenantSlug: input.tenantSlug,
currentUserId: context.userId,
permissions: [],
nowIso: new Date().toISOString(),
labels: input.labels,
});
const title = resolveAuditTitle(detail.channel, input.labels);
const administrationVm = buildChatAuditAdministrationVM({
channel: {
id: administration.channel.id,
kind: administration.channel.kind,
title,
archivedAtIso: administration.channel.archivedAtIso,
},
canAdminister: administration.canAdminister,
members: administration.members,
});
if (baseVm.status !== "ready") return { vm: baseVm, administrationVm, authors: [] };
const auditedMessages = baseVm.data.messages.map((message) => ({
...message,
attachments: message.attachments.map((attachment) => ({
...attachment,
downloadHref: chatAuditAttachmentPath(input.tenantSlug, input.chatId, attachment.fileId, "original"),
previewHref: attachment.previewHref ? chatAuditAttachmentPath(input.tenantSlug, input.chatId, attachment.fileId, "preview") : null,
})),
}));
const vm = buildChatChannelDetailVM({
header: {
...baseVm.data.header,
title,
avatar: { imageUrl: null, fallbackLabel: initials(title) },
isAuditMode: true,
canManage: false,
settingsHref: null,
searchHref: chatAuditPath(input.tenantSlug),
},
messages: auditedMessages,
pinnedMessages: baseVm.data.pinnedMessages,
typingLabels: [],
history: baseVm.data.history,
composer: {
...baseVm.data.composer,
canSend: false,
canAttachFiles: false,
canRecordVoice: false,
canMention: false,
canMarkAsTask: false,
disabledReasonKey: "chat.composer.auditReadOnly",
},
connection: { ...baseVm.data.connection, state: "blocked", reconnectAttempt: 0, retryAtIso: null },
});
return {
vm,
administrationVm,
authors: buildChatResolvedAuthors(detail.channel.participants, context.userId),
};
}
export async function loadChatAuditAttachment(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly fileId: string;
readonly variant: ChatAuditAttachmentVariant;
readonly session: ChatAuditSession;
readonly requestId: string;
}): Promise<ChatAuditAttachmentDownload> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readAllChannels);
return getChatAuditAttachmentDownload({
...repositoryContext(context),
chatId: input.chatId,
fileId: input.fileId,
variant: input.variant,
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
});
}
export async function archiveChatAuditChannel(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly session: ChatAuditSession;
readonly requestId: string;
}): Promise<void> {
const context = requireChatAuditAdministrator(input.context);
await forceArchiveChatAuditChannel({
...repositoryContext(context),
chatId: input.chatId,
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
});
}
export async function setChatAuditMemberRole(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly memberUserId: string;
readonly roleInChat: "admin" | "member";
readonly session: ChatAuditSession;
readonly requestId: string;
}): Promise<void> {
const context = requireChatAuditAdministrator(input.context);
await forceSetChatAuditMemberRole({
...repositoryContext(context),
chatId: input.chatId,
memberUserId: input.memberUserId,
roleInChat: input.roleInChat,
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
});
}
export async function removeChatAuditMember(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly memberUserId: string;
readonly session: ChatAuditSession;
readonly requestId: string;
}): Promise<void> {
const context = requireChatAuditAdministrator(input.context);
await forceRemoveChatAuditMember({
...repositoryContext(context),
chatId: input.chatId,
memberUserId: input.memberUserId,
requestId: input.requestId,
auditSession: auditSessionContext(input.session),
});
}
function requireChatAuditAdministrator(context: ChatRouteContext): ChatRouteContext {
return requireChatPermission(requireChatPermission(context, CHAT_PERMISSIONS.readAllChannels), CHAT_PERMISSIONS.admin);
}
function repositoryContext(context: ChatRouteContext) {
return { tenantId: context.tenantId, userId: context.userId, permissions: context.permissions };
}
function auditSessionContext(session: ChatAuditSession) {
return {
sessionId: session.id,
reason: session.reason,
expiresAtIso: new Date(session.expiresAt).toISOString(),
};
}
function resolveAuditTitle(
channel: {
readonly kind: "project" | "group" | "dm";
readonly name: string | null;
readonly participants: readonly { readonly displayName: string }[];
},
labels: Pick<ChatAuditLabels, "directMessage" | "unnamedGroup" | "unnamedProject">
): string {
const name = channel.name?.trim();
if (name) return name;
if (channel.kind === "dm") {
return (
channel.participants
.map((participant) => participant.displayName.trim())
.filter(Boolean)
.join(" · ") || labels.directMessage
);
}
return channel.kind === "project" ? labels.unnamedProject : labels.unnamedGroup;
}
function initials(label: string): string {
return (
label
.trim()
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0]?.toLocaleUpperCase() ?? "")
.join("") || "?"
);
}
@@ -0,0 +1,156 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
tenantUserFindMany: vi.fn(),
groupFindMany: vi.fn(),
createGroupChat: vi.fn(),
getOrCreateDirectMessage: vi.fn(),
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: vi.fn(async (_tenantId: string, operation: (tx: unknown) => Promise<unknown>) =>
operation({ tenantUser: { findMany: mocks.tenantUserFindMany }, group: { findMany: mocks.groupFindMany } })
),
}));
vi.mock("@hivegrid/chat/lifecycle.server", () => ({
createGroupChat: mocks.createGroupChat,
getOrCreateDirectMessage: mocks.getOrCreateDirectMessage,
}));
import { createChatChannel, loadChatChannelCreatePage } from "./ChatChannelCreateService.server";
const context = {
tenantId: "tenant_1",
userId: "user_current",
tenantUserId: "tenant_user_current",
permissions: ["chat.create_channel", "chat.create_dm"],
hasModule: true as const,
};
describe("AK-P15b chat channel create service", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.tenantUserFindMany.mockResolvedValue([
{
userId: "user_current",
user: { email: "raffael@example.test", firstName: "Raffael", lastName: "Sheikh", avatar: null },
},
{
userId: "user_mara",
user: { email: "mara@example.test", firstName: "Mara", lastName: "Klein", avatar: " https://example.test/mara.png " },
},
]);
mocks.groupFindMany.mockResolvedValue([
{
id: "group_south",
name: "Team Süd",
description: "Montage",
users: [{ userId: "user_mara" }],
},
]);
mocks.createGroupChat.mockResolvedValue({ chatId: "chat_group" });
mocks.getOrCreateDirectMessage.mockResolvedValue({ chatId: "chat_dm", dmPairKey: "pair", created: true });
});
it("loads only active tenant users inside tenant RLS and excludes the viewer from options", async () => {
const vm = await loadChatChannelCreatePage({ context, requestedMode: "group" });
expect(mocks.tenantUserFindMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
status: 2,
user: { active: true, pendingDeletion: false, pseudonymized: false },
},
select: {
userId: true,
user: { select: { email: true, firstName: true, lastName: true, avatar: true } },
},
orderBy: [{ user: { firstName: "asc" } }, { user: { lastName: "asc" } }, { user: { email: "asc" } }],
});
expect(mocks.groupFindMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1" },
select: {
id: true,
name: true,
description: true,
users: {
where: {
user: {
active: true,
pendingDeletion: false,
pseudonymized: false,
tenants: { some: { tenantId: "tenant_1", status: 2 } },
},
},
select: { userId: true },
},
},
orderBy: [{ name: "asc" }, { id: "asc" }],
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") throw new Error("fixture must be ready");
expect(vm.data.userOptions).toEqual([
{
userId: "user_mara",
displayName: "Mara Klein",
email: "mara@example.test",
avatar: { imageUrl: "https://example.test/mara.png", fallbackLabel: "MK" },
isCurrentUser: false,
},
]);
expect(vm.data.groupOptions).toEqual([
{ groupId: "group_south", name: "Team Süd", description: "Montage", memberCount: 1 },
]);
});
it("passes group privacy and initial members into the atomic lifecycle", async () => {
await expect(
createChatChannel({
context,
requestId: "request_group",
submission: {
mode: "group",
name: "Montage Nord",
description: "Abstimmung",
privacy: "private",
initialUserIds: ["user_mara"],
initialGroupIds: ["group_south"],
syncGroupMembership: true,
},
})
).resolves.toEqual({ chatId: "chat_group" });
expect(mocks.createGroupChat).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_current",
permissions: context.permissions,
requestId: "request_group",
name: "Montage Nord",
description: "Abstimmung",
isPrivate: true,
notificationDefault: "all_messages",
initialMemberUserIds: ["user_mara"],
initialGroupIds: ["group_south"],
syncGroupMembership: true,
});
});
it("uses the canonical get-or-create lifecycle for direct messages", async () => {
await expect(
createChatChannel({
context,
requestId: "request_dm",
submission: { mode: "dm", peerUserId: "user_mara" },
})
).resolves.toEqual({ chatId: "chat_dm", dmPairKey: "pair", created: true });
expect(mocks.getOrCreateDirectMessage).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_current",
permissions: context.permissions,
requestId: "request_dm",
peerUserId: "user_mara",
});
});
});
@@ -0,0 +1,158 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { createGroupChat, getOrCreateDirectMessage } from "@hivegrid/chat/lifecycle.server";
import { withTenantScope } from "@hivegrid/foundation";
import {
buildChatChannelCreateVM,
type ChatChannelCreateMode,
type ChatChannelCreateSubmission,
type ChatChannelCreateVM,
type ChatPermissionGroupOptionInput,
type ChatTenantUserOptionInput,
} from "@hivegrid/view-models";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { chatHasPermission, requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
export async function loadChatChannelCreatePage(input: {
readonly context: ChatRouteContext;
readonly requestedMode?: ChatChannelCreateMode;
}): Promise<ChatChannelCreateVM> {
const permissions = {
canCreateGroup: chatHasPermission(input.context, CHAT_PERMISSIONS.createChannel),
canCreateDm: chatHasPermission(input.context, CHAT_PERMISSIONS.createDm),
};
const options =
permissions.canCreateGroup || permissions.canCreateDm
? await loadChatChannelCreateOptions(input.context, permissions.canCreateGroup)
: { tenantUsers: [], tenantGroups: [] };
return buildChatChannelCreateVM({
currentUserId: input.context.userId,
tenantUsers: options.tenantUsers,
tenantGroups: options.tenantGroups,
permissions,
requestedMode: input.requestedMode,
});
}
export async function createChatChannel(input: {
readonly context: ChatRouteContext;
readonly requestId: string;
readonly submission: ChatChannelCreateSubmission;
}): Promise<{ readonly chatId: string }> {
if (input.submission.mode === "group") {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.createChannel);
return createGroupChat({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
requestId: input.requestId,
name: input.submission.name,
description: input.submission.description,
isPrivate: input.submission.privacy === "private",
notificationDefault: "all_messages",
initialMemberUserIds: input.submission.initialUserIds,
initialGroupIds: input.submission.initialGroupIds,
syncGroupMembership: input.submission.syncGroupMembership,
});
}
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.createDm);
return getOrCreateDirectMessage({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
requestId: input.requestId,
peerUserId: input.submission.peerUserId,
});
}
async function loadChatChannelCreateOptions(
context: ChatRouteContext,
includeGroups: boolean
): Promise<Readonly<{ tenantUsers: readonly ChatTenantUserOptionInput[]; tenantGroups: readonly ChatPermissionGroupOptionInput[] }>> {
const { memberships, groups } = await withTenantRLS(context.tenantId, async (tx) => {
const membershipsPromise = tx.tenantUser.findMany({
where: {
tenantId: context.tenantId,
status: TenantUserStatus.ACTIVE,
user: {
active: true,
pendingDeletion: false,
pseudonymized: false,
},
},
select: {
userId: true,
user: {
select: {
email: true,
firstName: true,
lastName: true,
avatar: true,
},
},
},
orderBy: [{ user: { firstName: "asc" } }, { user: { lastName: "asc" } }, { user: { email: "asc" } }],
});
const groupsPromise = includeGroups
? tx.group.findMany({
where: withTenantScope(context.tenantId, {}),
select: {
id: true,
name: true,
description: true,
users: {
where: {
user: {
active: true,
pendingDeletion: false,
pseudonymized: false,
tenants: { some: withTenantScope(context.tenantId, { status: TenantUserStatus.ACTIVE }) },
},
},
select: { userId: true },
},
},
orderBy: [{ name: "asc" }, { id: "asc" }],
})
: Promise.resolve([]);
const [memberships, groups] = await Promise.all([membershipsPromise, groupsPromise]);
return { memberships, groups };
});
const tenantUsers = memberships.map(({ userId, user }) => {
const displayName =
[user.firstName, user.lastName]
.map((part) => part?.trim())
.filter((part): part is string => Boolean(part))
.join(" ") || user.email;
const fallbackLabel =
[user.firstName?.trim().slice(0, 1), user.lastName?.trim().slice(0, 1)]
.filter((part): part is string => Boolean(part))
.join("")
.toLocaleUpperCase() ||
user.email.slice(0, 1).toLocaleUpperCase() ||
"?";
return {
userId,
displayName,
email: user.email,
avatar: {
imageUrl: user.avatar?.trim() || null,
fallbackLabel,
},
};
});
const tenantGroups = groups.map((group) => ({
groupId: group.id,
name: group.name,
description: group.description,
memberCount: group.users.length,
}));
return { tenantUsers, tenantGroups };
}
@@ -0,0 +1,173 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
loadSettings: vi.fn(),
setMember: vi.fn(),
removeMember: vi.fn(),
setPrivacy: vi.fn(),
leave: vi.fn(),
archive: vi.fn(),
projectFindFirst: vi.fn(),
}));
vi.mock("@hivegrid/chat/channel-settings.server", () => ({ loadChatChannelSettings: mocks.loadSettings }));
vi.mock("@hivegrid/chat/lifecycle.server", () => ({
setChatChannelMember: mocks.setMember,
removeChatChannelMember: mocks.removeMember,
setGroupChatPrivacy: mocks.setPrivacy,
leaveGroupChat: mocks.leave,
archiveChatChannel: mocks.archive,
}));
vi.mock("~/utils/db/.server/tenantRls.server", () => ({
withTenantRLS: vi.fn((_tenantId: string, operation: (tx: unknown) => Promise<unknown>) =>
operation({ projekt: { findFirst: mocks.projectFindFirst } })
),
}));
import {
addChatChannelMember,
archiveChatChannel,
changeChatChannelMemberRole,
changeChatChannelPrivacy,
leaveChatChannel,
loadChatChannelSettingsPage,
removeChatChannelMember,
} from "./ChatChannelSettingsService.server";
const context = {
tenantId: "tenant_1",
userId: "user_current",
tenantUserId: "tenant_user_current",
permissions: ["chat.read_own_channels"],
hasModule: true as const,
};
const labels = {
directMessage: "Direktnachricht",
unnamedGroup: "Gruppe",
unnamedProject: "Projekt",
unknownProjectStage: "Unbekannte Phase",
};
function profile(userId: string, displayName: string) {
return { userId, displayName, email: `${userId}@example.test`, avatarUrl: null };
}
function settingsRecord(kind: "group" | "dm" | "project" = "group") {
return {
channel: {
id: "chat_1",
kind,
name: kind === "group" ? "Montage" : null,
description: null,
privacy: kind === "group" ? ("private" as const) : null,
archivedAtIso: null,
projectId: kind === "project" ? "project_1" : null,
},
members: [
{
...profile("user_current", "Raffael Sheikh"),
roleInChat: "admin" as const,
joinedAtIso: "2026-07-15T10:00:00.000Z",
joinedViaUserId: null,
writeRevokedAtIso: null,
provenance: {
isManualMember: kind !== "dm",
manualRoleInChat: kind !== "dm" ? ("admin" as const) : null,
isProjectManaged: kind === "project",
projectRoleInChat: kind === "project" ? ("admin" as const) : null,
isGroupManaged: false,
},
},
{
...profile("user_peer", "Mara Klein"),
roleInChat: "member" as const,
joinedAtIso: "2026-07-15T10:00:00.000Z",
joinedViaUserId: null,
writeRevokedAtIso: null,
provenance: {
isManualMember: kind === "group",
manualRoleInChat: kind === "group" ? ("member" as const) : null,
isProjectManaged: kind === "project",
projectRoleInChat: kind === "project" ? ("member" as const) : null,
isGroupManaged: false,
},
},
],
candidateUsers: kind === "group" ? [profile("user_candidate", "Ada Lovelace")] : [],
capabilities: {
canManageMembers: kind === "group",
canManageAdmins: kind === "group",
canChangePrivacy: kind === "group",
canManageManualGuests: kind === "project",
canArchive: kind !== "dm",
canLeave: false,
isReadOnly: kind !== "group",
},
};
}
describe("AK-P15b chat channel settings service", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.loadSettings.mockResolvedValue(settingsRecord());
});
it("maps the RLS-scoped group record to the pure settings VM", async () => {
const vm = await loadChatChannelSettingsPage({ context, tenantSlug: "demo", chatId: "chat_1", labels });
expect(mocks.loadSettings).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_current",
permissions: context.permissions,
chatId: "chat_1",
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") throw new Error("fixture must be ready");
expect(vm.data.channel).toMatchObject({ title: "Montage", privacy: "private", isArchived: false });
expect(vm.data.members.map(({ displayName }) => displayName)).toEqual(["Raffael Sheikh", "Mara Klein"]);
expect(vm.data.candidateUsers.map(({ displayName }) => displayName)).toEqual(["Ada Lovelace"]);
});
it("resolves project metadata inside tenant RLS and keeps project membership read-only", async () => {
mocks.loadSettings.mockResolvedValue(settingsRecord("project"));
mocks.projectFindFirst.mockResolvedValue({
id: "project_1",
projektNummer: "P-42",
projektname: "Wärmepumpe Klein",
stage: { name: "Montage" },
});
const vm = await loadChatChannelSettingsPage({ context, tenantSlug: "demo", chatId: "chat_1", labels });
expect(mocks.projectFindFirst).toHaveBeenCalledWith(expect.objectContaining({ where: { tenantId: "tenant_1", id: "project_1" } }));
expect(vm.status).toBe("ready");
if (vm.status !== "ready") throw new Error("fixture must be ready");
expect(vm.data.channel.project).toEqual({
id: "project_1",
number: "P-42",
label: "Wärmepumpe Klein",
stageLabel: "Montage",
href: "/demo/projects/project_1",
});
expect(vm.data.infoKey).toBe("chat.channelSettings.project.managedExternally");
expect(vm.data.permissions).toMatchObject({ canManageManualGuests: true, canArchive: true });
});
it("delegates group settings mutations with tenant context and stable request ids", async () => {
const base = { context, chatId: "chat_1", requestId: "request_1" };
await addChatChannelMember({ ...base, memberUserId: "user_new" });
await changeChatChannelMemberRole({ ...base, memberUserId: "user_new", roleInChat: "admin" });
await removeChatChannelMember({ ...base, memberUserId: "user_new" });
await changeChatChannelPrivacy({ ...base, privacy: "public" });
await leaveChatChannel(base);
await archiveChatChannel(base);
const repositoryContext = { tenantId: "tenant_1", userId: "user_current", permissions: context.permissions };
expect(mocks.setMember).toHaveBeenNthCalledWith(1, { ...repositoryContext, chatId: "chat_1", requestId: "request_1", memberUserId: "user_new", roleInChat: "member" });
expect(mocks.setMember).toHaveBeenNthCalledWith(2, { ...repositoryContext, chatId: "chat_1", requestId: "request_1", memberUserId: "user_new", roleInChat: "admin" });
expect(mocks.removeMember).toHaveBeenCalledWith({ ...repositoryContext, chatId: "chat_1", requestId: "request_1", memberUserId: "user_new" });
expect(mocks.setPrivacy).toHaveBeenCalledWith({ ...repositoryContext, chatId: "chat_1", requestId: "request_1", isPrivate: false });
expect(mocks.leave).toHaveBeenCalledWith({ ...repositoryContext, chatId: "chat_1", requestId: "request_1" });
expect(mocks.archive).toHaveBeenCalledWith({ ...repositoryContext, chatId: "chat_1", requestId: "request_1" });
});
});
@@ -0,0 +1,186 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { loadChatChannelSettings, type ChatChannelSettingsRecord } from "@hivegrid/chat/channel-settings.server";
import {
archiveChatChannel as archiveManagedChatChannel,
leaveGroupChat,
removeChatChannelMember as removeManagedChatChannelMember,
setChatChannelMember,
setGroupChatPrivacy,
} from "@hivegrid/chat/lifecycle.server";
import { buildChatChannelSettingsVM, type ChatChannelSettingsVM } from "@hivegrid/view-models";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { projectDetailPath } from "~/utils/integrations/projects/projectRoutePaths";
import { requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
export type ChatChannelSettingsLabels = Readonly<{
directMessage: string;
unnamedGroup: string;
unnamedProject: string;
unknownProjectStage: string;
}>;
export async function loadChatChannelSettingsPage(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly labels: ChatChannelSettingsLabels;
}): Promise<ChatChannelSettingsVM> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
const record = await loadChatChannelSettings({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
});
const project = record.channel.projectId
? await loadProjectSummary(context.tenantId, input.tenantSlug, record.channel.projectId, input.labels)
: null;
return buildChatChannelSettingsVM({
currentUserId: context.userId,
channel: {
id: record.channel.id,
kind: record.channel.kind,
title: channelTitle(record, context.userId, project?.label ?? null, input.labels),
description: record.channel.description,
isPrivate: record.channel.privacy !== "public",
isArchived: record.channel.archivedAtIso !== null,
project,
},
members: record.members.map((member) => ({
user: profileInput(member),
role: member.roleInChat,
isProjectManaged: member.provenance.isProjectManaged,
isManualGuest: member.provenance.isManualMember,
manualRole: member.provenance.manualRoleInChat,
})),
tenantUsers: record.candidateUsers.map(profileInput),
permissions: {
canManageMembers: record.capabilities.canManageMembers,
canManageAdmins: record.capabilities.canManageAdmins,
canChangePrivacy: record.capabilities.canChangePrivacy,
canLeave: record.capabilities.canLeave,
canManageManualGuests: record.capabilities.canManageManualGuests,
canArchive: record.capabilities.canArchive,
},
});
}
export async function addChatChannelMember(input: MutationInput & { readonly memberUserId: string }): Promise<void> {
await setChatChannelMember({ ...repositoryContext(input.context), chatId: input.chatId, requestId: input.requestId, memberUserId: input.memberUserId, roleInChat: "member" });
}
export async function changeChatChannelMemberRole(
input: MutationInput & { readonly memberUserId: string; readonly roleInChat: "admin" | "member" }
): Promise<void> {
await setChatChannelMember({
...repositoryContext(input.context),
chatId: input.chatId,
requestId: input.requestId,
memberUserId: input.memberUserId,
roleInChat: input.roleInChat,
});
}
export async function removeChatChannelMember(input: MutationInput & { readonly memberUserId: string }): Promise<void> {
await removeManagedChatChannelMember({
...repositoryContext(input.context),
chatId: input.chatId,
requestId: input.requestId,
memberUserId: input.memberUserId,
});
}
export async function changeChatChannelPrivacy(input: MutationInput & { readonly privacy: "public" | "private" }): Promise<void> {
await setGroupChatPrivacy({
...repositoryContext(input.context),
chatId: input.chatId,
requestId: input.requestId,
isPrivate: input.privacy === "private",
});
}
export async function leaveChatChannel(input: MutationInput): Promise<void> {
await leaveGroupChat({ ...repositoryContext(input.context), chatId: input.chatId, requestId: input.requestId });
}
export async function archiveChatChannel(input: MutationInput): Promise<void> {
await archiveManagedChatChannel({ ...repositoryContext(input.context), chatId: input.chatId, requestId: input.requestId });
}
type MutationInput = Readonly<{
context: ChatRouteContext;
chatId: string;
requestId: string;
}>;
function repositoryContext(context: ChatRouteContext) {
return { tenantId: context.tenantId, userId: context.userId, permissions: context.permissions };
}
function profileInput(profile: {
readonly userId: string;
readonly displayName: string;
readonly email: string;
readonly avatarUrl: string | null;
}) {
return {
userId: profile.userId,
displayName: profile.displayName,
email: profile.email,
avatar: {
imageUrl: profile.avatarUrl,
fallbackLabel: fallbackLabel(profile.displayName, profile.email),
},
};
}
function fallbackLabel(displayName: string, email: string): string {
const initials = displayName
.split(/\s+/u)
.filter(Boolean)
.slice(0, 2)
.map((part) => part.slice(0, 1))
.join("")
.toLocaleUpperCase();
return initials || email.slice(0, 1).toLocaleUpperCase() || "?";
}
function channelTitle(
record: ChatChannelSettingsRecord,
currentUserId: string,
projectLabel: string | null,
labels: ChatChannelSettingsLabels
): string {
if (record.channel.kind === "group") return record.channel.name ?? labels.unnamedGroup;
if (record.channel.kind === "project") return projectLabel ?? record.channel.name ?? labels.unnamedProject;
return record.members.find((member) => member.userId !== currentUserId)?.displayName ?? labels.directMessage;
}
async function loadProjectSummary(
tenantId: string,
tenantSlug: string,
projectId: string,
labels: ChatChannelSettingsLabels
) {
const project = await withTenantRLS(tenantId, (tx) =>
tx.projekt.findFirst({
where: { tenantId, id: projectId },
select: {
id: true,
projektNummer: true,
projektname: true,
stage: { select: { name: true } },
},
})
);
return {
id: projectId,
number: project?.projektNummer ?? projectId,
label: project?.projektname?.trim() || labels.unnamedProject,
stageLabel: project?.stage.name?.trim() || labels.unknownProjectStage,
href: projectDetailPath(tenantSlug, projectId),
};
}
@@ -0,0 +1,29 @@
import { describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ list: vi.fn() }));
vi.mock("@hivegrid/chat/mentions.server", () => ({ listChatMentionSuggestions: mocks.list }));
import { loadChatMentionSuggestions } from "./ChatMentionsService.server";
describe("loadChatMentionSuggestions", () => {
it("passes the route identity to the fresh repository and returns the pure grouped VM", async () => {
mocks.list.mockResolvedValue([
{ type: "user", id: "user_1", label: "Raffael", detail: "raffael@example.test" },
{ type: "project", id: "project_1", label: "P-100", detail: "P-100" },
]);
const context = {
tenantId: "tenant_1",
tenantUserId: "tenant_user_1",
userId: "user_1",
permissions: ["chat.read_own_channels"],
hasModule: true as const,
};
const vm = await loadChatMentionSuggestions({ context, tenantSlug: "acme", chatId: "chat_1", query: "ra", type: null });
expect(mocks.list).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", chatId: "chat_1", query: "ra", limit: 10 })
);
expect(vm.groups.map((group) => group.kind)).toEqual(["user", "project"]);
});
});
@@ -0,0 +1,31 @@
import { listChatMentionSuggestions, type ChatMentionSuggestion } from "@hivegrid/chat/mentions.server";
import { buildChatMentionAutocompleteVM, type ChatMentionAutocompleteVM } from "@hivegrid/view-models";
import type { ChatRouteContext } from "../routes/chatAccess.server";
export async function loadChatMentionSuggestions(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly query: string;
readonly type: ChatMentionSuggestion["type"] | null;
}): Promise<ChatMentionAutocompleteVM> {
const suggestions = await listChatMentionSuggestions({
tenantId: input.context.tenantId,
userId: input.context.userId,
permissions: input.context.permissions,
chatId: input.chatId,
query: input.query,
type: input.type,
limit: 10,
});
return buildChatMentionAutocompleteVM({
tenantSlug: input.tenantSlug,
suggestions: suggestions.map((suggestion) => ({
kind: suggestion.type,
id: suggestion.id,
label: suggestion.label,
detail: suggestion.detail,
})),
});
}
@@ -0,0 +1,109 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
const mocks = vi.hoisted(() => ({ list: vi.fn() }));
vi.mock("@hivegrid/chat/message-discovery.server", () => ({
listChatMessageDiscovery: (...args: unknown[]) => mocks.list(...args),
}));
import { loadChatMessageDiscovery } from "./ChatMessageDiscoveryService.server";
const context = {
tenantId: "tenant_1",
userId: "viewer_1",
tenantUserId: "tenant_user_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
hasModule: true,
} as const;
const labels = {
directMessage: "Direct message",
unnamedGroup: "Unnamed group",
unnamedProject: "Project chat",
unknownUser: "Unknown user",
} as const;
describe("ChatMessageDiscoveryService", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.list.mockResolvedValue({ messages: [], nextCursor: null });
});
it("maps repository records to pure VM rows and resolves a DM counterpart", async () => {
mocks.list.mockResolvedValue({
nextCursor: "cursor_1",
messages: [
{
id: "message_1",
chatId: "chat_dm",
channelKind: "dm",
channelName: null,
projectId: null,
authorUserId: "peer_1",
body: "Heat pump update",
parentMessageId: null,
createdAtIso: "2026-07-16T11:00:00.000Z",
participants: [
{ userId: "viewer_1", displayName: "Raffael Sheikh", avatarUrl: null },
{ userId: "peer_1", displayName: "Ada Lovelace", avatarUrl: "/avatars/ada" },
],
},
],
});
const vm = await loadChatMessageDiscovery({ context, tenantSlug: "demo", mode: "search", query: "heat", labels });
expect(mocks.list).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "viewer_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels],
mode: "search",
query: "heat",
});
expect(vm).toMatchObject({
status: "ready",
data: {
nextCursor: "cursor_1",
rows: [
{
channelTitle: "Ada Lovelace",
authorLabel: "Ada Lovelace",
authorAvatar: { imageUrl: "/avatars/ada", fallbackLabel: "AL" },
detailHref: "/demo/chat/chat_dm?message=message_1#message-message_1",
},
],
},
});
});
it("uses localized fallbacks without exposing unresolved identities", async () => {
mocks.list.mockResolvedValue({
nextCursor: null,
messages: [
{
id: "message_2",
chatId: "chat_project",
channelKind: "project",
channelName: null,
projectId: "project_1",
authorUserId: "former_user",
body: "Archived author stays readable",
parentMessageId: "parent_1",
createdAtIso: "2026-07-16T10:00:00.000Z",
participants: [],
},
],
});
const vm = await loadChatMessageDiscovery({ context, tenantSlug: "demo", mode: "mentions", labels });
expect(vm.status === "ready" && vm.data.rows[0]).toMatchObject({
channelTitle: "Project chat",
authorLabel: "Unknown user",
authorAvatar: { fallbackLabel: "UU" },
isThreadReply: true,
detailHref: "/demo/chat/chat_project/thread/parent_1?message=message_2#message-message_2",
});
});
});
@@ -0,0 +1,86 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { buildChatMessageDeepLink } from "@hivegrid/chat/deep-links";
import { listChatMessageDiscovery, type ChatMessageDiscoveryRecord } from "@hivegrid/chat/message-discovery.server";
import { buildChatMessageDiscoveryVM, type ChatMessageDiscoveryMode, type ChatMessageDiscoveryVM } from "@hivegrid/view-models";
import { requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
import { chatIndexPath, chatMentionsPath, chatSearchPath } from "../routes/chatRoutePaths";
export type ChatMessageDiscoveryLabels = Readonly<{
directMessage: string;
unnamedGroup: string;
unnamedProject: string;
unknownUser: string;
}>;
export async function loadChatMessageDiscovery(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly mode: ChatMessageDiscoveryMode;
readonly query?: string;
readonly beforeCursor?: string;
readonly limit?: number;
readonly labels: ChatMessageDiscoveryLabels;
}): Promise<ChatMessageDiscoveryVM> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
const result = await listChatMessageDiscovery({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
mode: input.mode,
...(input.query !== undefined ? { query: input.query } : {}),
...(input.beforeCursor ? { beforeCursor: input.beforeCursor } : {}),
...(input.limit !== undefined ? { limit: input.limit } : {}),
});
return buildChatMessageDiscoveryVM({
mode: input.mode,
query: input.query,
nextCursor: result.nextCursor,
hrefs: {
chat: chatIndexPath(input.tenantSlug),
search: chatSearchPath(input.tenantSlug),
mentions: chatMentionsPath(input.tenantSlug),
},
rows: result.messages.map((message) => toRow(message, context.userId, input.tenantSlug, input.labels)),
});
}
function toRow(message: ChatMessageDiscoveryRecord, currentUserId: string, tenantSlug: string, labels: ChatMessageDiscoveryLabels) {
const author = message.participants.find((participant) => participant.userId === message.authorUserId);
const authorLabel = author?.displayName ?? labels.unknownUser;
const channelTitle = resolveChannelTitle(message, currentUserId, labels);
return {
id: message.id,
chatId: message.chatId,
channelKind: message.channelKind,
channelTitle,
authorLabel,
authorAvatar: {
imageUrl: author?.avatarUrl ?? null,
fallbackLabel: initials(authorLabel),
},
body: message.body,
createdAtIso: message.createdAtIso,
detailHref: buildChatMessageDeepLink({
tenantSlug,
chatId: message.chatId,
messageId: message.id,
parentMessageId: message.parentMessageId,
}),
isThreadReply: message.parentMessageId !== null,
} as const;
}
function resolveChannelTitle(message: ChatMessageDiscoveryRecord, currentUserId: string, labels: ChatMessageDiscoveryLabels): string {
if (message.channelKind === "dm") {
return message.participants.find((participant) => participant.userId !== currentUserId)?.displayName ?? labels.directMessage;
}
return message.channelName ?? (message.channelKind === "project" ? labels.unnamedProject : labels.unnamedGroup);
}
function initials(label: string): string {
const normalized = label.trim();
const parts = normalized.split(/\s+/).filter(Boolean);
return (parts.length > 1 ? `${parts[0]?.[0] ?? ""}${parts.at(-1)?.[0] ?? ""}` : normalized.slice(0, 2)).toUpperCase() || "?";
}
@@ -0,0 +1,217 @@
import { CHAT_PERMISSIONS, type ChatAttachmentRecord, type ChatMemberChannelRecord, type ChatMessageFeatureRecord } from "@hivegrid/chat";
import { buildChatMessageDeepLink } from "@hivegrid/chat/deep-links";
import type { ChatRealtimeMessage } from "@hivegrid/realtime";
import { getChatThreadDetail, listChatPinnedMessages, sendChatThreadReply, setChatMessagePin, setChatReaction } from "@hivegrid/chat/message-features.server";
import { buildChatPinnedMessagesVM, buildChatThreadVM, type ChatFeatureMessageVM, type ChatPinnedMessagesVM, type ChatThreadVM } from "@hivegrid/view-models";
import type { ChatRouteContext } from "../routes/chatAccess.server";
import { chatChannelPath } from "../routes/chatRoutePaths";
import { toChatAttachmentVM, toChatResolvedMentionVM } from "./chatViewModel.server";
export type ChatMessageFeatureLabels = {
readonly directMessage: string;
readonly unnamedGroup: string;
readonly unnamedProject: string;
readonly unknownUser: string;
readonly unknownMention: string;
};
export async function loadChatThreadPage(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly threadId: string;
readonly labels: ChatMessageFeatureLabels;
}): Promise<{ readonly vm: ChatThreadVM; readonly eventCursor: string }> {
const detail = await getChatThreadDetail({ ...input.context, chatId: input.chatId, threadId: input.threadId });
const features = new Map(detail.messageFeatures.map((feature) => [feature.messageId, feature]));
const attachments = groupAttachments(detail.attachments);
const profiles = new Map(detail.channel.participants.map((profile) => [profile.userId, profile]));
const canWrite = input.context.permissions.includes(CHAT_PERMISSIONS.write) && detail.channel.member.canWrite && detail.channel.archivedAtIso === null;
const canAdministerMessages = input.context.permissions.includes(CHAT_PERMISSIONS.admin);
const canDeleteAsChannelAdmin = detail.channel.member.roleInChat === "admin" || canAdministerMessages;
const nowIso = new Date().toISOString();
const vm = buildChatThreadVM({
chatId: detail.channel.id,
threadId: detail.parentMessage.id,
channelTitle: resolveChannelTitle(detail.channel, input.context.userId, input.labels),
backHref: chatChannelPath(input.tenantSlug, detail.channel.id),
parent: mapFeatureMessage(
detail.parentMessage,
features.get(detail.parentMessage.id) ?? null,
profiles,
input.context.userId,
canWrite,
detail.channel.kind,
input.tenantSlug,
attachments.get(detail.parentMessage.id) ?? [],
canAdministerMessages,
canDeleteAsChannelAdmin,
nowIso,
input.labels
),
replies: detail.replies.map((message) =>
mapFeatureMessage(
message,
features.get(message.id) ?? null,
profiles,
input.context.userId,
canWrite,
detail.channel.kind,
input.tenantSlug,
attachments.get(message.id) ?? [],
canAdministerMessages,
canDeleteAsChannelAdmin,
nowIso,
input.labels
)
),
replyCount: detail.replies.length,
canReply: canWrite,
});
return { vm, eventCursor: detail.channel.eventCursor };
}
export async function loadChatPinnedPage(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly labels: ChatMessageFeatureLabels;
}): Promise<{ readonly vm: ChatPinnedMessagesVM; readonly eventCursor: string }> {
const result = await listChatPinnedMessages({ ...input.context, chatId: input.chatId });
const profiles = new Map(result.channel.participants.map((profile) => [profile.userId, profile]));
const canWrite = input.context.permissions.includes(CHAT_PERMISSIONS.write) && result.channel.member.canWrite && result.channel.archivedAtIso === null;
const vm = buildChatPinnedMessagesVM({
chatId: result.channel.id,
channelTitle: resolveChannelTitle(result.channel, input.context.userId, input.labels),
backHref: chatChannelPath(input.tenantSlug, result.channel.id),
rows: result.pinnedMessages.map((row) => ({
message: mapFeatureMessage(
row.message,
{
messageId: row.message.id,
reactions: [],
thread: null,
pin: row.pin,
},
profiles,
input.context.userId,
false,
result.channel.kind,
input.tenantSlug,
[],
false,
false,
new Date().toISOString(),
input.labels
),
pinnedAtIso: row.pin.pinnedAtIso,
pinnedByLabel: row.pinnedBy?.displayName ?? input.labels.unknownUser,
note: row.pin.note,
messageHref: buildChatMessageDeepLink({ tenantSlug: input.tenantSlug, chatId: result.channel.id, messageId: row.message.id }),
canUnpin: canWrite,
})),
});
return { vm, eventCursor: result.channel.eventCursor };
}
export async function createChatThreadReply(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly threadId: string;
readonly body: string;
readonly requestId: string;
readonly clientMessageId: string;
}) {
return sendChatThreadReply({ ...input.context, ...input });
}
export async function changeChatReaction(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly messageId: string;
readonly emoji: string;
readonly active: boolean;
readonly requestId: string;
}) {
return setChatReaction({ ...input.context, ...input });
}
export async function changeChatMessagePin(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly messageId: string;
readonly pinned: boolean;
readonly requestId: string;
}) {
return setChatMessagePin({ ...input.context, ...input });
}
function mapFeatureMessage(
message: ChatRealtimeMessage,
feature: ChatMessageFeatureRecord | null,
profiles: ReadonlyMap<string, ChatMemberChannelRecord["participants"][number]>,
currentUserId: string,
canWrite: boolean,
channelKind: ChatMemberChannelRecord["kind"],
tenantSlug: string,
attachments: readonly ChatAttachmentRecord[],
canAdministerMessages: boolean,
canDeleteAsChannelAdmin: boolean,
nowIso: string,
labels: ChatMessageFeatureLabels
): ChatFeatureMessageVM {
const deleted = message.deletedAt !== null;
const author = message.authorUserId ? profiles.get(message.authorUserId) : null;
const ownMessage = message.authorUserId === currentUserId;
const ageMs = Date.parse(nowIso) - Date.parse(message.createdAt);
const withinOwnMutationWindow = Number.isFinite(ageMs) && ageMs >= 0 && ageMs <= 24 * 60 * 60 * 1_000;
const reactionGroups = new Map<string, string[]>();
for (const reaction of feature?.reactions ?? []) {
const userIds = reactionGroups.get(reaction.emoji) ?? [];
userIds.push(reaction.userId);
reactionGroups.set(reaction.emoji, userIds);
}
return {
id: message.id,
authorLabel: author?.displayName ?? "?",
authorAvatarUrl: author?.avatarUrl ?? null,
bodyMarkdown: deleted ? null : message.body,
createdAtIso: message.createdAt,
deleted,
mentions: deleted
? []
: message.mentions.map((mention) =>
toChatResolvedMentionVM(mention, profiles, tenantSlug, {
...labels,
})
),
attachments: deleted ? [] : attachments.map((attachment) => toChatAttachmentVM(attachment, tenantSlug)),
reactions: [...reactionGroups].map(([emoji, userIds]) => ({
emoji,
count: userIds.length,
reactedByViewer: userIds.includes(currentUserId),
})),
pinned: feature?.pin !== null && feature?.pin !== undefined,
canReact: canWrite && !deleted,
canPin: canWrite && !deleted && channelKind !== "dm",
canEdit: canWrite && !deleted && (canAdministerMessages || (ownMessage && withinOwnMutationWindow)),
canDelete: canWrite && !deleted && (canDeleteAsChannelAdmin || (ownMessage && withinOwnMutationWindow)),
};
}
function groupAttachments(attachments: readonly ChatAttachmentRecord[]): ReadonlyMap<string, readonly ChatAttachmentRecord[]> {
const grouped = new Map<string, ChatAttachmentRecord[]>();
for (const attachment of attachments) {
grouped.set(attachment.messageId, [...(grouped.get(attachment.messageId) ?? []), attachment]);
}
return grouped;
}
function resolveChannelTitle(channel: ChatMemberChannelRecord, currentUserId: string, labels: ChatMessageFeatureLabels): string {
if (channel.kind === "dm") {
return channel.participants.find((participant) => participant.userId !== currentUserId)?.displayName ?? labels.directMessage;
}
return channel.name?.trim() || (channel.kind === "project" ? labels.unnamedProject : labels.unnamedGroup);
}
@@ -0,0 +1,50 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
updateMessage: vi.fn(),
deleteMessage: vi.fn(),
}));
vi.mock("@hivegrid/chat/message-mutations.server", () => ({
updateChatMessage: mocks.updateMessage,
deleteChatMessage: mocks.deleteMessage,
}));
import { editMemberChatMessage, removeMemberChatMessage } from "./ChatMessageMutationsService.server";
const context = {
tenantId: "tenant_1",
userId: "user_1",
permissions: ["chat.read_own_channels", "chat.write"],
} as const;
describe("ChatMessageMutationsService", () => {
beforeEach(() => vi.clearAllMocks());
it("passes the fresh route context to an edit mutation", async () => {
mocks.updateMessage.mockResolvedValue({ replayed: false });
await editMemberChatMessage({ context, chatId: "chat_1", messageId: "message_1", requestId: "request_1", body: "Neu" });
expect(mocks.updateMessage).toHaveBeenCalledWith({
...context,
chatId: "chat_1",
messageId: "message_1",
requestId: "request_1",
body: "Neu",
});
});
it("passes the stable request id to a delete mutation", async () => {
mocks.deleteMessage.mockResolvedValue({ replayed: false });
await removeMemberChatMessage({ context, chatId: "chat_1", messageId: "message_1", requestId: "request_2" });
expect(mocks.deleteMessage).toHaveBeenCalledWith({
...context,
chatId: "chat_1",
messageId: "message_1",
requestId: "request_2",
});
});
});
@@ -0,0 +1,40 @@
import { CHAT_PERMISSIONS } from "@hivegrid/chat";
import { deleteChatMessage, updateChatMessage } from "@hivegrid/chat/message-mutations.server";
import { requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
export async function editMemberChatMessage(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly messageId: string;
readonly requestId: string;
readonly body: string;
}) {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.write);
return updateChatMessage({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
messageId: input.messageId,
requestId: input.requestId,
body: input.body,
});
}
export async function removeMemberChatMessage(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly messageId: string;
readonly requestId: string;
}) {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.write);
return deleteChatMessage({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
messageId: input.messageId,
requestId: input.requestId,
});
}
@@ -0,0 +1,153 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
withWritableSource: vi.fn(),
createTask: vi.fn(),
linkEntities: vi.fn(),
auditTask: vi.fn(),
logActivity: vi.fn(),
writeSystemMessage: vi.fn(),
publishWakeup: vi.fn(),
hasTasksModule: vi.fn(),
}));
vi.mock("@hivegrid/chat/repository.server", () => ({
withWritableChatMessageTaskSource: (...args: unknown[]) => mocks.withWritableSource(...args),
}));
vi.mock("@hivegrid/chat/system-message.server", () => ({
writeChatSystemMessageWithTx: (...args: unknown[]) => mocks.writeSystemMessage(...args),
}));
vi.mock("@hivegrid/chat/realtime-wakeup.server", () => ({
publishChatPersistentRealtimeWakeup: (...args: unknown[]) => mocks.publishWakeup(...args),
}));
vi.mock("@hivegrid/chat/module-access.server", () => ({
tenantHasTasksModuleWithPermissionsTx: (...args: unknown[]) => mocks.hasTasksModule(...args),
}));
vi.mock("~/utils/integrations/taskService.server", () => ({
createIdempotentTaskFromSourceWithTx: (...args: unknown[]) => mocks.createTask(...args),
}));
vi.mock("~/utils/integrations/entityLinkService.server", () => ({
linkEntitiesWithTx: (...args: unknown[]) => mocks.linkEntities(...args),
}));
vi.mock("~/utils/integrations/taskAudit.server", () => ({
auditTaskEvent: (...args: unknown[]) => mocks.auditTask(...args),
logTaskActivity: (...args: unknown[]) => mocks.logActivity(...args),
}));
import { markChatMessageAsTask } from "./ChatMessageTaskService.server";
const tx = { transaction: "shared" };
const source = { chatId: "chat_1", messageId: "message_1", body: "Heizung prüfen\nDetails", projectId: "project_1" };
const currentPermissions = ["chat.read_own_channels", "chat.write", "tasks.read_own", "tasks.write"];
const chatContext = {
tenantId: "tenant_1",
userId: "user_1",
tenantUserId: "tenant_user_1",
permissions: currentPermissions,
hasModule: true as const,
};
const taskContext = { tenantId: "tenant_1", userId: "user_1", permissions: ["tasks.write"], hasModule: true };
const input = {
chatContext,
taskContext,
chatId: "chat_1",
messageId: "message_1",
requestId: "request_1",
tenantSlug: "demo",
fallbackTitle: "Aufgabe aus Chat",
};
describe("markChatMessageAsTask", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.withWritableSource.mockImplementation(async (_input: unknown, operation: (...args: unknown[]) => unknown) =>
operation(tx, source, currentPermissions)
);
mocks.createTask.mockResolvedValue({
replayed: false,
task: { id: "task_1", linkedEntityType: "project", linkedEntityId: "project_1" },
});
mocks.linkEntities.mockResolvedValue(undefined);
mocks.auditTask.mockResolvedValue(undefined);
mocks.logActivity.mockResolvedValue(undefined);
mocks.writeSystemMessage.mockResolvedValue({ replayed: false, event: { event: "chat.message.created" } });
mocks.publishWakeup.mockResolvedValue(undefined);
mocks.hasTasksModule.mockResolvedValue(true);
});
it("writes task, backlink, strict effects and system link in one chat-authorized transaction", async () => {
await expect(markChatMessageAsTask(input)).resolves.toEqual({ taskId: "task_1", replayed: false });
expect(mocks.withWritableSource).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: "tenant_1", userId: "user_1", chatId: "chat_1", messageId: "message_1" }),
expect.any(Function)
);
expect(mocks.createTask).toHaveBeenCalledWith(
tx,
expect.objectContaining({
tenantId: "tenant_1",
title: "Heizung prüfen",
description: "Heizung prüfen\nDetails",
linkedEntityType: "project",
linkedEntityId: "project_1",
source: "chat",
sourceRef: "chat-message:message_1",
ctx: expect.objectContaining({ permissions: currentPermissions }),
})
);
expect(mocks.linkEntities).toHaveBeenCalledWith(tx, {
tenantId: "tenant_1",
userId: "user_1",
sourceType: "chat_message",
sourceId: "message_1",
targetType: "task",
targetId: "task_1",
linkRole: "created-from",
});
expect(mocks.auditTask).toHaveBeenCalledWith(expect.objectContaining({ action: "task.created", taskId: "task_1" }), { client: tx, strict: true });
expect(mocks.logActivity).toHaveBeenCalledWith(expect.objectContaining({ taskId: "task_1", activityType: "task_created", summaryText: "Heizung prüfen" }), {
client: tx,
strict: true,
});
expect(mocks.writeSystemMessage).toHaveBeenCalledWith(
tx,
expect.objectContaining({
systemEventKey: "task-created:message_1",
kind: "task_created",
metadata: expect.objectContaining({ taskId: "task_1", taskHref: "/demo/tasks/task_1" }),
})
);
expect(mocks.publishWakeup).toHaveBeenCalledOnce();
});
it("repairs the backlink and system reply on replay without duplicating audit or activity", async () => {
mocks.createTask.mockResolvedValue({ replayed: true, task: { id: "task_1", linkedEntityType: null, linkedEntityId: null } });
mocks.writeSystemMessage.mockResolvedValue({ replayed: true, event: { event: "chat.message.created" } });
await expect(markChatMessageAsTask(input)).resolves.toEqual({ taskId: "task_1", replayed: true });
expect(mocks.linkEntities).toHaveBeenCalledOnce();
expect(mocks.auditTask).not.toHaveBeenCalled();
expect(mocks.logActivity).not.toHaveBeenCalled();
expect(mocks.writeSystemMessage).toHaveBeenCalledOnce();
expect(mocks.publishWakeup).not.toHaveBeenCalled();
});
it("fails closed when tasks.write was revoked after the route context was loaded", async () => {
mocks.withWritableSource.mockImplementation(async (_input: unknown, operation: (...args: unknown[]) => unknown) =>
operation(tx, source, ["chat.read_own_channels", "chat.write"])
);
await expect(markChatMessageAsTask(input)).rejects.toMatchObject({ status: 404 });
expect(mocks.createTask).not.toHaveBeenCalled();
});
it("fails closed when the Tasks module was disabled after the route context was loaded", async () => {
mocks.hasTasksModule.mockResolvedValue(false);
await expect(markChatMessageAsTask(input)).rejects.toMatchObject({ status: 404 });
expect(mocks.hasTasksModule).toHaveBeenCalledWith(tx, "tenant_1", currentPermissions);
expect(mocks.createTask).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,110 @@
import type { OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import type { AuditEventWriterClient } from "@hivegrid/db/audit-events.server";
import { CatalogError, foundationErrors, requirePermission } from "@hivegrid/foundation";
import { publishChatPersistentRealtimeWakeup } from "@hivegrid/chat/realtime-wakeup.server";
import { withWritableChatMessageTaskSource } from "@hivegrid/chat/repository.server";
import { tenantHasTasksModuleWithPermissionsTx } from "@hivegrid/chat/module-access.server";
import { writeChatSystemMessageWithTx } from "@hivegrid/chat/system-message.server";
import type { ChatRouteContext } from "../routes/chatAccess.server";
import { linkEntitiesWithTx } from "~/utils/integrations/entityLinkService.server";
import type { TasksRouteContext } from "~/utils/integrations/taskAccess.server";
import { auditTaskEvent, logTaskActivity } from "~/utils/integrations/taskAudit.server";
import { tasksDetailPath } from "~/utils/integrations/taskRoutePaths";
import { createIdempotentTaskFromSourceWithTx } from "~/utils/integrations/taskService.server";
export async function markChatMessageAsTask(input: {
readonly chatContext: ChatRouteContext;
readonly taskContext: TasksRouteContext;
readonly chatId: string;
readonly messageId: string;
readonly requestId: string;
readonly tenantSlug: string;
readonly fallbackTitle: string;
}): Promise<{ readonly taskId: string; readonly replayed: boolean }> {
if (input.chatContext.tenantId !== input.taskContext.tenantId || input.chatContext.userId !== input.taskContext.userId) {
throw new Error("Chat and task contexts must belong to the same tenant user");
}
const tenantSlug = input.tenantSlug.trim();
if (!tenantSlug) throw new CatalogError(foundationErrors.notFound);
return withWritableChatMessageTaskSource(
{
tenantId: input.chatContext.tenantId,
userId: input.chatContext.userId,
permissions: input.chatContext.permissions,
chatId: input.chatId,
messageId: input.messageId,
},
async (tx, source, currentPermissions) => {
if (!currentPermissions.includes("tasks.write")) {
throw new CatalogError(foundationErrors.notFound, { permission: "tasks.write" });
}
if (!(await tenantHasTasksModuleWithPermissionsTx(tx, input.chatContext.tenantId, currentPermissions))) {
throw new CatalogError(foundationErrors.notFound, { module: "tasks" });
}
requirePermission({ tenantId: input.taskContext.tenantId, userId: input.taskContext.userId, permissions: currentPermissions }, "tasks.write");
const currentTaskContext = { ...input.taskContext, permissions: currentPermissions };
const firstLine = source.body
.split(/\r?\n/u)
.map((line) => line.trim())
.find(Boolean);
const title = (firstLine || input.fallbackTitle).slice(0, 255);
const result = await createIdempotentTaskFromSourceWithTx(tx, {
tenantId: currentTaskContext.tenantId,
ctx: currentTaskContext,
title,
description: source.body.trim() || null,
linkedEntityType: source.projectId ? "project" : null,
linkedEntityId: source.projectId,
source: "chat",
sourceRef: `chat-message:${source.messageId}`,
});
await linkEntitiesWithTx(tx, {
tenantId: currentTaskContext.tenantId,
userId: currentTaskContext.userId,
sourceType: "chat_message",
sourceId: source.messageId,
targetType: "task",
targetId: result.task.id,
linkRole: "created-from",
});
if (!result.replayed) {
await auditTaskEvent(
{
ctx: currentTaskContext,
action: "task.created",
taskId: result.task.id,
metadata: { source: "chat", chatId: source.chatId, messageId: source.messageId },
},
{ client: tx as unknown as AuditEventWriterClient, strict: true }
);
await logTaskActivity(
{
ctx: currentTaskContext,
taskId: result.task.id,
activityType: "task_created",
summaryText: title,
linkedEntityType: result.task.linkedEntityType,
linkedEntityId: result.task.linkedEntityId,
},
{ client: tx, strict: true }
);
}
const taskHref = tasksDetailPath(tenantSlug, result.task.id);
const systemMessage = await writeChatSystemMessageWithTx(tx, {
tenantId: currentTaskContext.tenantId,
chatId: source.chatId,
systemEventKey: `task-created:${source.messageId}`,
requestId: `${input.requestId}:task-created`,
kind: "task_created",
metadata: { sourceMessageId: source.messageId, taskId: result.task.id, taskTitle: title, taskHref },
body: `${input.fallbackTitle}: ${title}`,
actorUserId: currentTaskContext.userId,
});
if (!systemMessage.replayed) {
await publishChatPersistentRealtimeWakeup(tx as unknown as OutboxPublisherTransaction, { event: systemMessage.event });
}
return { taskId: result.task.id, replayed: result.replayed };
}
);
}
@@ -0,0 +1,249 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CHAT_PERMISSIONS, type ChatMemberChannelDetail, type ChatMemberChannelRecord, type ListMemberChannelsResult } from "@hivegrid/chat";
const mocks = vi.hoisted(() => ({
listMemberChannels: vi.fn(),
getMemberChannelDetail: vi.fn(),
listDiscoverablePublicGroupChats: vi.fn(),
joinPublicGroupChat: vi.fn(),
setChatMemberPreferences: vi.fn(),
tenantHasModule: vi.fn(),
}));
vi.mock("@hivegrid/chat/repository.server", () => ({
listMemberChannels: mocks.listMemberChannels,
getMemberChannelDetail: mocks.getMemberChannelDetail,
}));
vi.mock("@hivegrid/chat/discovery.server", () => ({
listDiscoverablePublicGroupChats: mocks.listDiscoverablePublicGroupChats,
}));
vi.mock("@hivegrid/chat/lifecycle.server", () => ({
joinPublicGroupChat: mocks.joinPublicGroupChat,
}));
vi.mock("@hivegrid/chat/member-preferences.server", () => ({
setChatMemberPreferences: mocks.setChatMemberPreferences,
}));
vi.mock("~/utils/connector/tenantConnector.server", () => ({
tenantHasModule: mocks.tenantHasModule,
}));
vi.mock("../routes/chatAccess.server", () => ({
requireChatPermission: (context: unknown) => context,
}));
import { joinPublicChatChannel, loadMemberChatChannel, loadMemberChatChannels, updateOwnChatChannelPreferences } from "./ChatService.server";
import type { ChatRouteContext } from "../routes/chatAccess.server";
const context: ChatRouteContext = {
tenantId: "tenant_1",
userId: "user_1",
tenantUserId: "tenant_user_1",
permissions: [CHAT_PERMISSIONS.readOwnChannels, CHAT_PERMISSIONS.write],
hasModule: true,
};
const labels = {
directMessage: "Direktnachricht",
unnamedGroup: "Unbenannte Gruppe",
unnamedProject: "Projektchat",
unknownUser: "Unbekannte Person",
unknownMention: "Unbekannte Erwähnung",
};
const emptyChannelResult: ListMemberChannelsResult = { channels: [], nextCursor: null };
const listedChannel: ChatMemberChannelRecord = {
id: "chat_1",
kind: "group",
name: "Montage",
description: null,
projektId: null,
isPrivate: false,
archivedAtIso: null,
lastMessageAtIso: null,
eventStreamId: "stream_1",
eventCursor: "stream_1:12",
member: {
roleInChat: "member",
notificationPreference: "all_messages",
lastReadMessageId: null,
lastReadAtIso: null,
isPinned: false,
canWrite: true,
},
memberCount: 1,
participants: [{ userId: "user_1", displayName: "Raffael Sheikh", avatarUrl: null }],
unreadCount: 0,
hasUnreadMention: false,
lastMessage: null,
};
describe("ChatService", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.listMemberChannels.mockResolvedValue(emptyChannelResult);
mocks.listDiscoverablePublicGroupChats.mockResolvedValue({ channels: [] });
mocks.joinPublicGroupChat.mockResolvedValue({ chatId: "chat_public", memberUserId: "user_1", roleInChat: "member", changed: true });
mocks.setChatMemberPreferences.mockResolvedValue({ chatId: "chat_1", isPinned: true, notificationPreference: "muted", changed: true });
mocks.tenantHasModule.mockResolvedValue(true);
});
it("passes the authenticated tenant/user context into the RLS repository list", async () => {
mocks.listMemberChannels.mockResolvedValue({ channels: [listedChannel], nextCursor: "next_cursor" });
const vm = await loadMemberChatChannels({
context,
tenantSlug: "demo",
filter: { query: "Montage", view: "groups", showArchived: true },
afterCursor: "current_cursor",
limit: 25,
labels,
});
expect(mocks.listMemberChannels).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: context.permissions,
query: "Montage",
view: "groups",
includeArchived: true,
afterCursor: "current_cursor",
limit: 25,
});
expect(vm.status).toBe("ready");
expect(vm.data?.rows.map((row) => row.id)).toEqual(["chat_1"]);
expect(vm.data?.nextCursor).toBe("next_cursor");
expect(mocks.listDiscoverablePublicGroupChats).not.toHaveBeenCalled();
});
it("loads discoverable public groups only on the first page and maps no pre-join detail link", async () => {
mocks.listDiscoverablePublicGroupChats.mockResolvedValue({
channels: [{ id: "chat_public", name: "Montage Nord", description: "Austausch", memberCount: 4 }],
});
const vm = await loadMemberChatChannels({
context,
tenantSlug: "demo",
filter: { query: "Montage", view: "all", showArchived: false },
labels,
});
expect(mocks.listDiscoverablePublicGroupChats).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: context.permissions,
query: "Montage",
});
expect(vm.status).toBe("ready");
expect(vm.data?.permissions.canDiscover).toBe(true);
expect(vm.data?.discoverRows).toEqual([
expect.objectContaining({
id: "chat_public",
title: "Montage Nord",
memberCount: 4,
canJoin: true,
joinHref: "/demo/chat",
detailHref: null,
}),
]);
});
it("joins through the lifecycle boundary with the authenticated tenant context", async () => {
await joinPublicChatChannel({ context, chatId: "chat_public", requestId: "request_join_1" });
expect(mocks.joinPublicGroupChat).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: context.permissions,
chatId: "chat_public",
requestId: "request_join_1",
});
});
it("updates only the authenticated member's channel preferences through the RLS boundary", async () => {
await updateOwnChatChannelPreferences({
context,
chatId: "chat_1",
requestId: "request_preferences_1",
isPinned: true,
notificationPreference: "muted",
});
expect(mocks.setChatMemberPreferences).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: context.permissions,
chatId: "chat_1",
requestId: "request_preferences_1",
isPinned: true,
notificationPreference: "muted",
});
});
it("passes the opaque history cursor and returns the repository event cursor", async () => {
const detail: ChatMemberChannelDetail = {
channel: {
id: "chat_1",
kind: "group",
name: "Montage",
description: null,
projektId: null,
isPrivate: false,
archivedAtIso: null,
lastMessageAtIso: null,
eventStreamId: "stream_1",
eventCursor: "stream_1:12",
member: {
roleInChat: "member",
notificationPreference: "all_messages",
lastReadMessageId: null,
lastReadAtIso: null,
isPinned: false,
},
memberCount: 1,
participants: [{ userId: "user_1", displayName: "Raffael Sheikh", avatarUrl: null }],
unreadCount: 0,
hasUnreadMention: false,
lastMessage: null,
},
messages: [],
readReceipts: [],
attachments: [],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:12",
};
mocks.getMemberChannelDetail.mockResolvedValue(detail);
const result = await loadMemberChatChannel({
context,
tenantSlug: "demo",
chatId: "chat_1",
beforeMessageCursor: "opaque_cursor",
labels,
});
expect(mocks.getMemberChannelDetail).toHaveBeenCalledWith({
tenantId: "tenant_1",
userId: "user_1",
permissions: context.permissions,
chatId: "chat_1",
beforeMessageCursor: "opaque_cursor",
});
expect(mocks.tenantHasModule).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", moduleKey: "files" });
expect(mocks.tenantHasModule).toHaveBeenCalledWith({ tenantId: "tenant_1", userId: "user_1", moduleKey: "tasks" });
expect(result.eventCursor).toBe("stream_1:12");
expect(result.authors).toEqual([
{
userId: "user_1",
displayName: "Raffael Sheikh",
avatar: { imageUrl: null, fallbackLabel: "RS" },
isCurrentUser: true,
},
]);
expect(result.vm.status).toBe("ready");
});
});
@@ -0,0 +1,148 @@
import { CHAT_PERMISSIONS, type ChatNotificationPreference } from "@hivegrid/chat";
import { listDiscoverablePublicGroupChats } from "@hivegrid/chat/discovery.server";
import { joinPublicGroupChat } from "@hivegrid/chat/lifecycle.server";
import { setChatMemberPreferences } from "@hivegrid/chat/member-preferences.server";
import { getMemberChannelDetail, listMemberChannels, sendTopLevelChatMessage } from "@hivegrid/chat/repository.server";
import type { ChatChannelDetailVM, ChatChannelListFilterState, ChatChannelListVM, ChatResolvedAuthorVM } from "@hivegrid/view-models";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { requireChatPermission, type ChatRouteContext } from "../routes/chatAccess.server";
import { buildMemberChatChannelDetailVM, buildMemberChatChannelListVM, buildChatResolvedAuthors, type ChatViewModelLabels } from "./chatViewModel.server";
export async function loadMemberChatChannels(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly filter: ChatChannelListFilterState;
readonly afterCursor?: string;
readonly limit?: number;
readonly labels: ChatViewModelLabels;
}): Promise<ChatChannelListVM> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
const [result, discover] = await Promise.all([
listMemberChannels({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
query: input.filter.query,
view: input.filter.view,
includeArchived: input.filter.showArchived,
afterCursor: input.afterCursor,
limit: input.limit,
}),
input.afterCursor
? Promise.resolve(undefined)
: listDiscoverablePublicGroupChats({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
query: input.filter.query,
}),
]);
return buildMemberChatChannelListVM({
channels: result.channels,
tenantSlug: input.tenantSlug,
currentUserId: context.userId,
permissions: context.permissions,
filter: input.filter,
nextCursor: result.nextCursor,
discoverChannels: discover?.channels,
labels: input.labels,
});
}
export async function joinPublicChatChannel(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly requestId: string;
}) {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
return joinPublicGroupChat({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
requestId: input.requestId,
});
}
export async function updateOwnChatChannelPreferences(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly requestId: string;
readonly isPinned?: boolean;
readonly notificationPreference?: ChatNotificationPreference;
}) {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
return setChatMemberPreferences({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
requestId: input.requestId,
...(input.isPinned === undefined ? {} : { isPinned: input.isPinned }),
...(input.notificationPreference === undefined ? {} : { notificationPreference: input.notificationPreference }),
});
}
export async function loadMemberChatChannel(input: {
readonly context: ChatRouteContext;
readonly tenantSlug: string;
readonly chatId: string;
readonly beforeMessageCursor?: string;
readonly focusMessageId?: string;
readonly labels: ChatViewModelLabels;
}): Promise<{
readonly vm: ChatChannelDetailVM;
readonly eventCursor: string;
readonly authors: readonly ChatResolvedAuthorVM[];
}> {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.readOwnChannels);
const [detail, filesEnabled, tasksEnabled] = await Promise.all([
getMemberChannelDetail({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
...(input.beforeMessageCursor ? { beforeMessageCursor: input.beforeMessageCursor } : {}),
...(input.focusMessageId ? { focusMessageId: input.focusMessageId } : {}),
}),
tenantHasModule({ tenantId: context.tenantId, userId: context.userId, moduleKey: "files" }),
tenantHasModule({ tenantId: context.tenantId, userId: context.userId, moduleKey: "tasks" }),
]);
return {
vm: buildMemberChatChannelDetailVM({
detail,
tenantSlug: input.tenantSlug,
currentUserId: context.userId,
permissions: context.permissions,
nowIso: new Date().toISOString(),
featureAvailability: { files: filesEnabled, tasks: tasksEnabled },
labels: input.labels,
}),
eventCursor: detail.eventCursor,
authors: buildChatResolvedAuthors(detail.channel.participants, context.userId),
};
}
export async function sendMemberChatMessage(input: {
readonly context: ChatRouteContext;
readonly chatId: string;
readonly clientMessageId: string;
readonly requestId: string;
readonly body: string;
readonly attachmentFileIds: readonly string[];
}) {
const context = requireChatPermission(input.context, CHAT_PERMISSIONS.write);
return sendTopLevelChatMessage({
tenantId: context.tenantId,
userId: context.userId,
permissions: context.permissions,
chatId: input.chatId,
clientMessageId: input.clientMessageId,
requestId: input.requestId,
body: input.body,
attachmentFileIds: input.attachmentFileIds,
});
}
@@ -0,0 +1,74 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@hivegrid/config", async (importOriginal) => {
const actual = await importOriginal<typeof import("@hivegrid/config")>();
return {
...actual,
loadRequiredWebConfig: () => ({
nodeEnv: "test",
routing: {
appHost: "app.localhost",
adminHost: "admin.localhost",
marketingHost: "localhost",
protocol: "http",
},
sessionSecret: "chat-audit-test-session-secret-with-enough-entropy",
}),
};
});
import {
__resetChatAuditSessionCookieForTests,
beginChatAuditSession,
CHAT_AUDIT_SESSION_TTL_MS,
normalizeChatAuditReason,
readChatAuditSession,
} from "./chatAuditSession.server";
describe("AK-P15b short-lived chat audit sessions", () => {
beforeEach(() => __resetChatAuditSessionCookieForTests());
it("binds the signed reason session to its tenant and user", async () => {
const now = new Date("2026-07-16T10:00:00.000Z");
const issued = await beginChatAuditSession({
tenantId: "tenant-a",
userId: "admin-a",
reason: " Kundenreklamation nachvollziehen ",
now,
sessionId: "audit-session-1",
});
const request = requestWithCookie(issued.cookie);
await expect(readChatAuditSession({ request, tenantId: "tenant-a", userId: "admin-a", now })).resolves.toMatchObject({
id: "audit-session-1",
reason: "Kundenreklamation nachvollziehen",
expiresAt: now.getTime() + CHAT_AUDIT_SESSION_TTL_MS,
});
await expect(readChatAuditSession({ request, tenantId: "tenant-b", userId: "admin-a", now })).resolves.toBeNull();
await expect(readChatAuditSession({ request, tenantId: "tenant-a", userId: "admin-b", now })).resolves.toBeNull();
});
it("expires server-side even when a client retains the cookie", async () => {
const now = new Date("2026-07-16T10:00:00.000Z");
const issued = await beginChatAuditSession({ tenantId: "tenant-a", userId: "admin-a", reason: "Audit", now });
await expect(
readChatAuditSession({
request: requestWithCookie(issued.cookie),
tenantId: "tenant-a",
userId: "admin-a",
now: new Date(now.getTime() + CHAT_AUDIT_SESSION_TTL_MS),
})
).resolves.toBeNull();
});
it("rejects a missing justification", () => {
expect(normalizeChatAuditReason(" \n ")).toBeNull();
expect(normalizeChatAuditReason("Legitimer Supportfall")).toBe("Legitimer Supportfall");
});
});
function requestWithCookie(setCookie: string): Request {
return new Request("http://app.localhost/demo/settings/chat/audit", {
headers: { cookie: setCookie.split(";", 1)[0]! },
});
}
@@ -0,0 +1,153 @@
import { randomUUID } from "node:crypto";
import { createCookie } from "react-router";
import { loadRequiredWebConfig, resolveHostOnlyCookiePolicy } from "@hivegrid/config";
export const CHAT_AUDIT_SESSION_TTL_MS = 15 * 60 * 1_000;
export const CHAT_AUDIT_REASON_MAX_LENGTH = 500;
const CLOCK_SKEW_MS = 30 * 1_000;
const SECURE_COOKIE_NAME = "__Host-hivegrid_chat_audit";
const LOCAL_COOKIE_NAME = "hivegrid_chat_audit";
const PAYLOAD_VERSION = 1;
export type ChatAuditSession = Readonly<{
id: string;
tenantId: string;
userId: string;
reason: string;
issuedAt: number;
expiresAt: number;
}>;
type StoredChatAuditSession = ChatAuditSession & { readonly version: typeof PAYLOAD_VERSION };
let cachedCookie: ReturnType<typeof createCookie> | null = null;
function getChatAuditCookie(): ReturnType<typeof createCookie> {
if (cachedCookie) return cachedCookie;
const config = loadRequiredWebConfig();
const policy = resolveHostOnlyCookiePolicy({
nodeEnv: config.nodeEnv,
routing: config.routing,
secureName: SECURE_COOKIE_NAME,
localName: LOCAL_COOKIE_NAME,
maxAge: Math.ceil(CHAT_AUDIT_SESSION_TTL_MS / 1_000),
});
cachedCookie = createCookie(policy.name, {
httpOnly: true,
sameSite: "strict",
path: policy.path,
secure: policy.secure,
maxAge: policy.maxAge,
secrets: config.sessionSecret ? [config.sessionSecret] : [],
});
return cachedCookie;
}
export async function beginChatAuditSession(input: {
readonly tenantId: string;
readonly userId: string;
readonly reason: string;
readonly now?: Date;
readonly sessionId?: string;
}): Promise<{ readonly session: ChatAuditSession; readonly cookie: string }> {
const now = input.now ?? new Date();
const reason = normalizeReason(input.reason);
const session: ChatAuditSession = {
id: normalizeIdentifier(input.sessionId ?? randomUUID(), "session id"),
tenantId: normalizeIdentifier(input.tenantId, "tenant id"),
userId: normalizeIdentifier(input.userId, "user id"),
reason,
issuedAt: now.getTime(),
expiresAt: now.getTime() + CHAT_AUDIT_SESSION_TTL_MS,
};
const stored: StoredChatAuditSession = { version: PAYLOAD_VERSION, ...session };
return { session, cookie: await getChatAuditCookie().serialize(stored) };
}
export async function readChatAuditSession(input: {
readonly request: Request;
readonly tenantId: string;
readonly userId: string;
readonly now?: Date;
}): Promise<ChatAuditSession | null> {
let parsed: unknown;
try {
parsed = await getChatAuditCookie().parse(input.request.headers.get("cookie"));
} catch {
return null;
}
const session = parseStoredSession(parsed);
if (!session) return null;
const now = (input.now ?? new Date()).getTime();
if (
session.tenantId !== input.tenantId ||
session.userId !== input.userId ||
now < session.issuedAt - CLOCK_SKEW_MS ||
now >= session.expiresAt ||
session.expiresAt - session.issuedAt !== CHAT_AUDIT_SESSION_TTL_MS
) {
return null;
}
return session;
}
export function clearChatAuditSession(): Promise<string> {
return getChatAuditCookie().serialize("", { maxAge: 0, expires: new Date(0) });
}
export function normalizeChatAuditReason(value: unknown): string | null {
if (typeof value !== "string") return null;
try {
return normalizeReason(value);
} catch {
return null;
}
}
export function __resetChatAuditSessionCookieForTests(): void {
cachedCookie = null;
}
function parseStoredSession(value: unknown): ChatAuditSession | null {
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const row = value as Record<string, unknown>;
if (
row.version !== PAYLOAD_VERSION ||
typeof row.id !== "string" ||
typeof row.tenantId !== "string" ||
typeof row.userId !== "string" ||
typeof row.reason !== "string" ||
typeof row.issuedAt !== "number" ||
typeof row.expiresAt !== "number" ||
!Number.isFinite(row.issuedAt) ||
!Number.isFinite(row.expiresAt)
) {
return null;
}
try {
return {
id: normalizeIdentifier(row.id, "session id"),
tenantId: normalizeIdentifier(row.tenantId, "tenant id"),
userId: normalizeIdentifier(row.userId, "user id"),
reason: normalizeReason(row.reason),
issuedAt: row.issuedAt,
expiresAt: row.expiresAt,
};
} catch {
return null;
}
}
function normalizeReason(value: string): string {
const reason = value.trim().replace(/\s+/g, " ");
if (!reason || reason.length > CHAT_AUDIT_REASON_MAX_LENGTH || reason.includes("\0")) {
throw new Error("A chat audit reason is required");
}
return reason;
}
function normalizeIdentifier(value: string, label: string): string {
const normalized = value.trim();
if (!normalized || normalized.length > 500 || normalized.includes("\0")) throw new Error(`${label} is invalid`);
return normalized;
}
@@ -0,0 +1,100 @@
// @vitest-environment node
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
CHAT_GATEWAY_TOKEN_SESSION_LIMIT,
CHAT_GATEWAY_TOKEN_USER_LIMIT,
__resetChatGatewayTokenRateLimitStoreForTests,
__setChatGatewayTokenRateLimitStoreForTests,
checkChatGatewayTokenRateLimit,
} from "./chatGatewayRateLimit.server";
const stores: Array<ReturnType<typeof createSharedStore>> = [];
function useMemoryStore() {
const store = createSharedStore({ namespace: "chat-token-rate-test", adapter: new MemoryAdapter() });
stores.push(store);
__setChatGatewayTokenRateLimitStoreForTests(store);
return store;
}
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-07-15T12:00:00.000Z"));
useMemoryStore();
});
afterEach(async () => {
__resetChatGatewayTokenRateLimitStoreForTests();
vi.useRealTimers();
await Promise.allSettled(stores.splice(0).map((store) => store.close()));
});
describe("chat gateway token rate limit", () => {
it("atomically caps token minting per session and resets with the fixed window", async () => {
const input = { tenantId: "tenant_1", userId: "user_1", sessionId: "session_1" };
const reservations = await Promise.all(Array.from({ length: CHAT_GATEWAY_TOKEN_SESSION_LIMIT + 1 }, () => checkChatGatewayTokenRateLimit(input)));
expect(reservations.filter((result) => result.allowed)).toHaveLength(CHAT_GATEWAY_TOKEN_SESSION_LIMIT);
expect(reservations.filter((result) => !result.allowed)).toEqual([{ allowed: false, retryAfterSeconds: 60 }]);
vi.advanceTimersByTime(60_000);
await expect(checkChatGatewayTokenRateLimit(input)).resolves.toMatchObject({ allowed: true });
});
it("applies an authoritative tenant-user cap across independent sessions", async () => {
for (let index = 0; index < CHAT_GATEWAY_TOKEN_USER_LIMIT; index += 1) {
await expect(
checkChatGatewayTokenRateLimit({
tenantId: "tenant_1",
userId: "user_1",
sessionId: `session_${Math.floor(index / CHAT_GATEWAY_TOKEN_SESSION_LIMIT)}`,
})
).resolves.toMatchObject({ allowed: true });
}
await expect(checkChatGatewayTokenRateLimit({ tenantId: "tenant_1", userId: "user_1", sessionId: "session_fresh" })).resolves.toEqual({
allowed: false,
retryAfterSeconds: 60,
});
await expect(checkChatGatewayTokenRateLimit({ tenantId: "tenant_2", userId: "user_1", sessionId: "session_fresh" })).resolves.toMatchObject({
allowed: true,
});
});
it("does not consume a session budget when the user-wide reservation is denied", async () => {
for (let index = 0; index < CHAT_GATEWAY_TOKEN_USER_LIMIT; index += 1) {
await checkChatGatewayTokenRateLimit({
tenantId: "tenant_1",
userId: "user_1",
sessionId: `session_${Math.floor(index / CHAT_GATEWAY_TOKEN_SESSION_LIMIT)}`,
});
}
vi.advanceTimersByTime(30_000);
await expect(checkChatGatewayTokenRateLimit({ tenantId: "tenant_1", userId: "user_1", sessionId: "session_fresh" })).resolves.toMatchObject({
allowed: false,
});
vi.advanceTimersByTime(30_001);
const nextWindow = await Promise.all(
Array.from({ length: CHAT_GATEWAY_TOKEN_SESSION_LIMIT }, () =>
checkChatGatewayTokenRateLimit({ tenantId: "tenant_1", userId: "user_1", sessionId: "session_fresh" })
)
);
expect(nextWindow.every((result) => result.allowed)).toBe(true);
await expect(checkChatGatewayTokenRateLimit({ tenantId: "tenant_1", userId: "user_1", sessionId: "session_fresh" })).resolves.toMatchObject({
allowed: false,
});
});
it("fails closed when the shared rate-limit store is unavailable", async () => {
const store = stores.at(-1);
if (!store) throw new Error("Expected a test store");
await store.close();
await expect(checkChatGatewayTokenRateLimit({ tenantId: "tenant_1", userId: "user_1", sessionId: "session_1" })).rejects.toThrow(/closed/i);
});
});
@@ -0,0 +1,165 @@
import { MemoryAdapter, type SharedStore } from "@hivegrid/shared-store";
import { getSharedStore } from "~/shared-store.server";
export const CHAT_GATEWAY_TOKEN_SESSION_LIMIT = 20;
export const CHAT_GATEWAY_TOKEN_USER_LIMIT = 60;
export const CHAT_GATEWAY_TOKEN_WINDOW_SECONDS = 60;
const CHAT_GATEWAY_TOKEN_WINDOW_MS = CHAT_GATEWAY_TOKEN_WINDOW_SECONDS * 1_000;
const CHAT_GATEWAY_TOKEN_RATE_LIMIT_SCRIPT = `
local time = redis.call("TIME")
local now = (tonumber(time[1]) * 1000) + math.floor(tonumber(time[2]) / 1000)
local window_ms = tonumber(ARGV[1])
local session_limit = tonumber(ARGV[2])
local user_limit = tonumber(ARGV[3])
if not window_ms or window_ms <= 0 or not session_limit or session_limit <= 0 or
not user_limit or user_limit < session_limit then
return redis.error_reply("invalid chat token rate limit arguments")
end
local function read_bucket(key)
local raw = redis.call("GET", key)
if not raw then
return { count = 0, resetAt = now + window_ms }
end
local ok, bucket = pcall(cjson.decode, raw)
if not ok or type(bucket) ~= "table" or type(bucket.count) ~= "number" or
bucket.count < 0 or bucket.count % 1 ~= 0 or type(bucket.resetAt) ~= "number" then
return nil
end
if bucket.resetAt <= now then
return { count = 0, resetAt = now + window_ms }
end
return bucket
end
local session_bucket = read_bucket(KEYS[1])
local user_bucket = read_bucket(KEYS[2])
if not session_bucket or not user_bucket then
return redis.error_reply("invalid chat token rate limit bucket")
end
local session_blocked = session_bucket.count >= session_limit
local user_blocked = user_bucket.count >= user_limit
if session_blocked or user_blocked then
local retry_after_ms = 1
if session_blocked then retry_after_ms = math.max(retry_after_ms, session_bucket.resetAt - now) end
if user_blocked then retry_after_ms = math.max(retry_after_ms, user_bucket.resetAt - now) end
return { 0, 0, retry_after_ms }
end
session_bucket.count = session_bucket.count + 1
user_bucket.count = user_bucket.count + 1
redis.call("SET", KEYS[1], cjson.encode(session_bucket), "PX", math.max(1, session_bucket.resetAt - now))
redis.call("SET", KEYS[2], cjson.encode(user_bucket), "PX", math.max(1, user_bucket.resetAt - now))
local remaining = math.min(session_limit - session_bucket.count, user_limit - user_bucket.count)
return { 1, remaining, 0 }
`;
export type ChatGatewayTokenRateLimitInput = {
tenantId: string;
userId: string;
sessionId: string;
};
export type ChatGatewayTokenRateLimitResult = { allowed: true; remaining: number } | { allowed: false; retryAfterSeconds: number };
let storeFactory: () => SharedStore = () => getSharedStore();
export async function checkChatGatewayTokenRateLimit(input: ChatGatewayTokenRateLimitInput): Promise<ChatGatewayTokenRateLimitResult> {
const scope = `${encodeKeyPart(input.tenantId)}:${encodeKeyPart(input.userId)}`;
const result = await storeFactory().eval(
CHAT_GATEWAY_TOKEN_RATE_LIMIT_SCRIPT,
[`token-session:${scope}:${encodeKeyPart(input.sessionId)}`, `token-user:${scope}`],
[String(CHAT_GATEWAY_TOKEN_WINDOW_MS), String(CHAT_GATEWAY_TOKEN_SESSION_LIMIT), String(CHAT_GATEWAY_TOKEN_USER_LIMIT), String(Date.now())]
);
const decision = parseDecision(result);
if (decision.allowed) return { allowed: true, remaining: decision.remaining };
return { allowed: false, retryAfterSeconds: Math.max(1, Math.ceil(decision.retryAfterMs / 1_000)) };
}
function parseDecision(result: unknown): { allowed: true; remaining: number } | { allowed: false; retryAfterMs: number } {
if (!Array.isArray(result) || result.length !== 3) throw new Error("chat token rate limit returned an invalid result");
const allowed = Number(result[0]);
const remaining = Number(result[1]);
const retryAfterMs = Number(result[2]);
if ((allowed !== 0 && allowed !== 1) || !Number.isSafeInteger(remaining) || remaining < 0 || !Number.isFinite(retryAfterMs) || retryAfterMs < 0) {
throw new Error("chat token rate limit returned an invalid result");
}
return allowed === 1 ? { allowed: true, remaining } : { allowed: false, retryAfterMs };
}
function encodeKeyPart(value: string): string {
return Buffer.from(value, "utf8").toString("base64url");
}
type TokenRateBucket = { count: number; resetAt: number };
async function runTokenRateLimitInMemory(adapter: MemoryAdapter, keys: string[], args: string[]): Promise<[number, number, number]> {
if (keys.length !== 2 || args.length !== 4) throw new Error("invalid chat token rate limit arguments");
const windowMs = requirePositiveInteger(args[0], "window");
const sessionLimit = requirePositiveInteger(args[1], "session limit");
const userLimit = requirePositiveInteger(args[2], "user limit");
const now = Number(args[3]);
if (userLimit < sessionLimit || !Number.isFinite(now)) throw new Error("invalid chat token rate limit arguments");
const sessionBucket = readBucket(await adapter.get(keys[0] ?? ""), now, windowMs);
const userBucket = readBucket(await adapter.get(keys[1] ?? ""), now, windowMs);
const sessionBlocked = sessionBucket.count >= sessionLimit;
const userBlocked = userBucket.count >= userLimit;
if (sessionBlocked || userBlocked) {
return [0, 0, Math.max(1, sessionBlocked ? sessionBucket.resetAt - now : 0, userBlocked ? userBucket.resetAt - now : 0)];
}
sessionBucket.count += 1;
userBucket.count += 1;
await Promise.all([persistBucket(adapter, keys[0], sessionBucket, now), persistBucket(adapter, keys[1], userBucket, now)]);
return [1, Math.min(sessionLimit - sessionBucket.count, userLimit - userBucket.count), 0];
}
function readBucket(raw: string | null, now: number, windowMs: number): TokenRateBucket {
if (raw === null) return { count: 0, resetAt: now + windowMs };
let parsed: unknown;
try {
parsed = JSON.parse(raw) as unknown;
} catch {
throw new Error("invalid chat token rate limit bucket");
}
if (
typeof parsed !== "object" ||
parsed === null ||
Array.isArray(parsed) ||
!Number.isSafeInteger((parsed as Partial<TokenRateBucket>).count) ||
((parsed as Partial<TokenRateBucket>).count ?? -1) < 0 ||
!Number.isFinite((parsed as Partial<TokenRateBucket>).resetAt)
) {
throw new Error("invalid chat token rate limit bucket");
}
const bucket = parsed as TokenRateBucket;
return bucket.resetAt <= now ? { count: 0, resetAt: now + windowMs } : bucket;
}
async function persistBucket(adapter: MemoryAdapter, key: string | undefined, bucket: TokenRateBucket, now: number): Promise<void> {
if (!key) throw new Error("invalid chat token rate limit key");
const stored = await adapter.set(key, JSON.stringify(bucket), { ttlSeconds: Math.max(1, Math.ceil((bucket.resetAt - now) / 1_000)) });
if (!stored) throw new Error("chat token rate limit bucket could not be stored");
}
function requirePositiveInteger(value: string | undefined, label: string): number {
const parsed = Number(value);
if (!Number.isSafeInteger(parsed) || parsed <= 0) throw new Error(`invalid chat token rate limit ${label}`);
return parsed;
}
MemoryAdapter.registerScript(CHAT_GATEWAY_TOKEN_RATE_LIMIT_SCRIPT, runTokenRateLimitInMemory);
export function __setChatGatewayTokenRateLimitStoreForTests(store: SharedStore): void {
storeFactory = () => store;
}
export function __resetChatGatewayTokenRateLimitStoreForTests(): void {
storeFactory = () => getSharedStore();
}
@@ -0,0 +1,491 @@
import { describe, expect, it } from "vitest";
import type { ChatMemberChannelDetail, ChatMemberChannelRecord } from "@hivegrid/chat";
import type { ChatRealtimeSystemMessage } from "@hivegrid/realtime";
import { buildMemberChatChannelDetailVM, buildMemberChatChannelListVM, type ChatViewModelLabels } from "./chatViewModel.server";
const labels: ChatViewModelLabels = {
directMessage: "Direktnachricht",
unnamedGroup: "Unbenannte Gruppe",
unnamedProject: "Projektchat",
unknownUser: "Unbekannte Person",
unknownMention: "Unbekannte Erwähnung",
};
const channel = (overrides: Partial<ChatMemberChannelRecord> = {}): ChatMemberChannelRecord => ({
id: "chat_1",
kind: "dm",
name: null,
description: null,
projektId: null,
isPrivate: true,
archivedAtIso: null,
lastMessageAtIso: "2026-07-15T10:00:00.000Z",
eventStreamId: "stream_1",
eventCursor: "stream_1:8",
member: {
roleInChat: "member",
notificationPreference: "all_messages",
lastReadMessageId: null,
lastReadAtIso: null,
isPinned: false,
canWrite: true,
},
memberCount: 2,
participants: [
{ userId: "user_me", displayName: "Raffael Sheikh", avatarUrl: "/avatars/user_me?v=1" },
{ userId: "user_other", displayName: "Ada Lovelace", avatarUrl: null },
],
unreadCount: 1,
hasUnreadMention: true,
lastMessage: {
id: "message_1",
clientMessageId: "client_1",
authorUserId: "user_other",
body: "Hallo Raffael",
bodyFormat: "markdown",
parentMessageId: null,
mentions: [{ type: "user", id: "user_me", label: null }],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-15T10:00:00.000Z",
updatedAt: "2026-07-15T10:00:00.000Z",
editedAt: null,
deletedAt: null,
},
...overrides,
});
const systemMessage = (overrides: Partial<ChatRealtimeSystemMessage> = {}): ChatRealtimeSystemMessage => ({
id: "system_message_1",
clientMessageId: "system:project-created:project_1",
authorUserId: null,
body: "stored fallback copy",
bodyFormat: "system",
systemEvent: { kind: "project_created", metadata: { projectName: "Wärmepumpe Müller" } },
parentMessageId: null,
mentions: [],
attachmentIds: [],
linkPreviews: [],
createdAt: "2026-07-15T10:00:00.000Z",
updatedAt: "2026-07-15T10:00:00.000Z",
editedAt: null,
deletedAt: null,
...overrides,
});
describe("chatViewModel.server", () => {
it("maps the repository page without applying query, view, or archive filters a second time", () => {
const vm = buildMemberChatChannelListVM({
channels: [channel(), channel({ id: "chat_archived", archivedAtIso: "2026-07-14T10:00:00.000Z", unreadCount: 3 })],
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write", "chat.create_dm"],
filter: { query: "ada", view: "mentions", showArchived: false },
nextCursor: "next_cursor",
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.rows).toHaveLength(2);
expect(vm.data.rows[0]).toMatchObject({
id: "chat_1",
title: "Ada Lovelace",
detailHref: "/demo/chat/chat_1",
unreadCount: 1,
hasMention: true,
avatar: { fallbackLabel: "AL" },
});
expect(vm.data.totals).toEqual({ unread: 4, mentions: 2 });
expect(vm.data.nextCursor).toBe("next_cursor");
expect(vm.data.permissions).toMatchObject({ canWrite: true, canCreateDm: true, canCreateGroup: false, canSearch: true });
expect(vm.data.hrefs).toMatchObject({
newChannel: "/demo/chat/new?kind=group",
newDm: "/demo/chat/new?kind=dm",
});
});
it("renders a bounded plain-text channel snippet from long markdown", () => {
const markdown = `**Wichtig** [Plan](https://example.com) ${"x".repeat(300)}`;
const vm = buildMemberChatChannelListVM({
channels: [channel({ lastMessage: { ...channel().lastMessage!, body: markdown } })],
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels"],
filter: { query: "", view: "all", showArchived: false },
nextCursor: null,
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.rows[0]?.lastMessage?.snippet).toMatch(/^Wichtig Plan x+…$/);
expect(vm.data.rows[0]?.lastMessage?.snippet).toHaveLength(160);
});
it("maps discoverable public groups to join-only rows without exposing a detail route", () => {
const vm = buildMemberChatChannelListVM({
channels: [],
discoverChannels: [{ id: "chat_public", name: "Montage Nord", description: "Offener Austausch", memberCount: 7 }],
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels"],
filter: { query: "", view: "all", showArchived: false },
nextCursor: null,
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.permissions.canDiscover).toBe(true);
expect(vm.data.discoverRows).toEqual([
{
id: "chat_public",
title: "Montage Nord",
description: "Offener Austausch",
avatar: { imageUrl: null, fallbackLabel: "MN" },
memberCount: 7,
isJoined: false,
canJoin: true,
joinHref: "/demo/chat",
detailHref: null,
},
]);
});
it("maps the latest system event to an i18n preview without a fake author", () => {
const vm = buildMemberChatChannelListVM({
channels: [channel({ lastMessage: systemMessage() })],
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels"],
filter: { query: "", view: "all", showArchived: false },
nextCursor: null,
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.rows[0]?.lastMessage).toMatchObject({
authorLabel: null,
snippet: "",
systemEvent: {
kind: "project_created",
labelKey: "chat.systemEvent.projectCreated",
values: { project: "Wärmepumpe Müller" },
},
});
});
it("maps persisted messages, resolved mentions, reads and the enabled thread/reaction actions", () => {
const detail: ChatMemberChannelDetail = {
channel: channel(),
messages: [channel().lastMessage!],
readReceipts: [{ messageId: "message_1", userId: "user_me", readAtIso: "2026-07-15T10:01:00.000Z" }],
attachments: [
{
messageId: "message_1",
fileId: "file_1",
displayName: "camera.jpg",
mimeType: "image/jpeg",
sizeBytes: 1024,
linkRole: "image",
previewStatus: "ready",
scanStatus: "clean",
},
],
hasOlderMessages: true,
olderMessageCursor: "opaque_cursor",
eventCursor: "stream_1:8",
};
const vm = buildMemberChatChannelDetailVM({
detail,
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write", "files.write", "tasks.write"],
featureAvailability: { files: true, tasks: true },
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.header).toMatchObject({ title: "Ada Lovelace", kind: "dm", pinnedHref: null });
expect(vm.data.history).toEqual({ hasOlder: true, olderCursor: "opaque_cursor" });
expect(vm.data.messages[0]).toMatchObject({
source: "persisted",
deliveryState: "sent",
author: { displayName: "Ada Lovelace", isCurrentUser: false },
mentions: [{ kind: "user", id: "user_me", label: "Raffael Sheikh", href: null }],
readAggregate: { readCount: 1, recipientCount: 1, readerUserIds: ["user_me"], readerLabels: ["Raffael Sheikh"] },
attachments: [{ fileId: "file_1", kind: "image", previewHref: "/demo/media/file_1/preview", scanStatus: "clean" }],
actions: { canReact: true, canReply: true, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: true },
});
expect(vm.data.composer).toMatchObject({
enabled: true,
canSend: true,
canMention: true,
canAttachFiles: true,
canRecordVoice: true,
canMarkAsTask: true,
});
});
it("projects reactions, one-level thread aggregates, and pins for non-DM channels", () => {
const group = channel({
kind: "group",
name: "Montage Nord",
isPrivate: false,
member: { ...channel().member, roleInChat: "admin" },
});
const vm = buildMemberChatChannelDetailVM({
detail: {
channel: group,
messages: [group.lastMessage!],
readReceipts: [],
attachments: [],
messageFeatures: [
{
messageId: "message_1",
reactions: [
{ id: "reaction_1", messageId: "message_1", userId: "user_me", emoji: "👍", reactedAtIso: "2026-07-15T10:02:00.000Z" },
{ id: "reaction_2", messageId: "message_1", userId: "user_other", emoji: "👍", reactedAtIso: "2026-07-15T10:03:00.000Z" },
],
thread: {
id: "message_1",
parentMessageId: "message_1",
replyCount: 2,
lastReplyAtIso: "2026-07-15T10:04:00.000Z",
participantUserIds: ["user_me", "user_other"],
},
pin: { messageId: "message_1", pinnedByUserId: "user_me", pinnedAtIso: "2026-07-15T10:05:00.000Z", note: null },
},
],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:8",
},
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.header.pinnedHref).toBe("/demo/chat/chat_1/pinned");
expect(vm.data.messages[0]).toMatchObject({
reactions: [{ emoji: "👍", count: 2, reactedByViewer: true, reactorLabels: ["Raffael Sheikh", "Ada Lovelace"] }],
thread: { replyCount: 2, href: "/demo/chat/chat_1/thread/message_1", isFollowing: true },
pin: { pinnedByLabel: "Raffael Sheikh" },
actions: { canReact: true, canReply: true, canPin: true },
});
expect(vm.data.pinnedMessages).toHaveLength(1);
});
it("keeps archived channels read-only", () => {
const archived = channel({ archivedAtIso: "2026-07-15T09:00:00.000Z" });
const vm = buildMemberChatChannelDetailVM({
detail: {
channel: archived,
messages: [],
readReceipts: [],
attachments: [],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:0",
},
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.composer).toMatchObject({ enabled: false, canSend: false, disabledReasonKey: "chat.composer.archived" });
});
it("derives edit and delete actions from the deterministic 24-hour window and fresh admin capabilities", () => {
const ownMessage = { ...channel().lastMessage!, authorUserId: "user_me" };
const detail = (memberRole: "admin" | "member", message = ownMessage): ChatMemberChannelDetail => ({
channel: channel({ kind: "group", name: "Team", member: { ...channel().member, roleInChat: memberRole }, lastMessage: message }),
messages: [message],
readReceipts: [],
attachments: [],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:8",
});
const freshOwn = buildMemberChatChannelDetailVM({
detail: detail("member"),
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
nowIso: "2026-07-16T09:00:00.000Z",
labels,
});
const expiredOwn = buildMemberChatChannelDetailVM({
detail: detail("member"),
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
nowIso: "2026-07-17T11:00:00.000Z",
labels,
});
const channelAdmin = buildMemberChatChannelDetailVM({
detail: detail("admin", channel().lastMessage!),
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
nowIso: "2026-07-17T11:00:00.000Z",
labels,
});
const globalAdmin = buildMemberChatChannelDetailVM({
detail: detail("member", channel().lastMessage!),
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write", "chat.admin"],
nowIso: "2026-07-17T11:00:00.000Z",
labels,
});
expect(freshOwn.status === "ready" && freshOwn.data.messages[0]?.actions).toMatchObject({ canEdit: true, canDelete: true });
expect(expiredOwn.status === "ready" && expiredOwn.data.messages[0]?.actions).toMatchObject({ canEdit: false, canDelete: false });
expect(channelAdmin.status === "ready" && channelAdmin.data.messages[0]?.actions).toMatchObject({ canEdit: false, canDelete: true });
expect(globalAdmin.status === "ready" && globalAdmin.data.messages[0]?.actions).toMatchObject({ canEdit: true, canDelete: true });
});
it("maps actorless system messages fail-soft without author, receipts, or message actions", () => {
const vm = buildMemberChatChannelDetailVM({
detail: {
channel: channel({ lastMessage: systemMessage() }),
messages: [
systemMessage(),
systemMessage({
id: "system_message_2",
clientMessageId: "system:future",
systemEvent: { kind: "channel_renamed", metadata: { internalId: "secret" } },
}),
],
readReceipts: [{ messageId: "system_message_1", userId: "user_me", readAtIso: "2026-07-15T10:01:00.000Z" }],
attachments: [],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:8",
},
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.messages[0]).toMatchObject({
author: null,
bodyMarkdown: null,
bodyFormat: "system",
readAggregate: null,
systemEvent: {
kind: "project_created",
labelKey: "chat.systemEvent.projectCreated",
values: { project: "Wärmepumpe Müller" },
},
actions: { canReact: false, canReply: false, canEdit: false, canDelete: false, canPin: false, canMarkAsTask: false },
});
expect(vm.data.messages[1]?.systemEvent).toEqual({
kind: "channel_renamed",
labelKey: "chat.systemEvent.generic",
values: {},
});
});
it("keeps deleted message projections free of stale mention and preview metadata", () => {
const deletedMessage = {
...channel().lastMessage!,
body: "deleted secret",
deletedAt: "2026-07-15T10:02:00.000Z",
mentions: [{ type: "user" as const, id: "user_me", label: null }],
linkPreviews: [
{
url: "https://example.com/secret",
title: "Secret",
description: null,
imageUrl: null,
siteName: "Example",
},
],
};
const vm = buildMemberChatChannelDetailVM({
detail: {
channel: channel(),
messages: [deletedMessage],
readReceipts: [],
attachments: [
{
messageId: deletedMessage.id,
fileId: "file_secret",
displayName: "secret.pdf",
mimeType: "application/pdf",
sizeBytes: 10,
linkRole: "file",
previewStatus: "not_supported",
scanStatus: "clean",
},
],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:1",
},
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels", "chat.write"],
labels,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
expect(vm.data.messages[0]).toMatchObject({
bodyMarkdown: null,
mentions: [],
linkPreviews: [],
attachments: [],
deletedAtIso: "2026-07-15T10:02:00.000Z",
});
});
it("maps skipped attachment scans fail-closed instead of exposing a download", () => {
const persisted = channel().lastMessage!;
const vm = buildMemberChatChannelDetailVM({
detail: {
channel: channel(),
messages: [persisted],
readReceipts: [],
attachments: [
{
messageId: persisted.id,
fileId: "file_skipped",
displayName: "unchecked.pdf",
mimeType: "application/pdf",
sizeBytes: 20,
linkRole: "file",
previewStatus: "not_supported",
scanStatus: "skipped",
},
],
hasOlderMessages: false,
olderMessageCursor: null,
eventCursor: "stream_1:1",
},
tenantSlug: "demo",
currentUserId: "user_me",
permissions: ["chat.read_own_channels"],
labels,
});
expect(vm.status === "ready" ? vm.data.messages[0]?.attachments[0]?.scanStatus : null).toBe("blocked");
});
});
@@ -0,0 +1,502 @@
import {
CHAT_PERMISSIONS,
type ChatAttachmentRecord,
type ChatMemberChannelDetail,
type ChatMemberChannelRecord,
type ChatParticipantProfileRecord,
} from "@hivegrid/chat";
import { buildChatMessageDeepLink } from "@hivegrid/chat/deep-links";
import type { DiscoverablePublicGroupChat } from "@hivegrid/chat/discovery.server";
import { CHAT_MESSAGE_MAX_BODY_LENGTH, type ChatMention, type ChatRealtimeMessage } from "@hivegrid/realtime";
import {
buildChatChannelDetailVM,
buildChatChannelListVM,
buildChatSystemEventVM,
type ChatAvatarVM,
type ChatAttachmentVM,
type ChatChannelDetailVM,
type ChatChannelListFilterState,
type ChatChannelListRowInput,
type ChatChannelListVM,
type ChatMessageCandidate,
type ChatReadAggregateVM,
type ChatResolvedAuthorVM,
type ChatResolvedMentionVM,
} from "@hivegrid/view-models";
import { mediaVariantPath } from "~/utils/integrations/fileRoutePaths";
import {
chatArchivedPath,
chatChannelPath,
chatChannelSettingsPath,
chatPinnedPath,
chatIndexPath,
chatMentionsPath,
chatNewPath,
chatSearchPath,
chatThreadPath,
} from "../routes/chatRoutePaths";
const CHAT_LIST_SNIPPET_MAX_LENGTH = 160;
export type ChatViewModelLabels = {
readonly directMessage: string;
readonly unnamedGroup: string;
readonly unnamedProject: string;
readonly unknownUser: string;
readonly unknownMention: string;
};
type ChatListViewModelInput = {
readonly channels: readonly ChatMemberChannelRecord[];
readonly tenantSlug: string;
readonly currentUserId: string;
readonly permissions: readonly string[];
readonly filter: ChatChannelListFilterState;
readonly nextCursor: string | null;
readonly discoverChannels?: readonly DiscoverablePublicGroupChat[];
readonly labels: ChatViewModelLabels;
};
type ChatDetailViewModelInput = {
readonly detail: ChatMemberChannelDetail;
readonly tenantSlug: string;
readonly currentUserId: string;
readonly permissions: readonly string[];
readonly featureAvailability?: { readonly files: boolean; readonly tasks: boolean };
/** Injected by the server assembler so the pure builder enforces the 24-hour window deterministically. */
readonly nowIso?: string;
readonly labels: ChatViewModelLabels;
};
/** Maps the already RLS-scoped repository projection to the serializable list
* contract. Filtering remains deterministic and does not trigger client-side
* data access or a second permission path. */
export function buildMemberChatChannelListVM(input: ChatListViewModelInput): ChatChannelListVM {
const rows = input.channels.map((channel) => toChannelListRow(channel, input));
return buildChatChannelListVM({
rows,
discoverRows: (input.discoverChannels ?? []).map((channel) => ({
id: channel.id,
title: channel.name,
description: channel.description,
avatar: fallbackAvatar(channel.name),
memberCount: channel.memberCount,
isJoined: false,
canJoin: true,
joinHref: chatIndexPath(input.tenantSlug),
detailHref: null,
})),
filter: input.filter,
permissions: {
canWrite: hasPermission(input.permissions, CHAT_PERMISSIONS.write),
canCreateGroup: hasPermission(input.permissions, CHAT_PERMISSIONS.createChannel),
canCreateDm: hasPermission(input.permissions, CHAT_PERMISSIONS.createDm),
canDiscover: input.discoverChannels !== undefined && hasPermission(input.permissions, CHAT_PERMISSIONS.readOwnChannels),
canViewMentions: hasPermission(input.permissions, CHAT_PERMISSIONS.readOwnChannels),
canSearch: hasPermission(input.permissions, CHAT_PERMISSIONS.readOwnChannels),
canViewArchived: hasPermission(input.permissions, CHAT_PERMISSIONS.readOwnChannels),
canAdmin: hasPermission(input.permissions, CHAT_PERMISSIONS.admin),
},
hrefs: {
newChannel: `${chatNewPath(input.tenantSlug)}?kind=group`,
newDm: `${chatNewPath(input.tenantSlug)}?kind=dm`,
search: chatSearchPath(input.tenantSlug),
mentions: chatMentionsPath(input.tenantSlug),
archived: chatArchivedPath(input.tenantSlug),
},
totals: {
unread: input.channels.reduce((total, channel) => total + channel.unreadCount, 0),
mentions: input.channels.filter((channel) => channel.hasUnreadMention).length,
},
nextCursor: input.nextCursor,
});
}
/** Builds the first member-channel live-loop without exposing unfinished
* thread/reaction/file/pin actions. Repository data is already authorized and
* contains every profile/read projection needed by this mapper. */
export function buildMemberChatChannelDetailVM(input: ChatDetailViewModelInput): ChatChannelDetailVM {
const { channel } = input.detail;
const profiles = new Map(channel.participants.map((participant) => [participant.userId, participant]));
const title = resolveChannelTitle(channel, input.currentUserId, input.labels);
const counterpart = resolveDmCounterpart(channel, input.currentUserId);
const canWrite = hasPermission(input.permissions, CHAT_PERMISSIONS.write) && channel.archivedAtIso === null && channel.member.canWrite;
const canManageGroup = channel.kind === "group" && (channel.member.roleInChat === "admin" || hasPermission(input.permissions, CHAT_PERMISSIONS.admin));
const featuresByMessageId = new Map((input.detail.messageFeatures ?? []).map((feature) => [feature.messageId, feature]));
const attachmentsByMessageId = new Map<string, ChatMemberChannelDetail["attachments"]>();
for (const attachment of input.detail.attachments ?? []) {
attachmentsByMessageId.set(attachment.messageId, [...(attachmentsByMessageId.get(attachment.messageId) ?? []), attachment]);
}
const canAttachFiles = canWrite && input.featureAvailability?.files === true && hasPermission(input.permissions, "files.write");
const canMarkAsTask = canWrite && input.featureAvailability?.tasks === true && hasPermission(input.permissions, "tasks.write");
const canPinAnyMessage = channel.member.roleInChat === "admin" || hasPermission(input.permissions, CHAT_PERMISSIONS.admin);
const canAdministerMessages = hasPermission(input.permissions, CHAT_PERMISSIONS.admin);
const canDeleteAsChannelAdmin = channel.member.roleInChat === "admin" || canAdministerMessages;
return buildChatChannelDetailVM({
header: {
id: channel.id,
kind: channel.kind,
title,
subtitle: channel.description,
avatar: counterpart ? participantAvatar(counterpart) : fallbackAvatar(title),
project: null,
memberCount: channel.memberCount,
isPrivate: channel.isPrivate,
isArchived: channel.archivedAtIso !== null,
isAuditMode: false,
canManage: canManageGroup,
settingsHref: chatChannelSettingsPath(input.tenantSlug, channel.id),
pinnedHref: channel.kind === "dm" ? null : chatPinnedPath(input.tenantSlug, channel.id),
searchHref: chatIndexPath(input.tenantSlug),
},
messages: input.detail.messages.map((message) =>
toMessageCandidate({
message,
profiles,
readReceipts: input.detail.readReceipts,
memberCount: channel.memberCount,
currentUserId: input.currentUserId,
tenantSlug: input.tenantSlug,
labels: input.labels,
feature: featuresByMessageId.get(message.id) ?? null,
canWrite,
channelKind: channel.kind,
chatId: channel.id,
attachments: attachmentsByMessageId.get(message.id) ?? [],
canMarkAsTask,
canPinAnyMessage,
canAdministerMessages,
canDeleteAsChannelAdmin,
nowIso: input.nowIso ?? "9999-12-31T23:59:59.999Z",
})
),
pinnedMessages: input.detail.messages.flatMap((message) => {
const feature = featuresByMessageId.get(message.id);
if (!feature?.pin || message.bodyFormat !== "markdown") return [];
return [
{
messageId: message.id,
authorLabel: profiles.get(message.authorUserId)?.displayName ?? input.labels.unknownUser,
snippet: chatListSnippet(message.body),
pinnedAtIso: feature.pin.pinnedAtIso,
pinnedByLabel: profiles.get(feature.pin.pinnedByUserId)?.displayName ?? input.labels.unknownUser,
href: buildChatMessageDeepLink({ tenantSlug: input.tenantSlug, chatId: channel.id, messageId: message.id }),
},
];
}),
typingLabels: [],
history: {
olderCursor: input.detail.olderMessageCursor,
hasOlder: input.detail.hasOlderMessages,
},
composer: {
canSend: canWrite,
canAttachFiles,
canRecordVoice: canAttachFiles,
canMention: canWrite,
canMarkAsTask,
disabledReasonKey: canWrite ? null : channel.archivedAtIso ? "chat.composer.archived" : "chat.composer.permissionDenied",
draftStorageKey: `chat:draft:v1:${input.tenantSlug}:${input.currentUserId}:${channel.id}`,
maxBodyLength: CHAT_MESSAGE_MAX_BODY_LENGTH,
},
connection: {
state: "connecting",
reconnectAttempt: 0,
retryAtIso: null,
},
});
}
export function buildChatResolvedAuthors(participants: readonly ChatParticipantProfileRecord[], currentUserId: string): readonly ChatResolvedAuthorVM[] {
return participants.map((participant) => ({
userId: participant.userId,
displayName: participant.displayName,
avatar: participantAvatar(participant),
isCurrentUser: participant.userId === currentUserId,
}));
}
function toChannelListRow(channel: ChatMemberChannelRecord, input: ChatListViewModelInput): ChatChannelListRowInput {
const title = resolveChannelTitle(channel, input.currentUserId, input.labels);
const counterpart = resolveDmCounterpart(channel, input.currentUserId);
const lastMessageAuthor = channel.lastMessage?.bodyFormat === "markdown" ? findParticipant(channel.participants, channel.lastMessage.authorUserId) : null;
return {
id: channel.id,
kind: channel.kind,
title,
subtitle: channel.description,
detailHref: chatChannelPath(input.tenantSlug, channel.id),
avatar: counterpart ? participantAvatar(counterpart) : fallbackAvatar(title),
project: null,
lastMessage: channel.lastMessage
? {
authorLabel: channel.lastMessage.bodyFormat === "system" ? null : (lastMessageAuthor?.displayName ?? input.labels.unknownUser),
snippet: channel.lastMessage.bodyFormat === "system" || channel.lastMessage.deletedAt ? "" : chatListSnippet(channel.lastMessage.body),
systemEvent:
channel.lastMessage.bodyFormat === "system"
? buildChatSystemEventVM(channel.lastMessage.systemEvent.kind, channel.lastMessage.systemEvent.metadata)
: null,
createdAtIso: channel.lastMessage.createdAt,
}
: null,
typingLabels: [],
unreadCount: channel.unreadCount,
hasMention: channel.hasUnreadMention,
isPinned: channel.member.isPinned,
isPrivate: channel.isPrivate,
notificationPreference: channel.member.notificationPreference,
archivedAtIso: channel.archivedAtIso,
memberCount: channel.memberCount,
canManage: false,
};
}
function chatListSnippet(markdown: string): string {
const plainText = markdown
.replace(/<[^>]*>/g, " ")
.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.replace(/[`*_~>#]/g, " ")
.replace(/^\s*[-+]\s+/gm, "")
.replace(/\s+/g, " ")
.trim();
if (plainText.length <= CHAT_LIST_SNIPPET_MAX_LENGTH) return plainText;
return `${plainText.slice(0, CHAT_LIST_SNIPPET_MAX_LENGTH - 1).trimEnd()}…`;
}
function toMessageCandidate(input: {
readonly message: ChatRealtimeMessage;
readonly profiles: ReadonlyMap<string, ChatParticipantProfileRecord>;
readonly readReceipts: ChatMemberChannelDetail["readReceipts"];
readonly memberCount: number;
readonly currentUserId: string;
readonly tenantSlug: string;
readonly labels: ChatViewModelLabels;
readonly feature: NonNullable<ChatMemberChannelDetail["messageFeatures"]>[number] | null;
readonly canWrite: boolean;
readonly channelKind: ChatMemberChannelRecord["kind"];
readonly chatId: string;
readonly attachments: ChatMemberChannelDetail["attachments"];
readonly canMarkAsTask: boolean;
readonly canPinAnyMessage: boolean;
readonly canAdministerMessages: boolean;
readonly canDeleteAsChannelAdmin: boolean;
readonly nowIso: string;
}): ChatMessageCandidate {
if (input.message.bodyFormat === "system") {
return {
id: input.message.id,
clientMessageId: input.message.clientMessageId,
source: "persisted",
deliveryState: "sent",
failureReasonKey: null,
author: null,
bodyMarkdown: null,
bodyFormat: "system",
systemEvent: buildChatSystemEventVM(input.message.systemEvent.kind, input.message.systemEvent.metadata),
createdAtIso: input.message.createdAt,
updatedAtIso: input.message.updatedAt,
editedAtIso: input.message.editedAt,
deletedAtIso: input.message.deletedAt,
parentMessageId: null,
mentions: [],
reactions: [],
thread: null,
attachments: [],
linkPreviews: [],
readAggregate: null,
pin: null,
actions: NO_MESSAGE_ACTIONS,
};
}
const profile = input.profiles.get(input.message.authorUserId);
const readerProfiles = input.readReceipts
.filter((receipt) => receipt.messageId === input.message.id && receipt.userId !== input.message.authorUserId)
.map((receipt) => input.profiles.get(receipt.userId))
.filter((reader): reader is ChatParticipantProfileRecord => reader !== undefined);
const reactionGroups = new Map<string, string[]>();
for (const reaction of input.feature?.reactions ?? []) {
const reactors = reactionGroups.get(reaction.emoji) ?? [];
reactors.push(reaction.userId);
reactionGroups.set(reaction.emoji, reactors);
}
const reactions = [...reactionGroups.entries()].map(([emoji, userIds]) => ({
emoji,
count: userIds.length,
reactedByViewer: userIds.includes(input.currentUserId),
reactorLabels: userIds.map((userId) => input.profiles.get(userId)?.displayName ?? input.labels.unknownUser),
}));
const thread = input.feature?.thread
? {
id: input.feature.thread.id,
replyCount: input.feature.thread.replyCount,
participantLabels: input.feature.thread.participantUserIds.map((userId) => input.profiles.get(userId)?.displayName ?? input.labels.unknownUser),
lastReplyAtIso: input.feature.thread.lastReplyAtIso,
isFollowing: input.feature.thread.participantUserIds.includes(input.currentUserId),
href: chatThreadPath(input.tenantSlug, input.chatId, input.feature.thread.id),
}
: null;
const pin = input.feature?.pin
? {
pinnedAtIso: input.feature.pin.pinnedAtIso,
pinnedByLabel: input.profiles.get(input.feature.pin.pinnedByUserId)?.displayName ?? input.labels.unknownUser,
note: input.feature.pin.note,
}
: null;
const deleted = input.message.deletedAt !== null;
const ownMessage = input.message.authorUserId === input.currentUserId;
const ageMs = Date.parse(input.nowIso) - Date.parse(input.message.createdAt);
const withinOwnMutationWindow = Number.isFinite(ageMs) && ageMs >= 0 && ageMs <= 24 * 60 * 60 * 1_000;
return {
id: input.message.id,
clientMessageId: input.message.clientMessageId,
source: "persisted",
deliveryState: "sent",
failureReasonKey: null,
author: {
userId: input.message.authorUserId,
displayName: profile?.displayName ?? input.labels.unknownUser,
avatar: profile ? participantAvatar(profile) : fallbackAvatar(input.labels.unknownUser),
isCurrentUser: input.message.authorUserId === input.currentUserId,
},
bodyMarkdown: deleted ? null : input.message.body,
bodyFormat: input.message.bodyFormat,
systemEvent: null,
createdAtIso: input.message.createdAt,
updatedAtIso: input.message.updatedAt,
editedAtIso: input.message.editedAt,
deletedAtIso: input.message.deletedAt,
parentMessageId: input.message.parentMessageId,
mentions: deleted ? [] : input.message.mentions.map((mention) => toChatResolvedMentionVM(mention, input.profiles, input.tenantSlug, input.labels)),
reactions,
thread,
attachments: deleted ? [] : input.attachments.map((attachment) => toChatAttachmentVM(attachment, input.tenantSlug)),
linkPreviews: deleted ? [] : input.message.linkPreviews,
readAggregate: toReadAggregate(readerProfiles, input.memberCount),
pin,
actions: {
canReact: input.canWrite && !deleted,
canReply: input.canWrite && !deleted,
canEdit: input.canWrite && !deleted && (input.canAdministerMessages || (ownMessage && withinOwnMutationWindow)),
canDelete: input.canWrite && !deleted && (input.canDeleteAsChannelAdmin || (ownMessage && withinOwnMutationWindow)),
canPin: input.canWrite && !deleted && input.channelKind !== "dm" && (ownMessage || input.canPinAnyMessage),
canMarkAsTask: input.canMarkAsTask && !deleted,
},
};
}
export function toChatAttachmentVM(attachment: ChatAttachmentRecord, tenantSlug: string): ChatAttachmentVM {
return {
id: `${attachment.messageId}:${attachment.fileId}`,
fileId: attachment.fileId,
kind:
attachment.linkRole === "voice" || attachment.mimeType.startsWith("audio/")
? "voice"
: attachment.linkRole === "image" || attachment.mimeType.startsWith("image/")
? "image"
: "file",
fileName: attachment.displayName,
mimeType: attachment.mimeType,
sizeBytes: attachment.sizeBytes,
downloadHref: mediaVariantPath(tenantSlug, attachment.fileId, "original"),
previewHref:
attachment.mimeType.startsWith("image/") && attachment.previewStatus === "ready" ? mediaVariantPath(tenantSlug, attachment.fileId, "preview") : null,
altText: attachment.mimeType.startsWith("image/") ? attachment.displayName : null,
durationSeconds: null,
scanStatus: attachment.scanStatus === "clean" ? "clean" : attachment.scanStatus === "pending" ? "pending" : "blocked",
};
}
const NO_MESSAGE_ACTIONS = Object.freeze({
canReact: false,
canReply: false,
canEdit: false,
canDelete: false,
canPin: false,
canMarkAsTask: false,
});
export function toChatResolvedMentionVM(
mention: ChatMention,
profiles: ReadonlyMap<string, ChatParticipantProfileRecord>,
tenantSlug: string,
labels: ChatViewModelLabels
): ChatResolvedMentionVM {
const userLabel = mention.type === "user" ? profiles.get(mention.id)?.displayName : null;
const href =
mention.type === "project"
? `/${tenantSlug}/projects/${encodeURIComponent(mention.id)}`
: mention.type === "contact"
? `/${tenantSlug}/contacts/${encodeURIComponent(mention.id)}`
: mention.type === "company"
? `/${tenantSlug}/contacts/companies/${encodeURIComponent(mention.id)}`
: null;
return {
kind: mention.type,
id: mention.id,
label: userLabel ?? mention.label ?? labels.unknownMention,
href,
};
}
function toReadAggregate(readers: readonly ChatParticipantProfileRecord[], memberCount: number): ChatReadAggregateVM {
const uniqueReaders = [...new Map(readers.map((reader) => [reader.userId, reader])).values()];
return {
readCount: uniqueReaders.length,
recipientCount: Math.max(0, memberCount - 1),
readerUserIds: uniqueReaders.map((reader) => reader.userId),
readerLabels: uniqueReaders.map((reader) => reader.displayName),
labelKey: "chat.message.read.aggregate",
};
}
function resolveChannelTitle(channel: ChatMemberChannelRecord, currentUserId: string, labels: ChatViewModelLabels): string {
if (channel.kind === "dm") {
return resolveDmCounterpart(channel, currentUserId)?.displayName ?? labels.directMessage;
}
const name = channel.name?.trim();
if (name) return name;
return channel.kind === "project" ? labels.unnamedProject : labels.unnamedGroup;
}
function resolveDmCounterpart(channel: ChatMemberChannelRecord, currentUserId: string): ChatParticipantProfileRecord | null {
if (channel.kind !== "dm") return null;
return channel.participants.find((participant) => participant.userId !== currentUserId) ?? null;
}
function findParticipant(participants: readonly ChatParticipantProfileRecord[], userId: string): ChatParticipantProfileRecord | null {
return participants.find((participant) => participant.userId === userId) ?? null;
}
function participantAvatar(participant: ChatParticipantProfileRecord): ChatAvatarVM {
return {
imageUrl: participant.avatarUrl,
fallbackLabel: initials(participant.displayName),
};
}
function fallbackAvatar(label: string): ChatAvatarVM {
return { imageUrl: null, fallbackLabel: initials(label) };
}
function initials(label: string): string {
const result = label
.trim()
.split(/\s+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part[0]?.toLocaleUpperCase() ?? "")
.join("");
return result || "?";
}
function hasPermission(permissions: readonly string[], permission: string): boolean {
return permissions.includes(permission);
}
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff. Show more