From 83f89a38ef0c98f59466d7bc550c61b6c01e54cd Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:52:26 +0530 Subject: [PATCH 1/4] feat(kin): push the right person for each chat, with mute, badge and quiet hours Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/components/ui/AppSymbol.tsx | 4 + .../src/features/chats/KinChatScreen.tsx | 52 ++- .../features/chats/components/KinChatRow.tsx | 8 + .../chats/notifications/KinBadgeSync.tsx | 20 ++ .../notifications/kinPushPayload.test.ts | 14 + .../src/features/chats/state/kinClient.ts | 6 + apps/server/src/kin/chat/KinChatHub.ts | 2 + apps/server/src/kin/chat/KinChatRepository.ts | 12 + .../src/kin/chat/KinChatService.test.ts | 28 ++ apps/server/src/kin/chat/KinChatService.ts | 22 ++ apps/server/src/kin/chat/rpcHandlers.ts | 7 + apps/server/src/kin/lead/ChatWake.test.ts | 6 +- apps/server/src/kin/push/KinPushDispatch.ts | 68 ++++ .../server/src/kin/push/KinPushSender.test.ts | 320 ++++++++++++++++-- apps/server/src/kin/push/KinPushSender.ts | 265 ++++++++++++--- apps/server/src/kin/push/layer.ts | 6 +- apps/server/src/kin/triggers/pings.ts | 11 +- apps/server/src/kin/triggers/quietHours.ts | 15 + .../src/kin/kinInboxModel.test.ts | 6 +- .../client-runtime/src/kin/kinInboxModel.ts | 4 + .../src/kin/kinScreenState.test.ts | 21 ++ .../client-runtime/src/kin/kinScreenState.ts | 26 +- .../src/state/commandPermissions.test.ts | 3 + packages/contracts/src/kinChat.ts | 11 + packages/contracts/src/kinRpcs.ts | 1 + 25 files changed, 838 insertions(+), 100 deletions(-) create mode 100644 apps/mobile/src/features/chats/notifications/KinBadgeSync.tsx create mode 100644 apps/server/src/kin/push/KinPushDispatch.ts create mode 100644 apps/server/src/kin/triggers/quietHours.ts diff --git a/apps/mobile/src/components/ui/AppSymbol.tsx b/apps/mobile/src/components/ui/AppSymbol.tsx index 3ca8f61aaece..f7501d59087a 100644 --- a/apps/mobile/src/components/ui/AppSymbol.tsx +++ b/apps/mobile/src/components/ui/AppSymbol.tsx @@ -22,6 +22,8 @@ import IconArrowsLeftRight from "@tabler/icons-react-native/IconArrowsLeftRight" import IconArrowsDiagonal2 from "@tabler/icons-react-native/IconArrowsDiagonal2"; import IconArrowsMinimize from "@tabler/icons-react-native/IconArrowsMinimize"; import IconBan from "@tabler/icons-react-native/IconBan"; +import IconBell from "@tabler/icons-react-native/IconBell"; +import IconBellOff from "@tabler/icons-react-native/IconBellOff"; import IconBellRinging from "@tabler/icons-react-native/IconBellRinging"; import IconBolt from "@tabler/icons-react-native/IconBolt"; import IconBox from "@tabler/icons-react-native/IconBox"; @@ -166,7 +168,9 @@ const ANDROID_ICON_BY_SF_SYMBOL = { "arrow.uturn.forward": IconArrowForwardUp, archivebox: IconArchive, "archivebox.fill": IconArchive, + bell: IconBell, "bell.badge": IconBellRinging, + "bell.slash": IconBellOff, "bolt.circle": IconBolt, "bolt.horizontal.circle": IconBolt, brain: IconBrain, diff --git a/apps/mobile/src/features/chats/KinChatScreen.tsx b/apps/mobile/src/features/chats/KinChatScreen.tsx index d43ed93e28d8..667818640818 100644 --- a/apps/mobile/src/features/chats/KinChatScreen.tsx +++ b/apps/mobile/src/features/chats/KinChatScreen.tsx @@ -18,6 +18,7 @@ import { type KinChatHistoryInput, type KinChatHistoryResult, type KinChatMember, + type KinChatSummary, type KinMessage, type KinReaction, type KinReactionEmoji, @@ -132,6 +133,7 @@ import { } from "@t3tools/client-runtime/kin/kinInboxModel"; import { kinPresenceLine, kinPresenceNeedsClock } from "@t3tools/client-runtime/kin/kinLive"; import { + kinChatMuted, kinChatTitle, kinDirectAgentName, kinAgentAvatar, @@ -148,6 +150,7 @@ import { kinSoftReplyMessageId, kinViewerMemberId, } from "@t3tools/client-runtime/kin/kinReactions"; +import { KinBadgeSync } from "./notifications/KinBadgeSync"; import { KinChatPushWatch } from "./notifications/KinChatPushWatch"; type KinChatParams = { @@ -199,6 +202,9 @@ const noChatAtom: Atom.Atom = Atom.make(null); const noInboxAtom: Atom.Atom = Atom.make(null); const decodeChatId = Schema.decodeUnknownOption(KinChatId); +/** Read at render: a mute only ends when its time passes, and a re-render reads it again. */ +const mutedNow = (chat: KinChatSummary, personId: string | null) => + personId !== null && kinChatMuted(chat, new Set([personId]), Date.now()); const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId); function KinLiveChat(props: { @@ -233,6 +239,9 @@ function KinLiveChat(props: { const ownedAgentId = summary === undefined ? null : kinLevelsAgentId(summary, viewer.personId); const levelsAgentId = canReadLevels ? ownedAgentId : null; const canInterrupt = useAtomValue(kinClient.leadInterrupt.permissionAtom(props.environmentId)); + const canMute = useAtomValue(kinClient.mute.permissionAtom(props.environmentId)); + const runMute = useAtomCommand(kinClient.mute, "Muting this chat"); + const muted = summary === undefined ? false : mutedNow(summary, viewer.personId); const retry = () => { if (environmentId === null) return; @@ -246,6 +255,10 @@ function KinLiveChat(props: { return ( <> + {/* Only a live inbox: a saved one would put an old count back on the icon. */} + { + void runMute({ environmentId, input: { chatId, muted: !muted } }); + }, + } + } stopLead={ environmentId === null || summary === undefined || ownedAgentId === null || !canInterrupt ? null @@ -400,6 +423,7 @@ function KinChatAppBar(props: { readonly tasks: string | null; readonly onBack: () => void; readonly actions: ComponentPropsWithRef["actions"]; + readonly menus: ComponentPropsWithRef["menus"]; }) { const pill = Platform.OS === "ios"; const now = useKinPresenceNow(!pill && kinPresenceNeedsClock(props.presence)); @@ -412,7 +436,13 @@ function KinChatAppBar(props: { ); return ( <> - + {/* Always set, so going back to the default size resets the bar. */} void } | null; readonly state: KinChatScreenState; readonly viewer: KinFeedViewer; readonly onRetry: () => void; @@ -498,6 +530,24 @@ function KinChatPage(props: { presence={livePresence(state)} tasks={tasks} onBack={() => navigation.goBack()} + menus={ + props.mute == null + ? undefined + : [ + { + title: "Chat options", + icon: "ellipsis", + items: [ + { + id: "mute", + title: props.mute.muted ? "Unmute notifications" : "Mute notifications", + icon: props.mute.muted ? "bell" : "bell.slash", + onPress: props.mute.toggle, + }, + ], + }, + ] + } actions={ levels == null ? undefined diff --git a/apps/mobile/src/features/chats/components/KinChatRow.tsx b/apps/mobile/src/features/chats/components/KinChatRow.tsx index 91ea82c3bb71..d78413981b09 100644 --- a/apps/mobile/src/features/chats/components/KinChatRow.tsx +++ b/apps/mobile/src/features/chats/components/KinChatRow.tsx @@ -36,6 +36,14 @@ export function KinChatRow(props: { > {view.title} + {view.muted ? ( + + ) : null} {view.sentAt === null ? null : ( diff --git a/apps/mobile/src/features/chats/notifications/KinBadgeSync.tsx b/apps/mobile/src/features/chats/notifications/KinBadgeSync.tsx new file mode 100644 index 000000000000..52447f205168 --- /dev/null +++ b/apps/mobile/src/features/chats/notifications/KinBadgeSync.tsx @@ -0,0 +1,20 @@ +import { kinBadgeCount, type KinInboxState } from "@t3tools/client-runtime/kin/kinInboxModel"; +import * as Notifications from "expo-notifications"; +import { useEffect } from "react"; +import { Platform } from "react-native"; + +/** + * Keeps the app icon's badge in step with the inbox while a chat is open, so reading a chat + * clears what the host's last push counted. Pushes set it again whenever the app is closed. + */ +export function KinBadgeSync(props: { readonly inbox: KinInboxState | null }) { + const count = props.inbox === null ? null : kinBadgeCount(props.inbox); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the icon badge lives in the OS, outside React + useEffect(() => { + if (count === null || Platform.OS !== "ios") return; + void Notifications.setBadgeCountAsync(count).catch((cause: unknown) => + console.warn("Setting the Kin badge failed", cause), + ); + }, [count]); + return null; +} diff --git a/apps/mobile/src/features/chats/notifications/kinPushPayload.test.ts b/apps/mobile/src/features/chats/notifications/kinPushPayload.test.ts index 1f2211397cdb..a5f649af33fe 100644 --- a/apps/mobile/src/features/chats/notifications/kinPushPayload.test.ts +++ b/apps/mobile/src/features/chats/notifications/kinPushPayload.test.ts @@ -61,6 +61,20 @@ describe("kinNotificationRoute", () => { "/kin", ], ["JSON-encoded data", JSON.stringify(deferral), chatLink], + // Each lead's DM and each group is its own chat id, so each push opens its own chat. + ...(["7ae13b6f-1a49-4bb5-ac5c-6ac6b4300978", "c1f0e2d4-group"] as const).map( + (chatId) => + [ + `the chat ${chatId}`, + { + kin: 1, + orgId: "kin-default", + chatId, + deepLink: `/kin/env-1/kin-default/chats/${chatId}`, + }, + `/kin/env-1/kin-default/chats/${chatId}`, + ] as const, + ), ])("routes %s", (_name, data, path) => { const route = kinNotificationRoute(response({ data })); expect(route?.path).toBe(path); diff --git a/apps/mobile/src/features/chats/state/kinClient.ts b/apps/mobile/src/features/chats/state/kinClient.ts index 64be14105c57..5db5307157c1 100644 --- a/apps/mobile/src/features/chats/state/kinClient.ts +++ b/apps/mobile/src/features/chats/state/kinClient.ts @@ -182,6 +182,12 @@ export const kinClient = { tag: "kin.lead.interrupt", concurrency: { mode: "singleFlight", key: ({ input }) => input.wakeupId }, }), + /** Mutes or unmutes this chat's pushes for the viewer; one in flight per chat. */ + mute: createEnvironmentRpcCommand(connectionAtomRuntime, { + label: "kin:mute", + tag: KIN_CHAT_WS_METHODS.chatsMute, + concurrency: { mode: "singleFlight", key: ({ input }) => input.chatId }, + }), markRead: createEnvironmentRpcCommand(connectionAtomRuntime, { label: "kin:mark-read", tag: KIN_CHAT_WS_METHODS.messagesMarkRead, diff --git a/apps/server/src/kin/chat/KinChatHub.ts b/apps/server/src/kin/chat/KinChatHub.ts index 499b7dafc957..9fe13aa44907 100644 --- a/apps/server/src/kin/chat/KinChatHub.ts +++ b/apps/server/src/kin/chat/KinChatHub.ts @@ -31,6 +31,8 @@ type ChatEvent = | { readonly type: "widget.updated"; readonly widget: KinWidget } | { readonly type: "waiting.updated"; readonly item: KinWaitingItem } | { readonly type: "member.removed"; readonly member: KinChatMember } + // A change to an active member's row, such as a mute; every member of the chat sees it. + | { readonly type: "member.updated"; readonly chatId: KinChatId; readonly member: KinChatMember } | { readonly type: "read.updated"; readonly chatId: KinChatId; diff --git a/apps/server/src/kin/chat/KinChatRepository.ts b/apps/server/src/kin/chat/KinChatRepository.ts index 4b77980466b5..ab183422e6df 100644 --- a/apps/server/src/kin/chat/KinChatRepository.ts +++ b/apps/server/src/kin/chat/KinChatRepository.ts @@ -301,6 +301,10 @@ export class KinChatRepository extends Context.Service< input: KinAgent & { readonly createdAt: IsoDateTime }, ) => Effect.Effect; readonly addMember: (input: KinChatMember) => Effect.Effect; + /** Sets an active member's mute; `null` unmutes. None when the member isn't active. */ + readonly setMute: ( + input: MemberScope & { readonly mutedUntil: IsoDateTime | null }, + ) => Effect.Effect, RepositoryError>; readonly leaveChat: ( input: MemberScope & { readonly leftAt: IsoDateTime }, ) => Effect.Effect, RepositoryError>; @@ -1035,6 +1039,14 @@ const make = Effect.gen(function* () { }, Effect.mapError(toRepositoryError("KinChatRepository.addMember")), ), + setMute: Effect.fn("KinChatRepository.setMute")( + function* (input) { + const changed = yield* sql`UPDATE kin_chat_members SET muted_until = ${input.mutedUntil} + WHERE org_id = ${input.orgId} AND chat_id = ${input.chatId} AND member_id = ${input.memberId} AND left_at IS NULL RETURNING member_id`; + return changed.length === 0 ? Option.none() : yield* memberOne(input); + }, + Effect.mapError(toRepositoryError("KinChatRepository.setMute")), + ), leaveChat: Effect.fn("KinChatRepository.leaveChat")( function* (input) { return yield* sql.withTransaction( diff --git a/apps/server/src/kin/chat/KinChatService.test.ts b/apps/server/src/kin/chat/KinChatService.test.ts index 8cb65a292100..ecafcb555bc3 100644 --- a/apps/server/src/kin/chat/KinChatService.test.ts +++ b/apps/server/src/kin/chat/KinChatService.test.ts @@ -554,6 +554,7 @@ describe("KinChatService", () => { service.send(foreign, { chatId: chat.chatId, body: "Hidden", clientMessageId: "foreign" }), service.history(foreign, { chatId: chat.chatId, beforeSeq: 99, limit: 100 }), service.markRead(foreign, { chatId: chat.chatId, seq: 1 }), + service.mute(foreign, { chatId: chat.chatId, muted: true }), service.upsertWidget(foreign, { chatId: chat.chatId, widgetId: widget.widgetId, @@ -1261,6 +1262,33 @@ describe("KinChatService", () => { assert.deepStrictEqual(yield* repo.listOpenWaiting(other), []); }).pipe(Effect.provide(layer)), ); + it.effect("mutes and unmutes a chat for the caller only, live in their list", () => + Effect.gen(function* () { + const { service, person, chat } = yield* seed(); + const updates = yield* Stream.toQueue(service.subscribeChats([person], {}), { + capacity: "unbounded", + }); + assert.strictEqual((yield* Queue.take(updates))._tag, "snapshot"); + const mine = Effect.map(Queue.take(updates), (event) => + event._tag === "chat" + ? Object.fromEntries( + event.chat.members.map((member) => [member.principal._tag, member.mutedUntil]), + ) + : event._tag, + ); + const muted = yield* service.mute(person, { chatId: chat.chatId, muted: true }); + assert.isAbove(Date.parse(muted.mutedUntil ?? ""), Date.parse("9999-01-01T00:00:00Z")); + // The agent's own mute is separate and stays off. + assert.deepStrictEqual(yield* mine, { person: muted.mutedUntil, agent: null }); + // Muting twice changes nothing, so the list sends nothing. + yield* service.mute(person, { chatId: chat.chatId, muted: true }); + assert.isNull( + (yield* service.mute(person, { chatId: chat.chatId, muted: false })).mutedUntil, + ); + assert.deepStrictEqual(yield* mine, { person: null, agent: null }); + }).pipe(Effect.provide(presenceLayer)), + ); + it.effect("marks a chat working in the list while its agent's run is live", () => Effect.gen(function* () { const { service, person, chat } = yield* seed(); diff --git a/apps/server/src/kin/chat/KinChatService.ts b/apps/server/src/kin/chat/KinChatService.ts index afa2de9c8de1..9bb5e99952e8 100644 --- a/apps/server/src/kin/chat/KinChatService.ts +++ b/apps/server/src/kin/chat/KinChatService.ts @@ -36,6 +36,7 @@ import { type KinChatsCreateDirectInput, type KinMessage, type KinMessagesMarkReadInput, + type KinChatsMuteInput, type KinPersonId, type KinOrgId, type KinReaction, @@ -121,6 +122,10 @@ export class KinChatService extends Context.Service< identities: ReadonlyArray, input: KinChatsSubscribeInput, ) => Stream.Stream; + readonly mute: ( + identity: PersonCaller, + input: KinChatsMuteInput, + ) => Effect.Effect; readonly leaveChat: ( identity: PersonIdentity, input: { readonly chatId: KinChatId; readonly memberId: KinMemberId }, @@ -250,6 +255,8 @@ const checkpointEvery = 100; /** The flood bound on one wake-up's posts in one chat, natural replies and kin_chat_post alike. */ export const KIN_WAKEUP_MESSAGE_LIMIT = 8; export const KIN_WAKEUP_CHAR_LIMIT = 32_000; +/** A person's mute with no end: it lasts until they unmute. */ +const KIN_MUTED_FOREVER = "9999-12-31T23:59:59.999Z"; /** Guests never write; a muted agent stays silent until its mute ends. */ export const mayWrite = (member: KinChatMember, agent: boolean, now: number) => member.role !== "guest" && @@ -797,6 +804,20 @@ const make = Effect.gen(function* () { ); return { orgs, me: identities.map(({ orgId, personId }) => ({ orgId, personId })) }; }), + mute: Effect.fn("KinChatService.mute")(function* (caller, input) { + const identity = yield* personFor(caller, input); + const member = yield* memberFor(identity, input.chatId); + const mutedUntil = input.muted ? KIN_MUTED_FOREVER : null; + if (member.mutedUntil === mutedUntil) return member; + const updated = yield* requireRecord(repo.setMute({ ...member, mutedUntil })); + yield* hub.publish({ + type: "member.updated", + orgId: identity.orgId, + chatId: input.chatId, + member: updated, + }); + return updated; + }, transaction), leaveChat: Effect.fn("KinChatService.leaveChat")(function* (identity, input) { const caller = yield* memberFor(identity, input.chatId); if (caller.role !== "owner") return yield* notAllowed; @@ -896,6 +917,7 @@ const make = Effect.gen(function* () { }); } case "member.removed": + case "member.updated": return event.member.chatId === input.chatId ? Option.some({ _tag: "member", member: event.member }) : Option.none(); diff --git a/apps/server/src/kin/chat/rpcHandlers.ts b/apps/server/src/kin/chat/rpcHandlers.ts index 4fc9ea5e463a..e59fe43faf19 100644 --- a/apps/server/src/kin/chat/rpcHandlers.ts +++ b/apps/server/src/kin/chat/rpcHandlers.ts @@ -168,6 +168,13 @@ export const makeKinChatHandlers = Effect.fn("makeKinChatHandlers")(function* ( Effect.mapError(mapError), Effect.catchDefect(defect), ), + "kin.chats.mute": (input) => + viewer.pipe( + Effect.flatMap(({ chat, people }) => chat.mute(people, input)), + Effect.tapError(logInfra), + Effect.mapError(mapError), + Effect.catchDefect(defect), + ), "kin.chat.history": (input) => viewer.pipe( Effect.flatMap(({ chat, people }) => chat.history(people, input)), diff --git a/apps/server/src/kin/lead/ChatWake.test.ts b/apps/server/src/kin/lead/ChatWake.test.ts index bca60c8c7fc5..4bb02eac3c22 100644 --- a/apps/server/src/kin/lead/ChatWake.test.ts +++ b/apps/server/src/kin/lead/ChatWake.test.ts @@ -389,6 +389,10 @@ describe("ChatWake", () => { /\bsubscribeAll\b/.test(NodeFS.readFileSync(NodePath.join(root, file), "utf8")), ) .toSorted(); - assert.deepStrictEqual(readers, ["kin/chat/KinChatHub.ts", "kin/lead/ChatWake.ts"]); + assert.deepStrictEqual(readers, [ + "kin/chat/KinChatHub.ts", + "kin/lead/ChatWake.ts", + "kin/push/KinPushDispatch.ts", + ]); }); }); diff --git a/apps/server/src/kin/push/KinPushDispatch.ts b/apps/server/src/kin/push/KinPushDispatch.ts new file mode 100644 index 000000000000..57bfbe5e45ca --- /dev/null +++ b/apps/server/src/kin/push/KinPushDispatch.ts @@ -0,0 +1,68 @@ +import type { KinActionId, KinWidget, KinWidgetId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import { KinChatHub } from "../chat/KinChatHub.ts"; +import { KinPushSender } from "./KinPushSender.ts"; + +const phaseOf = (widget: KinWidget) => + typeof widget.state === "object" && widget.state !== null && "phase" in widget.state + ? String(widget.state.phase) + : ""; +const actionOf = (widget: KinWidget) => + typeof widget.state === "object" && + widget.state !== null && + "actionId" in widget.state && + typeof widget.state.actionId === "string" + ? (widget.state.actionId as KinActionId) + : null; + +/** + * Turns committed chat events into pushes. Every post path publishes to the hub, so this is + * the one place that decides when to ask; the sender decides who hears it and how loudly. + */ +const make = Effect.gen(function* () { + const hub = yield* KinChatHub; + const sender = yield* KinPushSender; + // What each open card last pushed for. A card redraws often; it rings again only when it + // starts waiting on someone new or changes phase. Lost on restart: at most one repeat. + const announced = new Map< + KinWidgetId, + { readonly phase: string; readonly awaiting: Set } + >(); + + const onWidget = Effect.fn("KinPushDispatch.onWidget")(function* (widget: KinWidget) { + const previous = announced.get(widget.widgetId); + if (widget.closedAt !== null || widget.awaiting.length === 0) { + announced.delete(widget.widgetId); + return; + } + const phase = phaseOf(widget); + announced.set(widget.widgetId, { phase, awaiting: new Set(widget.awaiting) }); + const fresh = + previous === undefined || + previous.phase !== phase || + widget.awaiting.some((person) => !previous.awaiting.has(person)); + if (!fresh) return; + if (widget.type !== "approval") { + yield* sender.notify({ _tag: "widget", orgId: widget.orgId, widgetId: widget.widgetId }); + return; + } + // An approval rings once, when its card first waits; the action's own push says the rest. + const actionId = actionOf(widget); + if (actionId !== null && previous === undefined) + yield* sender.notify({ _tag: "approval", orgId: widget.orgId, actionId }); + }); + + const events = yield* hub.subscribeAll; + yield* Stream.runForEach(events, (event) => + event.type === "message.posted" && event.message.status === "posted" + ? sender.notify({ _tag: "message", orgId: event.orgId, messageId: event.message.messageId }) + : event.type === "widget.updated" + ? onWidget(event.widget) + : Effect.void, + ).pipe(Effect.forkScoped); +}); + +export const layer = Layer.effectDiscard(make); diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts index da8da3304295..ac7518e581f3 100644 --- a/apps/server/src/kin/push/KinPushSender.test.ts +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -31,6 +31,7 @@ import * as Audit from "../approvals/Audit.ts"; import { KinAttestationTrust } from "../approvals/attestation/AttestationTrust.ts"; import * as PendingActions from "../approvals/PendingActions.ts"; import { layerKinAuthTest, repairProofKey } from "../auth/ProofKeySessions.testkit.ts"; +import * as MemoryCache from "../memory/MemoryCache.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import { KinApnsTransport, type KinApnsPush, type KinApnsResult } from "./Apns.ts"; import { KinPushDevices, type KinPushCaller } from "./KinPushDevices.ts"; @@ -88,6 +89,7 @@ const buildOn = (apns: ReturnType, database: Layer.Lay Sender.layer.pipe( Layer.provideMerge(Layer.mergeAll(Devices.layer, Presence.layer, apns.layer)), Layer.provideMerge(ApproverKeys.layer), + Layer.provide(MemoryCache.layer), Layer.provideMerge(PendingActions.layer), Layer.provideMerge(Audit.layer), Layer.provide(Layer.succeed(KinAttestationTrust, { load: () => Effect.die("unused") })), @@ -129,15 +131,35 @@ const seed = Effect.gen(function* () { VALUES (${thumbprint}, 'org_01', '{}', ${person}, 'Phone', 'ios', 'secure_enclave', 1, 'sess-key', ${state}, ${NOW})`; } - yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, last_seq, created_at) - VALUES ('chat_team', 'org_01', 'project_group', 0, ${T})`; - for (const [memberId, person, role] of [ - ["m_owner", owner, "owner"], - ["m_priya", member, "member"], + // The owner's quiet hours are 21:00 to 08:00 in New York; NOW is 19:00 there. + yield* sql`INSERT INTO kin_trigger_settings (org_id, time_zone, morning_brief, evening_summary, + dream, full_rebuild_weekday, owner_check_weekday, owner_check, quiet_hours_json) + VALUES ('org_01', 'America/New_York', '08:00', '18:00', '03:00', 0, 1, '09:00', + '{"from":"21:00","to":"08:00"}')`; + yield* sql`INSERT INTO kin_agents (agent_id, org_id, display_name, role, owner_person_id, + created_at) + VALUES ('lead_fin', 'org_01', 'Finance', 'lead', ${owner}, ${T})`; + // A group of both people and the Finance lead, and the owner's direct chat with the lead. + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, title, last_seq, created_at) + VALUES ('chat_team', 'org_01', 'project_group', 'Payments team', 0, ${T})`; + yield* sql`INSERT INTO kin_chats (chat_id, org_id, kind, direct_key, last_seq, created_at) + VALUES ('chat_dm', 'org_01', 'direct', 'h_owner:lead_fin', 0, ${T})`; + for (const [memberId, chat, person, role] of [ + ["m_owner", "chat_team", owner, "owner"], + ["m_priya", "chat_team", member, "member"], + ["m_owner_dm", "chat_dm", owner, "owner"], ] as const) { yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, person_id, role, joined_at) - VALUES (${memberId}, 'org_01', 'chat_team', 'person', ${person}, ${role}, ${T})`; + VALUES (${memberId}, 'org_01', ${chat}, 'person', ${person}, ${role}, ${T})`; + } + for (const [memberId, chat] of [ + ["m_fin", "chat_team"], + ["m_fin_dm", "chat_dm"], + ] as const) { + yield* sql`INSERT INTO kin_chat_members (member_id, org_id, chat_id, principal_kind, agent_id, + role, joined_at) + VALUES (${memberId}, 'org_01', ${chat}, 'agent', 'lead_fin', 'member', ${T})`; } const devices = yield* KinPushDevices; yield* devices.register(caller("sess-owner-phone", owner), { @@ -165,21 +187,37 @@ const seed = Effect.gen(function* () { return { sql, devices, sender, notify }; }); +type Author = + | { readonly personId: KinPersonId; readonly memberId: string } + | { readonly agentMemberId: string } + | "system"; + const postMessage = ( sql: SqlClient.SqlClient, - author: { readonly personId: KinPersonId; readonly memberId: string } | "system", + author: Author, status = "posted", + options: { + readonly chatId?: string; + readonly body?: string; + readonly mentions?: ReadonlyArray; + readonly replyTo?: KinMessageId; + } = {}, ) => Effect.gen(function* () { const [{ seq }] = (yield* sql<{ seq: number }>` SELECT COALESCE(MAX(seq), 0) + 1 AS seq FROM kin_messages`) as [{ seq: number }]; const messageId = KinMessageId.make(`msg_${seq}`); - const human = author !== "system"; + const human = typeof author === "object" && "personId" in author; + const agent = typeof author === "object" && "agentMemberId" in author; yield* sql`INSERT INTO kin_messages (message_id, org_id, chat_id, seq, author_kind, - author_person_id, author_member_id, author_role, kind, body, mentions_json, status, created_at) - VALUES (${messageId}, 'org_01', 'chat_team', ${seq}, ${human ? "human" : "system"}, - ${human ? author.personId : null}, ${human ? author.memberId : null}, 'member', 'text', - 'Ship it before Friday, the secret is hunter2', '[]', ${status}, ${T})`; + author_person_id, author_agent_id, author_owner_person_id, author_thread_id, + author_member_id, author_role, kind, body, mentions_json, reply_to, status, created_at) + VALUES (${messageId}, 'org_01', ${options.chatId ?? "chat_team"}, ${seq}, + ${human ? "human" : agent ? "agent" : "system"}, ${human ? author.personId : null}, + ${agent ? "lead_fin" : null}, ${agent ? owner : null}, ${agent ? "thread-fin" : null}, + ${human ? author.memberId : agent ? author.agentMemberId : null}, 'member', 'text', + ${options.body ?? "Ship it before Friday, the secret is hunter2"}, + ${JSON.stringify(options.mentions ?? [])}, ${options.replyTo ?? null}, ${status}, ${T})`; return messageId; }); @@ -199,6 +237,9 @@ const postWidget = ( return widgetId; }); +const alerts = (sent: ReadonlyArray) => + sent.map((push) => (push.payload as { aps: { alert?: object } }).aps.alert); + const categories = (sent: ReadonlyArray) => sent.map((push) => (push.payload as { aps: { category: string } }).aps.category); @@ -263,6 +304,7 @@ describe("KinPushSender", () => { assert.deepStrictEqual(apns.sent[0]?.payload, { aps: { alert: { title: "Approval needed", body: "Merge #212 is waiting on you" }, + badge: 0, category: "kin.approval", sound: "default", }, @@ -330,7 +372,9 @@ describe("KinPushSender", () => { yield* notify({ _tag: "widget", orgId, widgetId }); assert.deepStrictEqual(apns.sent[0]?.payload, { aps: { - alert: { title: "Deferred", body: "A deferral needs a look" }, + alert: { title: "Payments team", body: "A deferral needs a look" }, + // Seven unread card messages in the group, nothing in Waiting on you. + badge: 7, category: "kin.deferral.confirmed", sound: "default", "thread-id": "kin:org_01:chat_team", @@ -346,25 +390,176 @@ describe("KinPushSender", () => { }); assert.isUndefined(apns.sent[0]?.collapseId); + // A card that waits on someone rings as a card, not again as its message. + const card = yield* postWidget(sql, "task", { status: "needs_decision" }, [member]); + const [{ messageId: carded }] = (yield* sql<{ messageId: KinMessageId }>` + SELECT message_id AS "messageId" FROM kin_widgets WHERE widget_id = ${card}`) as [ + { messageId: KinMessageId }, + ]; + assert.strictEqual((yield* notify({ _tag: "message", orgId, messageId: carded })).sent, 0); + // A suggestion only the owner can see isn't announced to anyone. + const suggested = yield* postMessage(sql, "system", "suggested"); + assert.strictEqual((yield* notify({ _tag: "message", orgId, messageId: suggested })).sent, 0); + }).pipe(Effect.provide(build(apns))); + }); + + it.effect("rings a person in a group only for what concerns them, and always in a DM", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { notify, sql } = yield* seed; + const fin = { agentMemberId: "m_fin" } as const; + const priyaSaid = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); + const long = `Payroll for November is ready to review. ${"The totals match the ledger. ".repeat(8)}`; + const cases = [ + ["an agent line in the group", fin, {}, []], + ["a mention of Priya", fin, { mentions: ["m_priya"] }, [memberPhone]], + [ + "the owner's reply to Priya", + { personId: owner, memberId: "m_owner" }, + { replyTo: priyaSaid }, + [memberPhone], + ], + // The owner mentions Priya; the owner never hears their own message. + [ + "the owner's own mention", + { personId: owner, memberId: "m_owner" }, + { mentions: ["m_priya", "m_owner"] }, + [memberPhone], + ], + [ + "the lead in the owner's DM", + { agentMemberId: "m_fin_dm" }, + { chatId: "chat_dm" }, + [ownerPhone, ownerTablet], + ], + ] as const; + for (const [name, author, options, expected] of cases) { + apns.sent.length = 0; + const messageId = yield* postMessage(sql, author, "posted", options); + yield* notify({ _tag: "message", orgId, messageId }); + assert.deepStrictEqual( + apns.sent.map((push) => push.token), + [...expected], + name, + ); + } + apns.sent.length = 0; - const messageId = yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); - yield* notify({ _tag: "message", orgId, messageId }); - // The author doesn't hear about their own message, and the text never leaves the server. - assert.deepStrictEqual( - apns.sent.map((push) => push.token), - [memberPhone], - ); - assert.deepStrictEqual(categories(apns.sent), ["kin.message"]); + const mention = yield* postMessage(sql, fin, "posted", { + mentions: ["m_priya"], + body: "**Priya**, can you check the [invoice](https://x.test/1)?", + }); + yield* notify({ _tag: "message", orgId, messageId: mention }); + assert.deepStrictEqual(alerts(apns.sent), [ + { title: "Payments team · Finance", body: "Priya, can you check the invoice?" }, + ]); + assert.match(apns.sent[0]?.collapseId ?? "", /^kin:[0-9a-f]{12}$/); assert.include( JSON.stringify(apns.sent[0]?.payload), - '"deepLink":"/kin/env_kin/org_01/chats/', + '"deepLink":"/kin/env_kin/org_01/chats/chat_team"', ); - assert.notInclude(JSON.stringify(apns.sent), "hunter2"); - // Messages collapse per chat; cards don't, since each one waits on something different. - assert.match(apns.sent[0]?.collapseId ?? "", /^kin:[0-9a-f]{12}$/); - // A suggestion only the owner can see isn't announced to anyone. - const suggested = yield* postMessage(sql, "system", "suggested"); - assert.strictEqual((yield* notify({ _tag: "message", orgId, messageId: suggested })).sent, 0); + + apns.sent.length = 0; + const dm = yield* postMessage(sql, { agentMemberId: "m_fin_dm" }, "posted", { + chatId: "chat_dm", + body: long, + }); + yield* notify({ _tag: "message", orgId, messageId: dm }); + const [first] = alerts(apns.sent); + assert.strictEqual(first?.title, "Finance"); + // Cut at a word, under the banner's length, and marked as cut. + assert.isAtMost(Array.from(first?.body ?? "").length, 160); + assert.match(first?.body ?? "", /^Payroll for November is ready to review\. .*ledger\.…$/); + }).pipe(Effect.provide(build(apns))); + }); + + it.effect("counts unread and waiting across chats in the badge", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { notify, sql } = yield* seed; + const dm = { agentMemberId: "m_fin_dm" } as const; + const read = yield* postMessage(sql, dm, "posted", { chatId: "chat_dm" }); + yield* sql`INSERT INTO kin_read_state (org_id, chat_id, member_id, last_read_seq, updated_at) + SELECT 'org_01', 'chat_dm', 'm_owner_dm', seq, ${T} FROM kin_messages + WHERE message_id = ${read}`; + // Unread: one agent line in the group (it rang nobody, but it counts) and one in the DM. + yield* postMessage(sql, { agentMemberId: "m_fin" }); + // The owner's own message isn't unread to them. + yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); + for (const [waitingId, resolvedAt] of [ + ["wait_open", null], + ["wait_done", T], + ] as const) + yield* sql`INSERT INTO kin_waiting (waiting_id, org_id, person_id, chat_id, reason, + created_at, resolved_at) + VALUES (${waitingId}, 'org_01', ${owner}, 'chat_team', 'question', ${T}, ${resolvedAt})`; + apns.sent.length = 0; + const messageId = yield* postMessage(sql, dm, "posted", { chatId: "chat_dm" }); + yield* notify({ _tag: "message", orgId, messageId }); + // Two unread in the group, one in the DM, one open waiting item. + assert.deepStrictEqual( + apns.sent.map((push) => (push.payload as { aps: { badge: number } }).aps.badge), + [3, 3], + ); + }).pipe(Effect.provide(build(apns))); + }); + + it.effect("keeps quiet hours silent, except for what the owner timed", () => { + const apns = makeApns(); + return Effect.gen(function* () { + const { notify, sql } = yield* seed; + const dm = { agentMemberId: "m_fin_dm" } as const; + const sound = () => + apns.sent.map((push) => (push.payload as { aps: { sound?: string } }).aps.sound ?? null); + const lead = (chatId: string) => + postMessage(sql, dm, "posted", { chatId, body: "Your reminder: call the bank" }); + // 22:00 in New York. + yield* TestClock.setTime(Date.parse("2026-11-08T03:00:00Z")); + apns.sent.length = 0; + yield* notify({ _tag: "message", orgId, messageId: yield* lead("chat_dm") }); + assert.deepStrictEqual(sound(), [null, null]); + assert.deepStrictEqual(apns.sent[0]?.payload, { + aps: { badge: 1 }, + body: { + kin: 1, + orgId, + chatId: "chat_dm", + deepLink: "/kin/env_kin/org_01/chats/chat_dm", + }, + }); + + // Kin's own fallback for a reminder carries the reminder card. + const fallback = yield* postMessage(sql, "system", "posted", { chatId: "chat_dm" }); + yield* sql`INSERT INTO kin_widgets (widget_id, org_id, chat_id, message_id, widget_class, + type, revision, state_json, awaiting_json, updated_at) + VALUES ('w_reminder', 'org_01', 'chat_dm', ${fallback}, 'native', 'reminder', 1, '{}', + '[]', ${T})`; + // The lead writing a scheduled task's result while that wake-up runs. + yield* sql`INSERT INTO kin_leads (agent_id, org_id, name, level_since, models_json, + worker_projects_json, owner_chat_id) + VALUES ('lead_fin', 'org_01', 'Finance', 0, '[]', '[]', 'chat_dm')`; + yield* sql`INSERT INTO kin_wakeups (wakeup_id, org_id, agent_id, model, started_at, status, + event_ids) + VALUES ('wk_1', 'org_01', 'lead_fin', 'opus', ${NOW}, 'running', '["ev_1"]')`; + yield* sql`INSERT INTO kin_events (event_id, org_id, agent_id, tag, priority, json, + received_at, queued_at, state, wakeup_id) + VALUES ('ev_1', 'org_01', 'lead_fin', 'scheduled_task', 'P2', '{}', ${NOW}, ${NOW}, + 'claimed', 'wk_1')`; + yield* sql`INSERT INTO kin_lead_deliveries (org_id, event_id, kind, agent_id, chat_id, + widget_id, widget_type, state_json, fallback_body, deadline_at, status, created_at, + updated_at) + VALUES ('org_01', 'ev_1', 'scheduled_task', 'lead_fin', 'chat_dm', 'w_task', + 'scheduled_task', '{}', 'Kin ran it', ${NOW}, 'pending', ${NOW}, ${NOW})`; + for (const messageId of [fallback, yield* lead("chat_dm")]) { + apns.sent.length = 0; + yield* notify({ _tag: "message", orgId, messageId }); + assert.deepStrictEqual(sound(), ["default", "default"], messageId); + } + // Once that wake-up ends, the lead's next line is quiet again. + yield* sql`UPDATE kin_wakeups SET status = 'completed', ended_at = ${NOW}`; + apns.sent.length = 0; + yield* notify({ _tag: "message", orgId, messageId: yield* lead("chat_dm") }); + assert.deepStrictEqual(sound(), [null, null]); }).pipe(Effect.provide(build(apns))); }); @@ -375,7 +570,14 @@ describe("KinPushSender", () => { const presence = yield* KinPushPresence; const phone = AuthSessionId.make("sess-owner-phone"); const chat = KinChatId.make("chat_team"); - const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); + const messageId = yield* postMessage( + sql, + { personId: member, memberId: "m_priya" }, + "posted", + { + mentions: ["m_owner"], + }, + ); const watching = yield* presence .watch(phone, chat) .pipe(Stream.runDrain, Effect.forkChild({ startImmediately: true })); @@ -385,6 +587,20 @@ describe("KinPushSender", () => { apns.sent.map((push) => push.token), [ownerTablet], ); + // Watching one chat quiets only that chat: the DM still reaches the phone, until the + // phone opens the DM too, say beside the group on a wide screen. + const dm = KinChatId.make("chat_dm"); + const lead = () => + postMessage(sql, { agentMemberId: "m_fin_dm" }, "posted", { chatId: "chat_dm" }); + const elsewhere = yield* notify({ _tag: "message", orgId, messageId: yield* lead() }); + assert.deepStrictEqual(elsewhere, { status: "ready", sent: 2, suppressed: 0, failed: 0 }); + const both = yield* presence + .watch(phone, dm) + .pipe(Stream.runDrain, Effect.forkChild({ startImmediately: true })); + const bothOpen = yield* notify({ _tag: "message", orgId, messageId: yield* lead() }); + assert.deepStrictEqual(bothOpen, { status: "ready", sent: 1, suppressed: 1, failed: 0 }); + assert.deepStrictEqual((yield* notify({ _tag: "message", orgId, messageId })).suppressed, 1); + yield* Fiber.interrupt(both); // Closing the watch ends the suppression. yield* Fiber.interrupt(watching); const closed = yield* notify({ _tag: "message", orgId, messageId }); @@ -402,7 +618,7 @@ describe("KinPushSender", () => { }).pipe(Effect.provide(build(apns))); }); - it.effect("reaches only people still in the chat, in this org, and not muted", () => { + it.effect("reaches only people still in the chat and in this org; muted gets the badge", () => { const apns = makeApns(); return Effect.gen(function* () { const { notify, sql, devices } = yield* seed; @@ -423,14 +639,30 @@ describe("KinPushSender", () => { yield* sql`UPDATE kin_chat_members SET muted_until = ${mutedUntil}, left_at = ${left} WHERE member_id = 'm_priya'`; apns.sent.length = 0; - const messageId = yield* postMessage(sql, { personId: owner, memberId: "m_owner" }); + const messageId = yield* postMessage( + sql, + { personId: owner, memberId: "m_owner" }, + "posted", + { + mentions: ["m_priya"], + }, + ); yield* notify({ _tag: "message", orgId, messageId }); - return apns.sent.map((push) => push.token); + return apns.sent.map((push) => [ + push.token, + "alert" in (push.payload as { aps: object }).aps ? "alert" : "badge only", + ]); }); - assert.deepStrictEqual(yield* recipients(null, null), [memberPhone]); + assert.deepStrictEqual(yield* recipients(null, null), [[memberPhone, "alert"]]); // 03:00 at +05:00 is 22:00Z yesterday: the mute is over, though the text sorts later. - assert.deepStrictEqual(yield* recipients("2026-11-08T03:00:00+05:00", null), [memberPhone]); - assert.deepStrictEqual(yield* recipients("2026-11-08T01:00:00Z", null), []); + assert.deepStrictEqual(yield* recipients("2026-11-08T03:00:00+05:00", null), [ + [memberPhone, "alert"], + ]); + // Muted: no banner or sound, but the badge still counts. + assert.deepStrictEqual(yield* recipients("2026-11-08T01:00:00Z", null), [ + [memberPhone, "badge only"], + ]); + assert.isUndefined(apns.sent[0]?.collapseId); assert.deepStrictEqual(yield* recipients(null, T), []); // A phone whose session was revoked hears nothing, even before anything reconciles. yield* sql`UPDATE auth_sessions SET revoked_at = ${T} WHERE session_id = 'sess-member'`; @@ -463,7 +695,14 @@ describe("KinPushSender", () => { platform: "ios", apsEnvironment: "production", }); - const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); + const messageId = yield* postMessage( + sql, + { personId: member, memberId: "m_priya" }, + "posted", + { + mentions: ["m_owner"], + }, + ); const outcome = yield* notify({ _tag: "message", orgId, messageId }); assert.deepStrictEqual(outcome, { status: "ready", sent: 6, suppressed: 0, failed: 0 }); assert.strictEqual(peak, 4); @@ -775,7 +1014,14 @@ describe("KinPushDevices", () => { return Effect.gen(function* () { const { notify, sql } = yield* seed; const notifyOwner = Effect.gen(function* () { - const messageId = yield* postMessage(sql, { personId: member, memberId: "m_priya" }); + const messageId = yield* postMessage( + sql, + { personId: member, memberId: "m_priya" }, + "posted", + { + mentions: ["m_owner"], + }, + ); return yield* notify({ _tag: "message", orgId, messageId }); }); // A wrong topic is our misconfiguration: the token stays. diff --git a/apps/server/src/kin/push/KinPushSender.ts b/apps/server/src/kin/push/KinPushSender.ts index 6b6dc205928e..85aa888e441c 100644 --- a/apps/server/src/kin/push/KinPushSender.ts +++ b/apps/server/src/kin/push/KinPushSender.ts @@ -11,6 +11,7 @@ import type { KinPushSendingStatus, KinWidgetId, } from "@t3tools/contracts"; +import { KinTriggerSettings } from "@t3tools/contracts"; import * as Context from "effect/Context"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; @@ -23,6 +24,8 @@ import * as SqlClient from "effect/sql/SqlClient"; import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; import { ApproverKeys } from "../approvals/ApproverKeys.ts"; import { KinPendingActions } from "../approvals/PendingActions.ts"; +import { MemoryCache } from "../memory/MemoryCache.ts"; +import { isQuiet, KIN_DEFAULT_QUIET_HOURS } from "../triggers/quietHours.ts"; import { KinApnsTransport } from "./Apns.ts"; import { KinPushDevices, kinPushDeviceId, type KinPushDevice } from "./KinPushDevices.ts"; import { KinPushPresence } from "./KinPushPresence.ts"; @@ -44,6 +47,9 @@ export type KinPushOutcome = { readonly failed: number; }; +/** Silent recipients get the badge only: no banner, no sound. */ +type Recipient = { readonly personId: KinPersonId; readonly silent: boolean }; + type Push = { readonly category: KinPushCategory; readonly title: string; @@ -52,7 +58,26 @@ type Push = { /** Message pushes collapse per chat, so a busy chat shows one banner. */ readonly collapseId?: string; readonly data: KinPushData; - readonly recipients: ReadonlyArray; + readonly recipients: ReadonlyArray; +}; + +/** The longest body a banner shows before iOS cuts it; we cut at a word first. */ +const KIN_PUSH_BODY_MAX = 160; + +/** A message's start as one plain line for a banner. */ +const kinPushBody = (text: string) => { + const plain = text + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/^\s{0,3}(?:#{1,6}|>|[-*+]|\d+\.)\s+/gm, "") + .replace(/```[^\s`]*/g, "") + .replace(/(\*\*|__|~~|`)/g, "") + .replace(/\s+/g, " ") + .trim(); + const chars = Array.from(plain); + if (chars.length <= KIN_PUSH_BODY_MAX) return plain; + const cut = chars.slice(0, KIN_PUSH_BODY_MAX - 1).join(""); + const space = cut.lastIndexOf(" "); + return `${(space > KIN_PUSH_BODY_MAX / 2 ? cut.slice(0, space) : cut).trimEnd()}…`; }; // APNs docs, "Handling notification responses". A 410 is handled by its timestamp instead. @@ -68,10 +93,21 @@ export const kinPushChatLink = (environmentId: EnvironmentId, orgId: KinOrgId, c /** Fits `apns-collapse-id`'s 64 bytes whatever the ids' length. */ const kinPushCollapseId = (orgId: KinOrgId, chatId: KinChatId) => `kin:${kinPushDeviceId(`${orgId}\u0000${chatId}`)}`; -const decodeAwaiting = Schema.decodeUnknownEffect( - Schema.fromJsonString(Schema.Array(Schema.String)), +const decodeIds = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Array(Schema.String))); +const decodeQuietHours = Schema.decodeUnknownOption( + Schema.fromJsonString(KinTriggerSettings.fields.quietHours), ); +/** + * Whether a message concerns someone enough to ring their phone. A direct chat is theirs; in a + * group only a mention of them or a reply to their message does (cards push on their own). + */ +const kinPushConcerns = (input: { + readonly direct: boolean; + readonly mentioned: boolean; + readonly repliesToThem: boolean; +}) => input.direct || input.mentioned || input.repliesToThem; + /** Fixed text per kind: ids and numbers from the action, never the agent's reason. */ const approvalPushText = (action: KinPendingAction) => { switch (action.target._tag) { @@ -110,30 +146,86 @@ const make = Effect.gen(function* () { const devices = yield* KinPushDevices; const presence = yield* KinPushPresence; const keys = yield* ApproverKeys; + const cache = yield* MemoryCache; const actions = yield* KinPendingActions; const environmentId = yield* (yield* ServerEnvironment.ServerEnvironment).getEnvironmentId; const host = segment(environmentId); const chatLink = (orgId: KinOrgId, chatId: KinChatId) => kinPushChatLink(environmentId, orgId, chatId); - /** People in the chat now. Muting silences messages, not things waiting on you. */ + /** People in the chat now, each with whether they muted it. */ const chatPeople = Effect.fn("KinPushSender.chatPeople")(function* ( orgId: KinOrgId, chatId: KinChatId, - options: { readonly respectMute: boolean }, ) { const now = yield* Clock.currentTimeMillis; - const rows = yield* sql<{ person_id: KinPersonId; muted_until: string | null }>` - SELECT person_id, muted_until FROM kin_chat_members + const rows = yield* sql<{ + person_id: KinPersonId; + member_id: string; + muted_until: string | null; + }>` + SELECT person_id, member_id, muted_until FROM kin_chat_members WHERE org_id = ${orgId} AND chat_id = ${chatId} AND principal_kind = 'person' AND left_at IS NULL ORDER BY person_id`; - return rows - .filter( - (row) => - !options.respectMute || row.muted_until === null || !(Date.parse(row.muted_until) > now), - ) - .map((row) => row.person_id); + return rows.map((row) => ({ + personId: row.person_id, + memberId: row.member_id, + muted: row.muted_until !== null && Date.parse(row.muted_until) > now, + })); + }); + + /** What a chat is called on a banner: its title, or the lead a direct chat is with. */ + const chatName = Effect.fn("KinPushSender.chatName")(function* ( + orgId: KinOrgId, + chatId: KinChatId, + ) { + const [row] = yield* sql<{ kind: string; title: string | null; agent: string | null }>` + SELECT c.kind, c.title, ( + SELECT a.display_name FROM kin_chat_members m + JOIN kin_agents a ON a.org_id = m.org_id AND a.agent_id = m.agent_id + WHERE m.org_id = c.org_id AND m.chat_id = c.chat_id AND m.principal_kind = 'agent' + AND m.left_at IS NULL + ORDER BY m.joined_at, m.member_id LIMIT 1 + ) AS agent + FROM kin_chats c WHERE c.org_id = ${orgId} AND c.chat_id = ${chatId}`; + const direct = row?.kind === "direct"; + return { direct, name: row?.title ?? (direct ? (row?.agent ?? "Kin") : "Group") }; + }); + + /** Quiet hours as pings keep them: the org's hours on the owner's clock. */ + const quietNow = Effect.fn("KinPushSender.quietNow")(function* (orgId: KinOrgId) { + const [row] = yield* sql<{ quiet_hours_json: string }>` + SELECT quiet_hours_json FROM kin_trigger_settings WHERE org_id = ${orgId} ORDER BY org_id`; + const hours = Option.getOrElse( + decodeQuietHours(row?.quiet_hours_json), + () => KIN_DEFAULT_QUIET_HOURS, + ); + return isQuiet(yield* Clock.currentTimeMillis, yield* cache.ownerTimeZone(orgId), hours); + }); + + /** Unread messages plus open waiting items, across every chat the person is still in. */ + const badgeFor = Effect.fn("KinPushSender.badgeFor")(function* ( + orgId: KinOrgId, + personId: KinPersonId, + ) { + const [row] = yield* sql<{ unread: number; waiting: number }>` + SELECT ( + SELECT COUNT(*) FROM kin_chat_members cm + JOIN kin_messages m ON m.org_id = cm.org_id AND m.chat_id = cm.chat_id + WHERE cm.org_id = ${orgId} AND cm.person_id = ${personId} + AND cm.principal_kind = 'person' AND cm.left_at IS NULL + AND m.status = 'posted' + AND (m.author_member_id IS NULL OR m.author_member_id != cm.member_id) + AND m.seq > COALESCE((SELECT r.last_read_seq FROM kin_read_state r + WHERE r.chat_id = cm.chat_id AND r.member_id = cm.member_id), 0) + ) AS unread, ( + SELECT COUNT(*) FROM kin_waiting w + WHERE w.org_id = ${orgId} AND w.person_id = ${personId} AND w.resolved_at IS NULL + AND EXISTS (SELECT 1 FROM kin_chat_members cm WHERE cm.org_id = w.org_id + AND cm.chat_id = w.chat_id AND cm.person_id = w.person_id AND cm.left_at IS NULL) + ) AS waiting`; + return (row?.unread ?? 0) + (row?.waiting ?? 0); }); const approvalPush = Effect.fn("KinPushSender.approvalPush")(function* ( @@ -142,15 +234,20 @@ const make = Effect.gen(function* () { ) { const action = yield* actions.get({ orgId, actionId }); if (Option.isNone(action) || action.value.state !== "awaiting_approval") return undefined; + const [lead] = yield* sql<{ display_name: string }>` + SELECT display_name FROM kin_agents + WHERE org_id = ${orgId} AND agent_id = ${action.value.requestedBy.agentId}`; const deepLink = `/kin/${host}/${segment(orgId)}/actions/${segment(actionId)}`; + const quiet = yield* quietNow(orgId); + // DESIGN 9.3: approvers only, read from their keys, never from the request. + const approvers = yield* keys.activeApprovers(orgId); return { category: "kin.approval", - title: "Approval needed", + title: lead?.display_name ?? "Approval needed", body: approvalPushText(action.value), chatId: undefined, data: { kin: 1, orgId, pendingActionId: actionId, deepLink }, - // DESIGN 9.3: approvers only, read from their keys, never from the request. - recipients: yield* keys.activeApprovers(orgId), + recipients: approvers.map((personId) => ({ personId, silent: quiet })), } satisfies Push; }); @@ -158,15 +255,58 @@ const make = Effect.gen(function* () { orgId: KinOrgId, messageId: KinMessageId, ) { - const [row] = yield* sql<{ chat_id: KinChatId; author_person_id: KinPersonId | null }>` - SELECT chat_id, author_person_id FROM kin_messages - WHERE org_id = ${orgId} AND message_id = ${messageId} AND status = 'posted'`; - if (row === undefined) return undefined; - const people = yield* chatPeople(orgId, row.chat_id, { respectMute: true }); + const [row] = yield* sql<{ + chat_id: KinChatId; + author_kind: string; + author_person_id: KinPersonId | null; + author_member_id: string | null; + author_name: string | null; + body: string; + mentions_json: string; + reply_author: KinPersonId | null; + awaits_card: number; + owner_timed: number; + }>` + SELECT m.chat_id, m.author_kind, m.author_person_id, m.author_member_id, m.body, + m.mentions_json, + COALESCE( + (SELECT display_name FROM kin_agents a + WHERE a.org_id = m.org_id AND a.agent_id = m.author_agent_id), + (SELECT display_name FROM kin_people p + WHERE p.org_id = m.org_id AND p.person_id = m.author_person_id) + ) AS author_name, + (SELECT r.author_person_id FROM kin_messages r + WHERE r.org_id = m.org_id AND r.message_id = m.reply_to) AS reply_author, + EXISTS (SELECT 1 FROM kin_widgets w WHERE w.org_id = m.org_id + AND w.message_id = m.message_id AND w.closed_at IS NULL + AND w.awaiting_json != '[]') AS awaits_card, + (EXISTS (SELECT 1 FROM kin_widgets w WHERE w.org_id = m.org_id + AND w.message_id = m.message_id AND w.type IN ('reminder', 'scheduled_task')) + OR EXISTS (SELECT 1 FROM kin_lead_deliveries d + JOIN kin_events e ON e.org_id = d.org_id AND e.event_id = d.event_id + JOIN kin_wakeups k ON k.org_id = e.org_id AND k.wakeup_id = e.wakeup_id + WHERE d.org_id = m.org_id AND d.chat_id = m.chat_id + AND d.agent_id = m.author_agent_id AND d.kind IN ('reminder', 'scheduled_task') + AND k.status = 'running')) AS owner_timed + FROM kin_messages m + WHERE m.org_id = ${orgId} AND m.message_id = ${messageId} AND m.status = 'posted' + AND m.kind != 'widget_action'`; + // A card that waits on someone announces itself through its widget push. + if (row === undefined || row.awaits_card === 1) return undefined; + const chat = yield* chatName(orgId, row.chat_id); + const mentions = new Set(yield* decodeIds(row.mentions_json)); + // Reminders and scheduled runs come at the time the owner chose, so quiet hours let them ring. + const quiet = row.owner_timed === 1 ? false : yield* quietNow(orgId); + const people = yield* chatPeople(orgId, row.chat_id); + const author = row.author_name; return { category: "kin.message", - title: "Kin", - body: "New message", + title: chat.direct + ? (author ?? chat.name) + : author === null + ? chat.name + : `${chat.name} · ${author}`, + body: kinPushBody(row.body) || "New message", chatId: row.chat_id, collapseId: kinPushCollapseId(orgId, row.chat_id), data: { @@ -175,7 +315,18 @@ const make = Effect.gen(function* () { chatId: row.chat_id, deepLink: chatLink(orgId, row.chat_id), }, - recipients: people.filter((person) => person !== row.author_person_id), + recipients: people + .filter( + (person) => + person.personId !== row.author_person_id && + person.memberId !== row.author_member_id && + kinPushConcerns({ + direct: chat.direct, + mentioned: mentions.has(person.memberId), + repliesToThem: row.reply_author === person.personId, + }), + ) + .map((person) => ({ personId: person.personId, silent: person.muted || quiet })), } satisfies Push; }); @@ -200,25 +351,21 @@ const make = Effect.gen(function* () { if (row.type === "approval") return undefined; const kind = row.type !== "deferral" - ? ({ category: "kin.message", title: "Waiting on you", body: "A card needs you" } as const) + ? ({ category: "kin.message", body: "A card is waiting on you" } as const) : row.phase === "confirmed" || row.phase === null - ? ({ - category: "kin.deferral.confirmed", - title: "Deferred", - body: "A deferral needs a look", - } as const) + ? ({ category: "kin.deferral.confirmed", body: "A deferral needs a look" } as const) : row.phase === "heads_up" - ? ({ - category: "kin.deferral.heads_up", - title: "Starting soon", - body: "A deferred task starts soon", - } as const) + ? ({ category: "kin.deferral.heads_up", body: "A deferred task starts soon" } as const) : undefined; if (kind === undefined) return undefined; - const awaiting = new Set(yield* decodeAwaiting(row.awaiting_json)); - const people = yield* chatPeople(orgId, row.chat_id, { respectMute: false }); + const awaiting = new Set(yield* decodeIds(row.awaiting_json)); + const chat = yield* chatName(orgId, row.chat_id); + // A heads-up comes at the time the owner deferred the task to. + const quiet = row.phase === "heads_up" ? false : yield* quietNow(orgId); + const people = yield* chatPeople(orgId, row.chat_id); return { ...kind, + title: chat.name, chatId: row.chat_id, data: { kin: 1, @@ -228,7 +375,9 @@ const make = Effect.gen(function* () { revision: row.revision, deepLink: chatLink(orgId, row.chat_id), }, - recipients: people.filter((person) => awaiting.has(person)), + recipients: people + .filter((person) => awaiting.has(person.personId)) + .map((person) => ({ personId: person.personId, silent: person.muted || quiet })), } satisfies Push; }); @@ -236,20 +385,25 @@ const make = Effect.gen(function* () { orgId: KinOrgId, push: Push, device: KinPushDevice, + recipient: { readonly silent: boolean; readonly badge: number }, ) { if (push.chatId !== undefined && (yield* presence.isWatching(device.sessionId, push.chatId))) return "suppressed" as const; const result = yield* apns.send({ token: device.token, environment: device.apsEnvironment, - ...(push.collapseId === undefined ? {} : { collapseId: push.collapseId }), + // A badge-only push must not replace the banner a loud one left under the same id. + ...(push.collapseId === undefined || recipient.silent ? {} : { collapseId: push.collapseId }), payload: { - aps: { - alert: { title: push.title, body: push.body }, - category: push.category, - sound: "default", - ...(push.chatId === undefined ? {} : { "thread-id": `kin:${orgId}:${push.chatId}` }), - }, + aps: recipient.silent + ? { badge: recipient.badge } + : { + alert: { title: push.title, body: push.body }, + badge: recipient.badge, + category: push.category, + sound: "default", + ...(push.chatId === undefined ? {} : { "thread-id": `kin:${orgId}:${push.chatId}` }), + }, // expo-notifications reads a remote push's `content.data` from `body`. body: push.data, }, @@ -288,11 +442,24 @@ const make = Effect.gen(function* () { }); const deliver = Effect.fn("KinPushSender.deliver")(function* (orgId: KinOrgId, push: Push) { - const targets = yield* devices.forPeople(orgId, push.recipients); + const recipients = new Map(); + for (const recipient of push.recipients) + recipients.set(recipient.personId, { + silent: recipient.silent, + badge: yield* badgeFor(orgId, recipient.personId), + }); + const targets = yield* devices.forPeople(orgId, [...recipients.keys()]); // Bounded, so one slow device doesn't hold up the rest and a big org doesn't flood APNs. - const results = yield* Effect.forEach(targets, (device) => sendTo(orgId, push, device), { - concurrency: SEND_CONCURRENCY, - }); + const results = yield* Effect.forEach( + targets, + (device) => { + const recipient = recipients.get(device.personId); + return recipient === undefined + ? Effect.succeed("failed" as const) + : sendTo(orgId, push, device, recipient); + }, + { concurrency: SEND_CONCURRENCY }, + ); const count = (outcome: (typeof results)[number]) => results.filter((result) => result === outcome).length; return { sent: count("sent"), suppressed: count("suppressed"), failed: count("failed") }; diff --git a/apps/server/src/kin/push/layer.ts b/apps/server/src/kin/push/layer.ts index 817274be6f12..9279591b556d 100644 --- a/apps/server/src/kin/push/layer.ts +++ b/apps/server/src/kin/push/layer.ts @@ -1,12 +1,16 @@ import * as Layer from "effect/Layer"; +import * as Cache from "../memory/MemoryCache.ts"; import * as KinPersistence from "../persistence/KinPersistence.ts"; import * as Apns from "./Apns.ts"; import * as Devices from "./KinPushDevices.ts"; +import * as Dispatch from "./KinPushDispatch.ts"; import * as Presence from "./KinPushPresence.ts"; import * as Sender from "./KinPushSender.ts"; -export const layer = Sender.layer.pipe( +export const layer = Dispatch.layer.pipe( + Layer.provideMerge(Sender.layer), Layer.provideMerge(Layer.mergeAll(Devices.layer, Presence.layer, Apns.layer)), + Layer.provide(Cache.layer), Layer.provide(KinPersistence.layer), ); diff --git a/apps/server/src/kin/triggers/pings.ts b/apps/server/src/kin/triggers/pings.ts index f0bb2878622e..8b8124fdf550 100644 --- a/apps/server/src/kin/triggers/pings.ts +++ b/apps/server/src/kin/triggers/pings.ts @@ -23,6 +23,7 @@ import { PersistenceSqlError, toPersistenceSqlError } from "../../persistence/Er import * as Chat from "../chat/KinChatService.ts"; import * as Memory from "../memory/Memory.ts"; import * as Cache from "../memory/MemoryCache.ts"; +import { isQuiet, KIN_DEFAULT_QUIET_HOURS } from "./quietHours.ts"; const text = Schema.String.check( Schema.isTrimmed(), @@ -95,13 +96,6 @@ function validZone(zone: string | undefined, fallback: string) { return fallback; } } -function isQuiet(now: number, zone: string, hours: { readonly from: string; readonly to: string }) { - const p = localParts(now, zone); - const time = `${String(p.hour).padStart(2, "0")}:${String(p.minute).padStart(2, "0")}`; - return hours.from < hours.to - ? time >= hours.from && time < hours.to - : hours.from > hours.to && (time >= hours.from || time < hours.to); -} export function quoted(value: string) { const content = Array.from(value.replace(/[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/gu, " ")) @@ -217,8 +211,7 @@ const make = Effect.gen(function* () { quiet_hours_json: string; }>`SELECT quiet_hours_json FROM kin_trigger_settings WHERE org_id = ${orgId} ORDER BY org_id`; const defaultHours = decodeJsonQuiet(settings[0]?.quiet_hours_json); - const hours = - defaultHours._tag === "Some" ? defaultHours.value : { from: "21:00", to: "08:00" }; + const hours = defaultHours._tag === "Some" ? defaultHours.value : KIN_DEFAULT_QUIET_HOURS; const people = yield* memory.query(orgId, { kind: "person", excludeInvalid: true }); const candidates: Array<{ row: Row; diff --git a/apps/server/src/kin/triggers/quietHours.ts b/apps/server/src/kin/triggers/quietHours.ts new file mode 100644 index 000000000000..5bd61b4331bf --- /dev/null +++ b/apps/server/src/kin/triggers/quietHours.ts @@ -0,0 +1,15 @@ +import * as DateTime from "effect/DateTime"; + +export type KinQuietHours = { readonly from: string; readonly to: string }; + +/** Used until the owner sets their own in Kin's settings. */ +export const KIN_DEFAULT_QUIET_HOURS: KinQuietHours = { from: "21:00", to: "08:00" }; + +/** Whether `now` falls in `hours` on the wall clock of `zone`; `from` after `to` spans midnight. */ +export function isQuiet(now: number, zone: string, hours: KinQuietHours) { + const p = DateTime.toParts(DateTime.makeZonedUnsafe(now, { timeZone: zone })); + const time = `${String(p.hour).padStart(2, "0")}:${String(p.minute).padStart(2, "0")}`; + return hours.from < hours.to + ? time >= hours.from && time < hours.to + : hours.from > hours.to && (time >= hours.from || time < hours.to); +} diff --git a/packages/client-runtime/src/kin/kinInboxModel.test.ts b/packages/client-runtime/src/kin/kinInboxModel.test.ts index 7b715ff19ba4..a09ab68c11e1 100644 --- a/packages/client-runtime/src/kin/kinInboxModel.test.ts +++ b/packages/client-runtime/src/kin/kinInboxModel.test.ts @@ -21,6 +21,7 @@ import { emptyKinChat, emptyKinInbox, KIN_CACHED_MESSAGE_LIMIT, + kinBadgeCount, selectKinInboxView, trimKinChatForCache, type KinChatState, @@ -168,15 +169,18 @@ describe("kin inbox", () => { expect(state.chats[0]!.unread).toBe(1); state = applyKinInboxEvent(state, { _tag: "chat", chat: chat("a", { lastSeq: 5, unread: 0 }) }); expect(state.chats[0]!.unread).toBe(0); - state = applyKinInboxEvent(state, { _tag: "chat", chat: chat("b") }); + state = applyKinInboxEvent(state, { _tag: "chat", chat: chat("b", { unread: 2 }) }); expect(state.chats.map((c) => c.chatId)).toEqual(["a", "b"]); state = applyKinInboxEvent(state, { _tag: "waiting", item: waiting("w2", "b") }); + // The badge: unread across chats plus what waits on the viewer. + expect(kinBadgeCount(state)).toBe(4); state = applyKinInboxEvent(state, { _tag: "waiting", item: waiting("w1", "a", { resolvedAt: at(3), resolution: "answered" }), }); expect(state.waiting.map((w) => w.waitingId)).toEqual(["w2"]); + expect(kinBadgeCount(state)).toBe(3); }); it("drops a chat the viewer left, with its waiting rows", () => { diff --git a/packages/client-runtime/src/kin/kinInboxModel.ts b/packages/client-runtime/src/kin/kinInboxModel.ts index 1dc906d07fe7..fc7f8f42bb01 100644 --- a/packages/client-runtime/src/kin/kinInboxModel.ts +++ b/packages/client-runtime/src/kin/kinInboxModel.ts @@ -41,6 +41,10 @@ export type KinInboxEvent = export const emptyKinInbox: KinInboxState = { chats: [], waiting: [] }; +/** The app badge, as the host counts it on every push: unread messages plus Waiting on you. */ +export const kinBadgeCount = (state: KinInboxState) => + state.chats.reduce((total, chat) => total + chat.unread, 0) + state.waiting.length; + export function applyKinInboxEvent(state: KinInboxState, event: KinInboxEvent): KinInboxState { switch (event._tag) { case "snapshot": diff --git a/packages/client-runtime/src/kin/kinScreenState.test.ts b/packages/client-runtime/src/kin/kinScreenState.test.ts index 9e9875ffa8fa..de0c2829f832 100644 --- a/packages/client-runtime/src/kin/kinScreenState.test.ts +++ b/packages/client-runtime/src/kin/kinScreenState.test.ts @@ -370,6 +370,27 @@ describe("chat list rows", () => { ); }); + it.each([ + ["the viewer's open mute", "owner", "9999-12-31T23:59:59.999Z", true], + ["a mute that ended", "owner", "2026-11-08T09:00:00.000Z", false], + ["someone else's mute", "lead", "9999-12-31T23:59:59.999Z", false], + ] as const)("marks a chat muted for %s", (_name, mutedBy, mutedUntil, muted) => { + const members = [ + { principal: { _tag: "person", personId: "owner" }, leftAt: null, mutedUntil: null }, + { principal: { _tag: "agent", agentId: "lead" }, leftAt: null, mutedUntil: null }, + ].map((member) => + ("personId" in member.principal ? member.principal.personId : member.principal.agentId) === + mutedBy + ? { ...member, mutedUntil } + : member, + ); + const view = kinChatRowView(row({ members }), directory, Date.parse("2026-11-08T10:00:00Z")); + expect(view.muted).toBe(muted); + expect(kinChatRowLabel(view, () => "9:30")).toBe( + `Tech lead, agent. Payments test fixed, PR 212 ready. 9:30.${muted ? " Muted." : ""} 3 unread.`, + ); + }); + it("prefixes the viewer's own message and drops a missing time and zero unread", () => { const view = kinChatRowView( row({ diff --git a/packages/client-runtime/src/kin/kinScreenState.ts b/packages/client-runtime/src/kin/kinScreenState.ts index 0cb1752defeb..861b10169aff 100644 --- a/packages/client-runtime/src/kin/kinScreenState.ts +++ b/packages/client-runtime/src/kin/kinScreenState.ts @@ -265,6 +265,8 @@ export interface KinChatRowView { readonly preview: string; readonly sentAt: string | null; readonly unread: number; + /** The viewer muted this chat's notifications; it still counts toward the badge. */ + readonly muted: boolean; } /** @@ -316,7 +318,27 @@ function kinMessagePreview(last: KinChatSummary["lastMessage"]): string { return kinPreviewText(last.body) || "Message"; } -export function kinChatRowView(row: KinInboxRow, directory: KinDirectory): KinChatRowView { +/** Whether the viewer's own membership mutes this chat's pushes right now. */ +export function kinChatMuted( + chat: Pick, + me: ReadonlySet, + now: number, +): boolean { + return chat.members.some( + (member) => + member.leftAt === null && + member.principal._tag === "person" && + me.has(member.principal.personId) && + member.mutedUntil != null && + Date.parse(member.mutedUntil) > now, + ); +} + +export function kinChatRowView( + row: KinInboxRow, + directory: KinDirectory, + now = Date.now(), +): KinChatRowView { const { chat } = row; const others = chat.members.filter( (member) => @@ -345,6 +367,7 @@ export function kinChatRowView(row: KinInboxRow, directory: KinDirectory): KinCh preview, sentAt: chat.lastMessageAt, unread: chat.unread, + muted: kinChatMuted(chat, directory.me, now), }; } @@ -415,6 +438,7 @@ export function kinChatRowLabel(view: KinChatRowView, formatTime: (date: Date) = `${view.title}, ${view.avatar.kind}`, preview.replace(/[.!?]+$/, ""), view.sentAt === null ? null : formatTime(new Date(view.sentAt)), + view.muted ? "Muted" : null, view.unread > 0 ? `${view.unread} unread` : null, ] .filter((part): part is string => part !== null && part.length > 0) diff --git a/packages/client-runtime/src/state/commandPermissions.test.ts b/packages/client-runtime/src/state/commandPermissions.test.ts index b94139d32c8e..9ad23750633e 100644 --- a/packages/client-runtime/src/state/commandPermissions.test.ts +++ b/packages/client-runtime/src/state/commandPermissions.test.ts @@ -18,6 +18,7 @@ import { ThreadId, EnvironmentId, KIN_APPROVAL_WS_METHODS, + KIN_CHAT_WS_METHODS, KIN_LEVEL_WS_METHODS, KIN_PUSH_WS_METHODS, ORCHESTRATION_V2_WS_METHODS, @@ -128,6 +129,8 @@ describe("command permissions", () => { ), ); it.effect.each([ + // Muting quiets only the caller's own pushes, so reading the chat is enough. + [KIN_CHAT_WS_METHODS.chatsMute, AuthOrchestrationReadScope], [KIN_LEVEL_WS_METHODS.get, AuthOrchestrationReadScope], [KIN_LEVEL_WS_METHODS.review, AuthOrchestrationOperateScope], [KIN_LEVEL_WS_METHODS.deferPromotion, AuthOrchestrationOperateScope], diff --git a/packages/contracts/src/kinChat.ts b/packages/contracts/src/kinChat.ts index 4c7465c0593d..6d09725fdeaf 100644 --- a/packages/contracts/src/kinChat.ts +++ b/packages/contracts/src/kinChat.ts @@ -448,6 +448,9 @@ export type KinMessagesSendInput = typeof KinMessagesSendInput.Type; export const KinMessagesMarkReadInput = Schema.Struct({ chatId: KinChatId, seq: NonNegativeInt }); export type KinMessagesMarkReadInput = typeof KinMessagesMarkReadInput.Type; export const KinMessagesMarkReadResult = Schema.Struct({}); +/** Mutes or unmutes the caller's own notifications for one chat; the badge still counts it. */ +export const KinChatsMuteInput = Schema.Struct({ chatId: KinChatId, muted: Schema.Boolean }); +export type KinChatsMuteInput = typeof KinChatsMuteInput.Type; export type KinMessagesMarkReadResult = typeof KinMessagesMarkReadResult.Type; export const KinWidgetsActInput = Schema.Struct({ widgetId: KinWidgetId, @@ -494,6 +497,7 @@ export const KIN_CHAT_WS_METHODS = { orgsList: "kin.orgs.list", chatsSubscribe: "kin.chats.subscribe", chatsCreateDirect: "kin.chats.createDirect", + chatsMute: "kin.chats.mute", chatSubscribe: "kin.chat.subscribe", chatHistory: "kin.chat.history", messagesSend: "kin.messages.send", @@ -519,6 +523,11 @@ export const KinChatRpcs = [ success: KinChat, error: Schema.Union([KinChatError, EnvironmentAuthorizationError]), }), + Rpc.make(KIN_CHAT_WS_METHODS.chatsMute, { + payload: KinChatsMuteInput, + success: KinChatMember, + error: Schema.Union([KinChatError, EnvironmentAuthorizationError]), + }), Rpc.make(KIN_CHAT_WS_METHODS.chatSubscribe, { payload: KinChatSubscribeInput, success: KinChatStreamEvent, @@ -556,6 +565,8 @@ export const KIN_CHAT_RPC_SCOPES = { [KIN_CHAT_WS_METHODS.orgsList]: AuthOrchestrationReadScope, [KIN_CHAT_WS_METHODS.chatsSubscribe]: AuthOrchestrationReadScope, [KIN_CHAT_WS_METHODS.chatsCreateDirect]: AuthOrchestrationOperateScope, + // Only quiets the caller's own pushes, like marking a chat read. + [KIN_CHAT_WS_METHODS.chatsMute]: AuthOrchestrationReadScope, [KIN_CHAT_WS_METHODS.chatSubscribe]: AuthOrchestrationReadScope, [KIN_CHAT_WS_METHODS.chatHistory]: AuthOrchestrationReadScope, [KIN_CHAT_WS_METHODS.messagesSend]: AuthOrchestrationOperateScope, diff --git a/packages/contracts/src/kinRpcs.ts b/packages/contracts/src/kinRpcs.ts index 028723075cc4..ffb327e08258 100644 --- a/packages/contracts/src/kinRpcs.ts +++ b/packages/contracts/src/kinRpcs.ts @@ -150,6 +150,7 @@ export const KIN_RPC_AGGREGATES = { "kin.orgs.list": "kin-chat", "kin.chats.subscribe": "kin-chat", "kin.chats.createDirect": "kin-chat", + "kin.chats.mute": "kin-chat", "kin.chat.subscribe": "kin-chat", "kin.chat.history": "kin-chat", "kin.messages.send": "kin-chat", From 8ed188f21b2381080191b6297a5527d232a533fd Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:05:58 +0530 Subject: [PATCH 2/4] test(contracts): round-trip the chat mute input Co-Authored-By: Claude Opus 5.5 --- packages/contracts/src/kinChat.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/contracts/src/kinChat.test.ts b/packages/contracts/src/kinChat.test.ts index 3e7c97b7c435..6f7128a8aaa8 100644 --- a/packages/contracts/src/kinChat.test.ts +++ b/packages/contracts/src/kinChat.test.ts @@ -299,6 +299,10 @@ const samples = { { messageId: "message-1", emoji: "👍", on: true }, { messageId: "message-1", emoji: "👀", on: false }, ], + KinChatsMuteInput: [ + { chatId: "chat-1", muted: true }, + { chatId: "chat-1", muted: false }, + ], KinLeadInterruptInput: [{ orgId: "org-1", wakeupId: "wakeup-1" }], KinLeadInterruptResult: [{ interrupted: true }, { interrupted: false }], KinChatError: [ From 43c1e9cee772e17bdd5039981d1c736eb87dbb21 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:07:20 +0530 Subject: [PATCH 3/4] test(mobile): route a lead's DM and a group push to their chats Co-Authored-By: Claude Opus 5.5 --- .../notifications/kinPushPayload.test.ts | 35 +++++++++++-------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/apps/mobile/src/features/chats/notifications/kinPushPayload.test.ts b/apps/mobile/src/features/chats/notifications/kinPushPayload.test.ts index a5f649af33fe..a38dcaf37b52 100644 --- a/apps/mobile/src/features/chats/notifications/kinPushPayload.test.ts +++ b/apps/mobile/src/features/chats/notifications/kinPushPayload.test.ts @@ -61,20 +61,27 @@ describe("kinNotificationRoute", () => { "/kin", ], ["JSON-encoded data", JSON.stringify(deferral), chatLink], - // Each lead's DM and each group is its own chat id, so each push opens its own chat. - ...(["7ae13b6f-1a49-4bb5-ac5c-6ac6b4300978", "c1f0e2d4-group"] as const).map( - (chatId) => - [ - `the chat ${chatId}`, - { - kin: 1, - orgId: "kin-default", - chatId, - deepLink: `/kin/env-1/kin-default/chats/${chatId}`, - }, - `/kin/env-1/kin-default/chats/${chatId}`, - ] as const, - ), + // Each lead's DM and each group is its own chat, so each push opens its own chat. + [ + "a lead's DM", + { + kin: 1, + orgId: "kin-default", + chatId: "7ae13b6f-1a49-4bb5-ac5c-6ac6b4300978", + deepLink: "/kin/env-1/kin-default/chats/7ae13b6f-1a49-4bb5-ac5c-6ac6b4300978", + }, + "/kin/env-1/kin-default/chats/7ae13b6f-1a49-4bb5-ac5c-6ac6b4300978", + ], + [ + "a group", + { + kin: 1, + orgId: "kin-default", + chatId: "c1f0e2d4-group", + deepLink: "/kin/env-1/kin-default/chats/c1f0e2d4-group", + }, + "/kin/env-1/kin-default/chats/c1f0e2d4-group", + ], ])("routes %s", (_name, data, path) => { const route = kinNotificationRoute(response({ data })); expect(route?.path).toBe(path); From 8a9eec26eb5755831b87647b43a70a5f3d40230e Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Tue, 10 Nov 2026 15:08:40 +0530 Subject: [PATCH 4/4] test(kin): type the push alert helper Co-Authored-By: Claude Opus 5.5 --- apps/server/src/kin/push/KinPushSender.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/server/src/kin/push/KinPushSender.test.ts b/apps/server/src/kin/push/KinPushSender.test.ts index ac7518e581f3..96d205458797 100644 --- a/apps/server/src/kin/push/KinPushSender.test.ts +++ b/apps/server/src/kin/push/KinPushSender.test.ts @@ -238,7 +238,9 @@ const postWidget = ( }); const alerts = (sent: ReadonlyArray) => - sent.map((push) => (push.payload as { aps: { alert?: object } }).aps.alert); + sent.map( + (push) => (push.payload as { aps: { alert?: { title: string; body: string } } }).aps.alert, + ); const categories = (sent: ReadonlyArray) => sent.map((push) => (push.payload as { aps: { category: string } }).aps.category);