From 7a1fecc031821ea9b156ed36c4fd03cb0dafedb5 Mon Sep 17 00:00:00 2001 From: GLDRoger <130458023+GLDRoger@users.noreply.github.com> Date: Mon, 30 Nov 2026 02:16:58 +0530 Subject: [PATCH 1/2] fix(kin): standing-rules drafts survive Settings' close, Escape and a dropped host MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On web, closing Settings with the X, or Escape then Cancel, closed it without asking and lost the owner's unsaved rules, and any blip in the host connection unmounted Settings and lost them too. - Settings' modal takes an optional close guard from the page inside it. The rules page registers one while it holds a draft, so the X, Escape and a backdrop press ask "Discard what you typed?" (Keep editing / Discard); Keep editing leaves Settings open with the draft and the caret. Page switches, links and Back ask the same question with the same words. - Settings stays mounted for the same company while its host is offline. Check-ins, Sections and Deals now take Settings' company instead of a connected-only lookup, so they no longer go blank offline. - "Kin checked … ago" and "Changed … by …" move on with the minute clock, the owner's own change reads "by you", and withdrawing every rule says the agents follow no standing rules. - Save stays in view at the foot of Settings however tall the page. - Phone: the status, the too-large line (now styled as an error) are said aloud when they appear. People-change: none Co-Authored-By: Claude Opus 5.5 --- .../src/features/chats/KinRulesScreen.tsx | 50 ++++++- apps/web/src/components/AppRouteModal.tsx | 61 ++++++-- apps/web/src/kin/KinCheckIns.tsx | 11 +- apps/web/src/kin/KinFormDiscard.tsx | 54 +++++++- .../kin/KinSettingsOffline.browser.test.tsx | 81 +++++++++++ apps/web/src/kin/KinSettingsView.tsx | 16 ++- apps/web/src/kin/settings/KinDealsPage.tsx | 7 +- .../settings/KinRulesPage.browser.test.tsx | 131 ++++++++++++++++++ apps/web/src/kin/settings/KinRulesPage.tsx | 28 ++-- apps/web/src/kin/settings/KinSectionsPage.tsx | 11 +- .../client-runtime/src/kin/kinRules.test.ts | 18 ++- packages/client-runtime/src/kin/kinRules.ts | 43 ++++-- 12 files changed, 447 insertions(+), 64 deletions(-) create mode 100644 apps/web/src/kin/KinSettingsOffline.browser.test.tsx diff --git a/apps/mobile/src/features/chats/KinRulesScreen.tsx b/apps/mobile/src/features/chats/KinRulesScreen.tsx index f8e29c31bee6..7acd2ef7454d 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 20507e557a2d..e89940d3a62e 100644 --- a/apps/web/src/components/AppRouteModal.tsx +++ b/apps/web/src/components/AppRouteModal.tsx @@ -1,7 +1,15 @@ import { Dialog as DialogPrimitive } from "@base-ui/react/dialog"; import { T, useGT } from "gt-react"; import { XIcon } from "lucide-react"; -import { useRef, useState, type CSSProperties, type ReactNode } from "react"; +import { + createContext, + use, + useEffect, + useRef, + useState, + type CSSProperties, + type ReactNode, +} from "react"; import { getCommandPaletteOpener } from "../commandPaletteStore"; import { useNativeTitlebarHeight } from "../lib/windowControlsOverlay"; @@ -12,6 +20,26 @@ import { Button } from "./ui/button"; import { DialogBackdrop } from "./ui/dialog"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; +/** Answers whether the modal may close now: false keeps it open, as it was. */ +type AppRouteModalCloseGuard = () => boolean | Promise; +const AppRouteModalGuard = createContext<((guard: AppRouteModalCloseGuard | null) => void) | null>( + null, +); + +/** + * Lets a page inside the modal 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 by then. + */ +export function useAppRouteModalCloseGuard(guard: AppRouteModalCloseGuard | null) { + const register = use(AppRouteModalGuard); + // 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]); +} + /** * Large modal for the Settings and Usage routes. Esc, the close button, or a press on the * backdrop returns to the page that opened it. Keyboard guards that skip dialogs exempt @@ -29,6 +57,25 @@ export function AppRouteModal({ }) { const closeAppModal = useCloseAppModal(); const [open, setOpen] = useState(true); + // A page's veto on closing; none by default, so the modal closes as it always has. + const guardRef = useRef(null); + const [registerGuard] = useState(() => (guard: AppRouteModalCloseGuard | null) => { + guardRef.current = guard; + }); + const close = () => { + const guard = guardRef.current; + if (guard === null) return closeNow(); + void Promise.resolve(guard()).then((may) => { + if (may) closeNow(); + }); + }; + const closeNow = () => { + // 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; + if (focused instanceof HTMLElement && popupRef.current?.contains(focused)) focused.blur(); + setOpen(false); + }; // Text selection that ends on the backdrop is not a dismissal. const backdropPressRef = useRef(false); // Focus the surface, not its first control: no stray focus ring, no phone keyboard. @@ -62,11 +109,9 @@ export function AppRouteModal({ ) { return eventDetails.cancel(); } - // 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; - if (focused instanceof HTMLElement && popupRef.current?.contains(focused)) focused.blur(); - setOpen(false); + if (guardRef.current === null) return closeNow(); + eventDetails.cancel(); + close(); }} onOpenChangeComplete={(nextOpen) => { if (!nextOpen) void (onClose ?? closeAppModal)(); @@ -89,7 +134,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) close(); backdropPressRef.current = false; }} > @@ -116,7 +161,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} + {children} diff --git a/apps/web/src/kin/KinCheckIns.tsx b/apps/web/src/kin/KinCheckIns.tsx index 4abee064fa60..7c7343063a9e 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 05b15faf1ae0..756a8d8651ac 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, @@ -9,6 +10,7 @@ import { AlertDialogPopup, AlertDialogTitle, } from "../components/ui/alert-dialog"; +import { useAppRouteModalCloseGuard } from "../components/AppRouteModal"; import { Button } from "../components/ui/button"; /** @@ -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)), + ); + useAppRouteModalCloseGuard(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/KinSettingsOffline.browser.test.tsx b/apps/web/src/kin/KinSettingsOffline.browser.test.tsx new file mode 100644 index 000000000000..37ce07c89296 --- /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: () =>