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
301 changes: 301 additions & 0 deletions apps/mobile/src/features/chats/KinRulesScreen.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,301 @@
import { useAtomValue } from "@effect/atom-react";
import { useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { KIN_RETRY } from "@t3tools/client-runtime/kin/kinAnswers";
import { KIN_THIS_PHONE_COPY } from "@t3tools/client-runtime/kin/kinDevice";
import {
KIN_RULES_COPY,
KIN_RULES_NO_EDITS,
createKinRulesEditor,
kinRulesProblem,
kinRulesRead,
kinRulesView,
type KinRulesView,
} from "@t3tools/client-runtime/kin/kinRules";
import { KIN_FORM_DISCARD } from "@t3tools/client-runtime/kin/kinWorkForms";
import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { EnvironmentId, KinOrgId, type KinMemoryRules } from "@t3tools/contracts";
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 { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
import { AppText as Text } from "../../components/ui/AppText";
import { Button } from "../../components/ui/Button";
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 { appAtomRegistry } from "../../state/atom-registry";
import { useAtomCommand } from "../../state/use-atom-command";
import { SettingsRow } from "../settings/components/SettingsRow";
import {
KinGateView,
KinWorkFrame,
KinWorkTextField,
useKinAskBeforeDiscard,
} from "./components/KinWorkPieces";
import { kinClient } from "./state/kinClient";
import { useKinGate } from "./state/useKinHost";

export type KinRulesParams = { readonly environmentId: string; readonly orgId: string };

interface KinRulesTarget {
readonly environmentId: EnvironmentId;
readonly orgId: KinOrgId;
}

const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId);
const decodeOrgId = Schema.decodeUnknownOption(KinOrgId);

type RulesResult = AsyncResult.AsyncResult<KinMemoryRules, unknown>;
// Read only by the owner's session; anyone else asks the host nothing.
const noRulesAtom: Atom.Atom<RulesResult> = Atom.make(AsyncResult.initial());

/** Settings' way in, for the owner alone: absent for everyone else. */
export function KinRulesSettingsRow(props: KinRulesTarget) {
const navigation = useNavigation();
const allowed = useAtomValue(kinClient.memorySaveRules.permissionAtom(props.environmentId));
if (!allowed) return null;
return (
<SettingsRow
labelWholeWords
icon="list.bullet"
label={KIN_RULES_COPY.title}
onPress={() => navigation.navigate("KinRules", props)}
/>
);
}

/** The standing rules every agent follows: the owner's alone, to read and to change. */
export function KinRulesScreen({ route }: StaticScreenProps<KinRulesParams>) {
const navigation = useNavigation();
const environmentId = Option.getOrNull(decodeEnvironmentId(route.params.environmentId));
const orgId = Option.getOrNull(decodeOrgId(route.params.orgId));
if (environmentId === null || orgId === null)
return (
<KinWorkFrame title={KIN_RULES_COPY.title} onBack={() => navigation.goBack()}>
<EmptyState
variant="plain"
title="This link doesn't open anything"
detail="Open Standing rules from Settings."
/>
</KinWorkFrame>
);
return <KinRulesBody environmentId={environmentId} orgId={orgId} />;
}

function KinRulesBody({ environmentId, orgId }: KinRulesTarget) {
const navigation = useNavigation();
const gate = useKinGate(
kinClient.memorySaveRules.permissionStateAtom(environmentId),
environmentId,
);
const rulesAtom = kinClient.memoryRules({ environmentId, input: { orgId } });
const result = useAtomValue(gate === null ? rulesAtom : noRulesAtom);
const saveRules = useAtomCommand(kinClient.memorySaveRules, { reportFailure: false });
const [edits, setEdits] = useState(KIN_RULES_NO_EDITS);
const [editor] = useState(() =>
createKinRulesEditor({
orgId,
device: "phone",
save: (input) => saveRules({ environmentId, input }),
update: setEdits,
refresh: () => appAtomRegistry.refresh(rulesAtom),
}),
);
// 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);
// 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);

const save = async (confirmed = false) => {
if (read === null || view === null) return;
const ask = view.ask;
if ((await editor.save(read, edits, confirmed)) !== "ask" || ask === null) return;
Dialog.alert(ask.title, ask.detail, [
{ text: KIN_FORM_DISCARD.keep, style: "cancel" },
{
text: ask.action,
style: "destructive",
onPress: () => void save(true),
},
]);
};

return (
<KinWorkFrame
title={KIN_RULES_COPY.title}
form
guardBack={guarded}
showTop={
view?.problem?.text ??
view?.replacing?.detail ??
(view?.changed === null ? null : KIN_RULES_COPY.stale.title)
}
onBack={() => navigation.goBack()}
{...(view === null
? {}
: {
confirm: {
label: view.saving ? KIN_RULES_COPY.saving : view.saveLabel,
onPress: () => void save(),
loading: view.saving,
disabled: !view.canSave,
},
})}
>
{gate !== null ? (
<KinGateView
gate={gate}
refused={{ title: KIN_RULES_COPY.ownerOnly, detail: KIN_RULES_COPY.ownerOnlyDetail }}
label={KIN_RULES_COPY.title}
/>
) : read === null || view === null ? (
AsyncResult.isFailure(result) ? (
<KinRulesLoadFailed result={result} onRetry={() => appAtomRegistry.refresh(rulesAtom)} />
) : (
<View
className="items-center py-12"
accessible
accessibilityRole="progressbar"
accessibilityLabel={KIN_RULES_COPY.loading}
>
<AppActivityIndicator />
</View>
)
) : (
<>
<Text textRole="footnote" className="px-2 text-foreground-muted">
{view.empty ? KIN_RULES_COPY.empty : KIN_RULES_COPY.purpose}
</Text>
{view.replacing === null ? null : (
<Notice message={`${view.replacing.title}. ${view.replacing.detail}`} />
)}
{view.problem === null ? null : (
<Notice
message={view.problem.text}
tone="danger"
onDismiss={editor.dismissProblem}
{...(view.problem.kind === "pair_again"
? {
action: {
label: KIN_THIS_PHONE_COPY.title,
onPress: () => navigation.navigate("KinThisPhone"),
},
}
: {})}
/>
)}
{view.changed === null ? null : (
<KinRulesCurrent
changed={view.changed}
onTakeCurrent={() => editor.takeCurrent(read)}
/>
)}
<ListSection>
<KinWorkTextField
label={view.editorLabel}
value={view.text}
placeholder={KIN_RULES_COPY.placeholder}
multiline
disabled={view.saving}
hint={view.tooLarge ?? view.status ?? undefined}
onChangeText={(text) => editor.type(view.held, text)}
/>
</ListSection>
{view.facts.length === 0 ? null : (
<Text textRole="footnote" className="px-2 text-foreground-muted">
{view.facts.join("\n")}
</Text>
)}
</>
)}
</KinWorkFrame>
);
}

function KinRulesLoadFailed(props: {
readonly result: AsyncResult.Failure<KinMemoryRules, unknown>;
readonly onRetry: () => void;
}) {
const navigation = useNavigation();
const problem = kinRulesProblem(squashAtomCommandFailure(props.result), "", "phone");
return (
<EmptyState
variant="plain"
title={KIN_RULES_COPY.loadFailed}
detail={problem.text.trim()}
{...(problem.retry
? { action: <Button tone="secondary" label={KIN_RETRY} onPress={props.onRetry} /> }
: problem.kind === "pair_again"
? {
action: (
<Button
tone="secondary"
label={KIN_THIS_PHONE_COPY.title}
onPress={() => navigation.navigate("KinThisPhone")}
/>
),
}
: {})}
/>
);
}

/** After a save found the rules changed: the current rules, to copy from or take. */
function KinRulesCurrent(props: {
readonly changed: NonNullable<KinRulesView["changed"]>;
readonly onTakeCurrent: () => void;
}) {
const [copied, setCopied] = useState(false);
const empty = props.changed.text.trim() === "";
return (
<View className="gap-3">
<Notice
message={`${KIN_RULES_COPY.stale.title}. ${KIN_RULES_COPY.stale.detail(props.changed.who)}`}
/>
<ListSection>
<View className="gap-1 px-4 py-3">
<Text textRole="footnote" className="text-foreground-muted">
{KIN_RULES_COPY.stale.current}
</Text>
<Text selectable className="font-sans text-base text-foreground">
{empty ? KIN_RULES_COPY.stale.emptyCurrent : props.changed.text}
</Text>
</View>
</ListSection>
<View className="flex-row flex-wrap gap-2 px-2">
{empty ? null : (
<Button
tone="secondary"
size="compact"
label={copied ? KIN_RULES_COPY.stale.copied : KIN_RULES_COPY.stale.copy}
onPress={() =>
void Clipboard.setStringAsync(props.changed.text).then(() => setCopied(true))
}
/>
)}
<Button
tone="secondary"
size="compact"
label={KIN_RULES_COPY.stale.discard}
onPress={() =>
Dialog.alert(KIN_FORM_DISCARD.title, KIN_RULES_COPY.stale.discardDetail, [
{ text: KIN_FORM_DISCARD.keep, style: "cancel" },
{
text: KIN_FORM_DISCARD.discard,
style: "destructive",
onPress: props.onTakeCurrent,
},
])
}
/>
</View>
</View>
);
}
9 changes: 8 additions & 1 deletion apps/mobile/src/features/chats/KinSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ import { useSettingsPageBack } from "../settings/useSettingsPageBack";
import { useKinTab, kinTabFoot } from "./components/KinTab";
import { KinBriefsSection } from "./KinBriefs";
import { KinMailRulesSettingsRow } from "./connections/KinMailRules";
import { KinRulesSettingsRow } from "./KinRulesScreen";
import { KinChatsSettleRows } from "./KinChatsSettleRows";
import { kinClient } from "./state/kinClient";
import { KinQuietHoursRows } from "./KinQuietHoursRows";
import { useKinIsHome } from "./state/kinHome";
import { openKinNotificationSettings } from "./notifications/installKinNotifications";
Expand Down Expand Up @@ -115,7 +117,11 @@ export function KinSettings(props: {
host._tag === "host" && orgId !== null && ownerLevel
? { environmentId: host.environmentId, orgId }
: null;
const rows = kinPhoneSettingsRows({ ownerLevel: company !== null });
// The owner alone, as the host gates `kin.memory.saveRules`; a co-owner's Company has no row.
const rules = useAtomValue(
kinClient.memorySaveRules.permissionAtom(host._tag === "host" ? host.environmentId : null),
);
const rows = kinPhoneSettingsRows({ ownerLevel: company !== null, rules });
// What Kin checked is everyone's: a teammate's holds the watches on their own things.
const here =
host._tag === "host" && orgId !== null ? { environmentId: host.environmentId, orgId } : null;
Expand Down Expand Up @@ -240,6 +246,7 @@ export function KinSettings(props: {
<SettingsSection title="Company">
{rows.company.map((page) => {
if (page === "mailRules") return <KinMailRulesSettingsRow key={page} {...here} />;
if (page === "rules") return <KinRulesSettingsRow key={page} {...here} />;
const row = COMPANY_ROWS[page];
if (row === undefined) return null;
return (
Expand Down
7 changes: 7 additions & 0 deletions apps/mobile/src/features/chats/routes.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { KIN_WAITING_TITLE } from "@t3tools/client-runtime/kin/kinInboxModel";
import { KIN_RULES_COPY } from "@t3tools/client-runtime/kin/kinRules";
import { createNativeStackScreen } from "@react-navigation/native-stack";

import { pageRoute, sheetRoute } from "../layout/route-options";
Expand Down Expand Up @@ -43,6 +44,7 @@ import { KinEntryEditScreen } from "./KinListEntryEdit";
import { KinDatesScreen, KinListScreen } from "./KinListScreen";
import { KinLeadScreen } from "./KinLeadScreen";
import { KinMemoryScreen } from "./KinMemoryScreen";
import { KinRulesScreen } from "./KinRulesScreen";
import { KinRatesScreen } from "./KinMoneyEstimate";
import { KinSubscriptionsScreen } from "./KinSubscriptions";
import { KinMarketingListScreen } from "./KinMarketingListScreen";
Expand Down Expand Up @@ -109,6 +111,11 @@ export const KIN_SCREENS = {
linking: "kin/:environmentId/:orgId/memory",
options: pageRoute({ title: "Memory" }),
}),
KinRules: createNativeStackScreen({
screen: KinRulesScreen,
linking: "kin/:environmentId/:orgId/rules",
options: pageRoute({ title: KIN_RULES_COPY.title }),
}),
KinWork: createNativeStackScreen({
screen: KinWorkScreen,
linking: "kin/:environmentId/:orgId/work",
Expand Down
18 changes: 16 additions & 2 deletions apps/server/src/kin/featureMap/feature-map.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -461,6 +461,22 @@ features:
- apps/server/src/kin/memory/MemoryWriter.test.ts
- apps/server/src/kin/memory/MemoryChanges.test.ts

- id: standing-rules
name: Standing rules, the text every agent follows
tab: settings
web: [settings, section:Standing rules]
phone: [SettingsKin, KinRules]
roles: { owner: both, co_owner: none, lead: none, member: none }
note: >-
The owner's alone, from their own signed-in device; a co-owner sees neither the page nor its
way in. Also in the web command palette. A save names the revision the owner opened: when the
rules changed meanwhile the draft stays, the current rules show above it, and only the owner's
next Save replaces them. Emptying them asks first. Agents use saved rules from their next turn.
proof:
- packages/client-runtime/src/kin/kinRules.test.ts
- apps/web/src/kin/settings/KinRulesPage.browser.test.tsx
- apps/server/src/kin/memory/MemoryWriter.test.ts

# ── Tasks ──────────────────────────────────────────────────────────────────────────────────
- id: tasks
name: Tasks, with what needs you first
Expand Down Expand Up @@ -1912,8 +1928,6 @@ features:
unlisted:
"phone:KinBillsAdd": Where a photo or PDF shared into Kin lands; it opens the chat bills are added in at once.
"web:team": Old address; opens the Settings modal on Team.
"rpc:kin.memory.readRules": Owner-only rulebook reader; editor client ships separately.
"rpc:kin.memory.saveRules": Owner-only rulebook editor; editor client ships separately.
"web:memory": Old address; opens the Settings modal on Memory.
"web:settings/approvals": The app's old address; opens Kin's Settings β†’ Approvals.
"web:settings/company": The app's old address; opens Kin's Settings β†’ Company details.
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/kin/featureMap/featureMap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
readInventory,
} from "./featureMap.ts";

const PHONE_PROOF_GAP = 108;
const PHONE_PROOF_GAP = 109;

describe("Kin feature map", () => {
it("lists every route, pane, phone screen and agent tool, and every proof exists", () => {
Expand Down
Loading
Loading