diff --git a/apps/mobile/src/features/chats/KinRulesScreen.tsx b/apps/mobile/src/features/chats/KinRulesScreen.tsx index f8e29c31bee6a..7acd2ef7454d6 100644 --- a/apps/mobile/src/features/chats/KinRulesScreen.tsx +++ b/apps/mobile/src/features/chats/KinRulesScreen.tsx @@ -18,8 +18,8 @@ import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { AsyncResult, Atom } from "effect/reactivity"; import * as Clipboard from "expo-clipboard"; -import { useState } from "react"; -import { View } from "react-native"; +import { useEffect, useState } from "react"; +import { AccessibilityInfo, Platform, View } from "react-native"; import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator"; import { AppText as Text } from "../../components/ui/AppText"; @@ -28,6 +28,8 @@ import * as Dialog from "../../components/ui/Dialog"; import { EmptyState } from "../../components/ui/EmptyState"; import { ListSection } from "../../components/ui/ListSection"; import { Notice } from "../../components/ui/Notice"; +import { useNowMinuteMs } from "../../lib/clock"; +import { cn } from "../../lib/cn"; import { appAtomRegistry } from "../../state/atom-registry"; import { useAtomCommand } from "../../state/use-atom-command"; import { SettingsRow } from "../settings/components/SettingsRow"; @@ -38,7 +40,7 @@ import { useKinAskBeforeDiscard, } from "./components/KinWorkPieces"; import { kinClient } from "./state/kinClient"; -import { useKinGate } from "./state/useKinHost"; +import { useKinGate, useKinHostAt } from "./state/useKinHost"; export type KinRulesParams = { readonly environmentId: string; readonly orgId: string }; @@ -108,7 +110,15 @@ function KinRulesBody({ environmentId, orgId }: KinRulesTarget) { ); // What was last read stays up while it is read again, and the draft stays over it. const read = kinRulesRead(result); - const view = read === null ? null : kinRulesView(read, edits); + // The minute clock moves "Kin checked … ago" on while the screen sits, one render a minute. + const now = new Date(useNowMinuteMs()); + const host = useKinHostAt(environmentId); + // The name the host signs the owner's own changes with; a host too old to say keeps the name. + const myName = + host._tag === "host" && host.probe._tag === "ready" + ? (host.probe.orgs.me.find((entry) => entry.orgId === orgId)?.displayName ?? null) + : null; + const view = read === null ? null : kinRulesView(read, edits, { now, me: myName }); // Kept while saving too: a save that fails or finds the rules changed leaves the draft here. const guarded = view !== null && view.dirty; useKinAskBeforeDiscard(guarded); @@ -204,10 +214,14 @@ function KinRulesBody({ environmentId, orgId }: KinRulesTarget) { placeholder={KIN_RULES_COPY.placeholder} multiline disabled={view.saving} - hint={view.tooLarge ?? view.status ?? undefined} onChangeText={(text) => editor.type(view.held, text)} /> + {view.tooLarge !== null ? ( + + ) : view.status === null ? null : ( + + )} {view.facts.length === 0 ? null : ( {view.facts.join("\n")} @@ -219,6 +233,32 @@ function KinRulesBody({ environmentId, orgId }: KinRulesTarget) { ); } +/** + * What the editor's last change or save came to, said aloud as it appears: TalkBack hears the live + * region, VoiceOver the announcement. Keyed by what it says, so a too-large line that only moves + * by a few bytes while typing is not read again on every key. + */ +function KinRulesSaid(props: { readonly message: string; readonly danger?: boolean }) { + const [said] = useState(props.message); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- announces the line to VoiceOver through AccessibilityInfo when it appears + useEffect(() => { + if (Platform.OS === "ios") AccessibilityInfo.announceForAccessibility(said); + }, [said]); + return ( + + {props.message} + + ); +} + function KinRulesLoadFailed(props: { readonly result: AsyncResult.Failure; readonly onRetry: () => void; diff --git a/apps/web/src/components/AppRouteModal.tsx b/apps/web/src/components/AppRouteModal.tsx index 20507e557a2dc..f95bada1caf2f 100644 --- a/apps/web/src/components/AppRouteModal.tsx +++ b/apps/web/src/components/AppRouteModal.tsx @@ -4,6 +4,7 @@ import { XIcon } from "lucide-react"; import { useRef, useState, type CSSProperties, type ReactNode } from "react"; import { getCommandPaletteOpener } from "../commandPaletteStore"; +import { useKinModalCloseGuardHost } from "../kin/KinRouteModalGuard"; import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay"; import { requestWorkspaceFocus } from "../lib/workspaceFocus"; import { useCloseAppModal } from "./sidebar/mainAppLocation"; @@ -35,6 +36,7 @@ export function AppRouteModal({ // On close, return focus to the opener only after a keyboard close; after a pointer close it // would paint a focus ring. const popupRef = useRef(null); + const kinGuard = useKinModalCloseGuardHost(popupRef, setOpen); const [opener] = useState( () => getCommandPaletteOpener() ?? @@ -62,6 +64,7 @@ export function AppRouteModal({ ) { return eventDetails.cancel(); } + if (kinGuard.holds(eventDetails)) return; // Closing unmounts a focused field without a blur, so commit-on-blur rows would // drop what was typed. Blur first so they commit. const focused = document.activeElement; @@ -89,7 +92,7 @@ export function AppRouteModal({ backdropPressRef.current = event.target === event.currentTarget; }} onClick={(event) => { - if (backdropPressRef.current && event.target === event.currentTarget) setOpen(false); + if (backdropPressRef.current && event.target === event.currentTarget) kinGuard.close(); backdropPressRef.current = false; }} > @@ -116,7 +119,7 @@ export function AppRouteModal({ aria-hidden className="absolute inset-x-0 top-0 hidden h-(--app-modal-titlebar-height) [-webkit-app-region:drag] max-sm:block" /> - {children} + {kinGuard.provide(children)} diff --git a/apps/web/src/kin/KinCheckIns.tsx b/apps/web/src/kin/KinCheckIns.tsx index 4abee064fa602..7c7343063a9eb 100644 --- a/apps/web/src/kin/KinCheckIns.tsx +++ b/apps/web/src/kin/KinCheckIns.tsx @@ -32,7 +32,6 @@ import { Textarea } from "../components/ui/textarea"; import { Toggle, ToggleGroup } from "../components/ui/toggle-group"; import { useAtomCommand } from "../state/use-atom-command"; import { KinConfirm } from "./KinConfirm"; -import { kinNewLeadTarget } from "./KinNewLeadButton"; import { kinClient, refreshKinBriefs } from "./kinClient"; import { KinSettingsField, @@ -48,16 +47,10 @@ import { KinSettingsSection, KinSettingsStatus, } from "./settings/KinSettingsLayout"; -import { useKinHost } from "./useKinHost"; import type { KinWorkTarget } from "./useKinWork"; -/** Settings → Check-ins, for the owner or a co-owner; nothing shows where there is no Kin. */ -export function KinCheckInsPage() { - const target = kinNewLeadTarget(useKinHost()); - return target === null ? null : ; -} - -function CheckIns(props: KinWorkTarget) { +/** Settings → Check-ins, for the owner or a co-owner. */ +export function KinCheckInsPage(props: KinWorkTarget) { const searchableSetting = useSearchableSetting(); const query = { environmentId: props.environmentId, input: { orgId: props.orgId } }; const result = useAtomValue(kinClient.checkIns(query)); diff --git a/apps/web/src/kin/KinFormDiscard.tsx b/apps/web/src/kin/KinFormDiscard.tsx index 05b15faf1ae03..c2f0c9283ad32 100644 --- a/apps/web/src/kin/KinFormDiscard.tsx +++ b/apps/web/src/kin/KinFormDiscard.tsx @@ -1,5 +1,6 @@ import { KIN_FORM_DISCARD } from "@t3tools/client-runtime/kin/kinWorkForms"; -import { useState } from "react"; +import { useBlocker } from "@tanstack/react-router"; +import { useRef, useState } from "react"; import { AlertDialog, @@ -10,6 +11,7 @@ import { AlertDialogTitle, } from "../components/ui/alert-dialog"; import { Button } from "../components/ui/button"; +import { useKinModalCloseGuard } from "./KinRouteModalGuard"; /** * Closing a form that holds unsaved typing asks "Discard what you typed?" first; an untouched @@ -47,3 +49,53 @@ export function useKinFormDiscard(typed: boolean, onClose: () => void) { ); return { close, ask }; } + +/** + * A page that holds unsaved typing asks "Discard what you typed?" (Keep editing / Discard) before + * any way out: another route or Settings page, browser Back, reload or tab close, and closing the + * modal it sits in (Esc, the close button, a backdrop press). Render `ask` in the page. + */ +export function useKinLeaveGuard(typed: boolean) { + // Set once the person chose Discard, so the route's blocker lets the same leave through. + const released = useRef(false); + const [closing, setClosing] = useState<((leave: boolean) => void) | null>(null); + const blocker = useBlocker({ + shouldBlockFn: () => typed && !released.current, + enableBeforeUnload: () => typed && !released.current, + withResolver: true, + }); + const [askBeforeClose] = useState( + () => () => new Promise((resolve) => setClosing(() => resolve)), + ); + useKinModalCloseGuard(typed ? askBeforeClose : null); + const answer = (leave: boolean) => { + if (leave) released.current = true; + closing?.(leave); + setClosing(null); + if (leave) blocker.proceed?.(); + else blocker.reset?.(); + }; + const ask = ( + { + if (!open) answer(false); + }} + > + + + {KIN_FORM_DISCARD.title} + + + }> + {KIN_FORM_DISCARD.keep} + + + + + + ); + return ask; +} diff --git a/apps/web/src/kin/KinRouteModalGuard.tsx b/apps/web/src/kin/KinRouteModalGuard.tsx new file mode 100644 index 0000000000000..c0ed6423cc8eb --- /dev/null +++ b/apps/web/src/kin/KinRouteModalGuard.tsx @@ -0,0 +1,68 @@ +import { + createContext, + use, + useEffect, + useRef, + useState, + type ReactNode, + type RefObject, +} from "react"; + +/** Answers whether the modal may close now: false keeps it open, as it was. */ +type KinCloseGuard = () => boolean | Promise; +const KinCloseGuardContext = createContext<((guard: KinCloseGuard | null) => void) | null>(null); + +/** + * For a page inside T3's route modal (Settings): veto its close (Esc, the close button, a backdrop + * press) while it holds unsaved work. The route's own blocker answers too late: the popup is gone. + */ +export function useKinModalCloseGuard(guard: KinCloseGuard | null) { + const register = use(KinCloseGuardContext); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this page's guard with the modal that owns the close, and takes it back on unmount + useEffect(() => { + if (register === null || guard === null) return; + register(guard); + return () => register(null); + }, [register, guard]); +} + +/** + * The route modal's side, its hook into Kin: with no page guarding, every close goes on exactly as + * the modal does it; with one, the close waits for the page's answer. + */ +export function useKinModalCloseGuardHost( + popupRef: RefObject, + setOpen: (open: boolean) => void, +) { + const guardRef = useRef(null); + const [register] = useState(() => (guard: KinCloseGuard | null) => { + guardRef.current = guard; + }); + const ask = (guard: KinCloseGuard) => + void Promise.resolve(guard()).then((may) => { + if (!may) return; + // As the modal's own close: blur first, so commit-on-blur rows keep what was typed. + const focused = document.activeElement; + if (focused instanceof HTMLElement && popupRef.current?.contains(focused)) focused.blur(); + setOpen(false); + }); + return { + /** Esc or the close button: true when a page guards, after cancelling this close to ask. */ + holds: (details: { readonly cancel: () => void }) => { + const guard = guardRef.current; + if (guard === null) return false; + details.cancel(); + ask(guard); + return true; + }, + /** A backdrop press: asks first when a page guards, otherwise closes. */ + close: () => { + const guard = guardRef.current; + if (guard === null) setOpen(false); + else ask(guard); + }, + provide: (children: ReactNode) => ( + {children} + ), + }; +} diff --git a/apps/web/src/kin/KinSettingsOffline.browser.test.tsx b/apps/web/src/kin/KinSettingsOffline.browser.test.tsx new file mode 100644 index 0000000000000..37ce07c892962 --- /dev/null +++ b/apps/web/src/kin/KinSettingsOffline.browser.test.tsx @@ -0,0 +1,81 @@ +import { describe, expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +vi.mock("../components/chat/GlobalVoiceInputIndicator", () => ({ + GlobalVoiceInputIndicator: () => null, +})); + +// The company's host after its connection dropped: its last answer is still known. +vi.mock(import("./useKinHost"), async (importOriginal) => ({ + ...(await importOriginal()), + useKinHost: () => + ({ + _tag: "host", + environmentId: "env-1", + connected: false, + probe: { _tag: "ready", orgs: { me: [{ orgId: "org-1", personId: "p-owner" }] } }, + }) as never, +})); + +vi.mock(import("./useKinOwnerLevel"), async (importOriginal) => ({ + ...(await importOriginal()), + useKinOwnerLevel: () => true, + useKinPlaceReach: () => null, + useKinSeesClients: () => true, +})); + +vi.mock(import("./useKinShell"), async (importOriginal) => ({ + ...(await importOriginal()), + useKinSectionOn: () => true, +})); + +vi.mock(import("./kinClient"), async (importOriginal) => { + const real = await importOriginal(); + const { Atom: A } = await import("effect/reactivity"); + const allowed = A.make(true); + const granted = (command: C) => ({ ...command, permissionAtom: () => allowed }); + return { + ...real, + kinClient: { + ...real.kinClient, + recommendationAskAgain: granted(real.kinClient.recommendationAskAgain), + memorySaveRules: granted(real.kinClient.memorySaveRules), + }, + }; +}); + +// The page itself has its own tests; here it is only what the owner is typing into. +vi.mock("./settings/KinRulesPage", () => ({ + KinRulesPage: () =>