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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/mobile/src/components/ui/AppSymbol.android.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -168,7 +170,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,
Expand Down
52 changes: 51 additions & 1 deletion apps/mobile/src/features/chats/KinChatScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
type KinChatHistoryInput,
type KinChatHistoryResult,
type KinChatMember,
type KinChatSummary,
type KinMessage,
type KinReaction,
type KinReactionEmoji,
Expand Down Expand Up @@ -131,6 +132,7 @@ import {
} from "@t3tools/client-runtime/kin/kinInboxModel";
import { kinPresenceLine, kinPresenceNeedsClock } from "@t3tools/client-runtime/kin/kinLive";
import {
kinChatMuted,
kinChatTitle,
kinDirectAgentName,
kinAgentAvatar,
Expand All @@ -147,6 +149,7 @@ import {
kinSoftReplyMessageId,
kinViewerMemberId,
} from "@t3tools/client-runtime/kin/kinReactions";
import { KinBadgeSync } from "./notifications/KinBadgeSync";
import { KinChatPushWatch } from "./notifications/KinChatPushWatch";

type KinChatParams = {
Expand Down Expand Up @@ -198,6 +201,9 @@ const noChatAtom: Atom.Atom<ChatResult> = Atom.make<ChatResult>(null);
const noInboxAtom: Atom.Atom<InboxResult> = Atom.make<InboxResult>(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: {
Expand Down Expand Up @@ -232,6 +238,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;
Expand All @@ -245,6 +254,10 @@ function KinLiveChat(props: {
return (
<>
<KinChatPushWatch environmentId={props.environmentId} chatId={props.chatId} />
{/* Only a live inbox: a saved one would put an old count back on the icon. */}
<KinBadgeSync
inbox={inbox?._tag === "Success" && inbox.value.live ? inbox.value.value : null}
/>
Comment on lines +258 to +260

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Update the badge when notifications arrive outside a chat

On iOS, if the app is opened to the chat list without mounting a chat screen, incoming Kin pushes do not update the icon badge: the app-wide foregroundNotificationBehavior explicitly returns shouldSetBadge: false, and the only KinBadgeSync instance is mounted here inside KinLiveChat. The inbox can therefore receive new unread messages while the OS badge retains its previous count, including after the user backgrounds the app. Synchronize the badge from an app-level live inbox, or permit Kin notification badges in the foreground handler, rather than requiring a chat screen to have been opened.

Useful? React with 👍 / 👎.

<KinChatPage
environmentId={props.environmentId}
orgId={props.orgId}
Expand All @@ -267,6 +280,16 @@ function KinLiveChat(props: {
: { environmentId: props.environmentId, orgId: props.orgId, agentId: levelsAgentId }
}
unread={summary?.unread ?? null}
mute={
environmentId === null || chatId === null || summary === undefined || !canMute
? null
: {
muted,
toggle: () => {
void runMute({ environmentId, input: { chatId, muted: !muted } });
},
}
}
stopLead={
environmentId === null || summary === undefined || ownedAgentId === null || !canInterrupt
? null
Expand Down Expand Up @@ -399,6 +422,7 @@ function KinChatAppBar(props: {
readonly tasks: string | null;
readonly onBack: () => void;
readonly actions: ComponentPropsWithRef<typeof AppBar>["actions"];
readonly menus: ComponentPropsWithRef<typeof AppBar>["menus"];
}) {
const pill = Platform.OS === "ios";
const now = useKinPresenceNow(!pill && kinPresenceNeedsClock(props.presence));
Expand All @@ -411,7 +435,13 @@ function KinChatAppBar(props: {
);
return (
<>
<AppBar title={title} subtitle={subtitle} onBack={props.onBack} actions={props.actions} />
<AppBar
title={title}
subtitle={subtitle}
onBack={props.onBack}
actions={props.actions}
menus={props.menus}
/>
{/* Always set, so going back to the default size resets the bar. */}
<NativeStackScreenOptions
optionsVersion={[title, avatar.seed, avatar.kind, status, tasks]}
Expand Down Expand Up @@ -466,6 +496,8 @@ function KinChatPage(props: {
readonly markRead: MarkRead | null;
/** Interrupts the lead's current wake-up; null unless the viewer owns it and may stop it. */
readonly stopLead?: StopLead | null;
/** The viewer's mute for this chat's notifications; null until it can be set. */
readonly mute?: { readonly muted: boolean; readonly toggle: () => void } | null;
readonly state: KinChatScreenState;
readonly viewer: KinFeedViewer;
readonly onRetry: () => void;
Expand Down Expand Up @@ -497,6 +529,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
Expand Down
8 changes: 8 additions & 0 deletions apps/mobile/src/features/chats/components/KinChatRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ export function KinChatRow(props: {
>
{view.title}
</Text>
{view.muted ? (
<SymbolView
name="bell.slash"
size={13}
tintColorClassName="accent-icon-muted"
type="monochrome"
/>
) : null}
{view.sentAt === null ? null : (
<Text textRole="caption" className="text-foreground-muted">
<RelativeTime timestamp={view.sentAt} />
Expand Down
20 changes: 20 additions & 0 deletions apps/mobile/src/features/chats/notifications/KinBadgeSync.tsx
Original file line number Diff line number Diff line change
@@ -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;
}
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,27 @@ describe("kinNotificationRoute", () => {
"/kin",
],
["JSON-encoded data", JSON.stringify(deferral), chatLink],
// 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);
Expand Down
6 changes: 6 additions & 0 deletions apps/mobile/src/features/chats/state/kinClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/kin/chat/KinChatHub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
12 changes: 12 additions & 0 deletions apps/server/src/kin/chat/KinChatRepository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,10 @@ export class KinChatRepository extends Context.Service<
input: KinAgent & { readonly createdAt: IsoDateTime },
) => Effect.Effect<void, RepositoryError>;
readonly addMember: (input: KinChatMember) => Effect.Effect<KinChatMember, RepositoryError>;
/** 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<Option.Option<KinChatMember>, RepositoryError>;
readonly leaveChat: (
input: MemberScope & { readonly leftAt: IsoDateTime },
) => Effect.Effect<ReadonlyArray<KinWaitingItem>, RepositoryError>;
Expand Down Expand Up @@ -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(
Expand Down
28 changes: 28 additions & 0 deletions apps/server/src/kin/chat/KinChatService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down
22 changes: 22 additions & 0 deletions apps/server/src/kin/chat/KinChatService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
type KinChatsCreateDirectInput,
type KinMessage,
type KinMessagesMarkReadInput,
type KinChatsMuteInput,
type KinPersonId,
type KinOrgId,
type KinReaction,
Expand Down Expand Up @@ -121,6 +122,10 @@ export class KinChatService extends Context.Service<
identities: ReadonlyArray<PersonIdentity>,
input: KinChatsSubscribeInput,
) => Stream.Stream<KinChatListEvent, ServiceError>;
readonly mute: (
identity: PersonCaller,
input: KinChatsMuteInput,
) => Effect.Effect<KinChatMember, ServiceError>;
readonly leaveChat: (
identity: PersonIdentity,
input: { readonly chatId: KinChatId; readonly memberId: KinMemberId },
Expand Down Expand Up @@ -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" &&
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -896,6 +917,7 @@ const make = Effect.gen(function* () {
});
}
case "member.removed":
case "member.updated":
return event.member.chatId === input.chatId
? Option.some<KinChatStreamEvent>({ _tag: "member", member: event.member })
: Option.none();
Expand Down
7 changes: 7 additions & 0 deletions apps/server/src/kin/chat/rpcHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down
6 changes: 5 additions & 1 deletion apps/server/src/kin/lead/ChatWake.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
]);
});
});
Loading