diff --git a/apps/mobile/src/j5/inbox/InboxScreen.tsx b/apps/mobile/src/j5/inbox/InboxScreen.tsx
index 07f8dddd06152..9b3b7613db063 100644
--- a/apps/mobile/src/j5/inbox/InboxScreen.tsx
+++ b/apps/mobile/src/j5/inbox/InboxScreen.tsx
@@ -1,6 +1,7 @@
import { useAtomValue } from "@effect/atom-react";
import {
answeredByLine,
+ closedLine,
j5SourceNotice,
mergeHumanInboxSources,
type PresentedHumanInboxItem,
@@ -11,10 +12,12 @@ import type { EnvironmentId } from "@t3tools/contracts";
import { scopedInboxItemKey } from "@t3tools/contracts/j5";
import { useFocusEffect } from "@react-navigation/native";
import { useCallback, useState } from "react";
-import { Pressable, RefreshControl, View } from "react-native";
+import { Platform, Pressable, RefreshControl, View } from "react-native";
+import { KeyboardAwareScrollView } from "react-native-keyboard-controller";
import { SymbolView } from "../../components/ui/AppSymbol";
-import { AppText as Text } from "../../components/ui/AppText";
+import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
+import { Button } from "../../components/ui/Button";
import { EmptyState } from "../../components/ui/EmptyState";
import { ScreenScrollView } from "../../components/ui/ScreenScrollView";
import { useMarkdownPreviewStyles } from "../../features/files/FileMarkdownPreview";
@@ -23,6 +26,8 @@ import { relativeTime } from "../../lib/time";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { SelectableMarkdownText } from "../../native/SelectableMarkdownText";
import { j5Sharing } from "../sharing/guestAccess";
+import { j5Environment } from "../state";
+import { type ClosedItem, useInboxAnswers } from "./inboxAnswers";
import {
answeredInboxQueryAtom,
answeredInboxSourcesAtom,
@@ -61,7 +66,7 @@ function refreshAll() {
/**
* The person's Inbox: what agents on every connected server have asked them, most urgent first
- * (Inbox AC6), and the asks already answered. Read-only here; answering comes with the answer box.
+ * (Inbox AC6), answered in place, and the asks already answered.
*/
export function InboxScreen() {
const openSources = useAtomValue(openInboxSourcesAtom);
@@ -76,6 +81,7 @@ export function InboxScreen() {
connected: item.connected,
})),
);
+ const answers = useInboxAnswers({ openSources, items, answeredSources, answered });
// Reads again each time the Inbox comes into view; between visits the server's inbox signal
// rereads it. No timer.
useFocusEffect(useCallback(() => refreshAll(), []));
@@ -92,20 +98,15 @@ export function InboxScreen() {
}),
),
];
- return (
- }
- >
+ const content = (
+ <>
{notices.map((notice) => (
{notice}
))}
- {items.length === 0 ? (
+ {answers.shownItems.length === 0 ? (
loading ? (
Loading your inbox…
) : (
@@ -117,18 +118,56 @@ export function InboxScreen() {
)
) : (
- {items.map((item) => (
-
- ))}
+ {answers.shownItems.map((item) => {
+ const key = scopedInboxItemKey(item);
+ return (
+ answers.setAnswerText(item, text)}
+ onAnswer={() => void answers.answer(item)}
+ delivering={answers.pendingKey === key}
+ error={answers.errorFor(item)}
+ anyDelivering={answers.pendingKey !== null}
+ />
+ );
+ })}
)}
+ >
+ );
+ const refreshControl = ;
+ // iOS keeps upstream's scroll view, which registers with the native header, and lets it move the
+ // focused answer box above the keyboard, as upstream's commit sheet does. Android has no header
+ // marker, so keyboard-controller's scroll view brings the box being typed in clear of the keyboard.
+ return Platform.OS === "ios" ? (
+
+ {content}
+ ) : (
+
+ {content}
+
);
}
@@ -159,10 +198,25 @@ function InboxItem(props: {
readonly item: PresentedHumanInboxItem;
readonly labels: SenderLabels;
readonly showEnvironment: boolean;
+ /** The item closed while the person had typed into it, and stays with their words (AC17). */
+ readonly closed: ClosedItem | undefined;
+ readonly answerText: string;
+ readonly onChangeAnswer: (text: string) => void;
+ readonly onAnswer: () => void;
+ readonly delivering: boolean;
+ readonly anyDelivering: boolean;
+ /** Why this ask's last answer was not delivered, or a stale list after it was. */
+ readonly error: string | null;
}) {
const { item } = props;
const [expanded, setExpanded] = useState(false);
const urgency = URGENCY[item.urgency];
+ const ownName = useOwnName(item.environmentId);
+ const mayAnswer = useAtomValue(
+ j5Environment.answerHumanExchange.permissionAtom(item.environmentId),
+ );
+ const canAnswer = item.sourceReady && mayAnswer;
+ const closedText = props.closed === undefined ? null : closedLine({ ...props.closed, ownName });
return (
{expanded ? (
-
+ {/* Above the answer box, so it stays in view whenever the box is: iOS scrolls only the
+ focused box itself clear of the keyboard. */}
+
+
+ {closedText !== null ? (
+ {closedText}
+ ) : (
+
+ )}
+
+
+ {props.error === null ? null : (
+
+ {props.error}
+
+ )}
) : null}
diff --git a/apps/mobile/src/j5/inbox/inboxAnswers.ts b/apps/mobile/src/j5/inbox/inboxAnswers.ts
new file mode 100644
index 0000000000000..f609541bf4d6d
--- /dev/null
+++ b/apps/mobile/src/j5/inbox/inboxAnswers.ts
@@ -0,0 +1,194 @@
+import {
+ compareInboxItems,
+ type HumanInboxAnswerAttempt,
+ keepForPersonScopes,
+ nextKeptItems,
+ type PresentedHumanInboxItem,
+ submitHumanInboxAnswer,
+} from "@t3tools/client-runtime/j5/inbox";
+import type { J5ReadSources } from "@t3tools/client-runtime/j5/readSources";
+import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
+import type { EnvironmentId } from "@t3tools/contracts";
+import { type HumanInboxResponse, scopedInboxItemKey } from "@t3tools/contracts/j5";
+import * as Cause from "effect/Cause";
+import { useEffect, useRef, useState } from "react";
+
+import { uuidv4 } from "../../lib/uuid";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { j5Environment } from "../state";
+import { answeredInboxQueryAtom, inboxCountQueryAtom, openInboxQueryAtom } from "./inboxSources";
+
+type Sources = J5ReadSources;
+
+/** How a kept item says it closed: who answered, once the answered list holds it (AC16, AC17). */
+export interface ClosedItem {
+ readonly answered: { readonly answeredBy: string | null | undefined } | null;
+ readonly answeredReadSinceClose: boolean;
+}
+
+async function sendAnswer(
+ environmentId: EnvironmentId,
+ input: {
+ readonly exchangeId: string;
+ readonly message: string;
+ readonly clientRequestId: string;
+ },
+) {
+ const result = await j5Environment.answerHumanExchange.run(appAtomRegistry, {
+ environmentId,
+ input,
+ });
+ if (result._tag === "Failure") throw Cause.squash(result.cause);
+}
+
+async function refreshAfterAnswer(environmentId: EnvironmentId) {
+ const results = await Promise.all(
+ [openInboxQueryAtom(environmentId), answeredInboxQueryAtom(environmentId)].map((atom) => {
+ appAtomRegistry.refresh(atom);
+ return executeAtomQuery(appAtomRegistry, atom, { reportFailure: false });
+ }),
+ );
+ const failed = results.find((result) => result._tag === "Failure");
+ if (failed?._tag === "Failure") throw Cause.squash(failed.cause);
+}
+
+const notifyCountChanged = (environmentId: EnvironmentId) =>
+ appAtomRegistry.refresh(inboxCountQueryAtom(environmentId));
+
+/**
+ * The answers being typed and sent on the Inbox, as web's Inbox keeps them: words survive until
+ * the server takes the answer; an item that closes while the person has typed into it stays with
+ * their words and who answered (AC17); a retry with the same words reuses its request id; and a
+ * server whose person changes drops its unsent words.
+ */
+export function useInboxAnswers(input: {
+ readonly openSources: Sources;
+ readonly items: ReadonlyArray;
+ readonly answeredSources: Sources;
+ readonly answered: ReadonlyArray;
+}) {
+ const { openSources, items, answeredSources, answered } = input;
+ const [answers, setAnswers] = useState>>({});
+ const personScopes = JSON.stringify(
+ openSources.sources.map((source) => [source.environmentId, source.data?.personId ?? null]),
+ );
+ const [answersPersonScopes, setAnswersPersonScopes] = useState(personScopes);
+ if (answersPersonScopes !== personScopes) {
+ setAnswersPersonScopes(personScopes);
+ const keep = keepForPersonScopes(personScopes);
+ const entries = Object.entries(answers).filter(([key]) => keep(key));
+ if (entries.length !== Object.keys(answers).length) setAnswers(Object.fromEntries(entries));
+ }
+ // An item that closed while the person was answering stays in place with their words. It is
+ // kept in the render it closes in, so its row is never unmounted and drawn again closed;
+ // `closedWith` is the answered list as it was then, to tell a later read of it.
+ const [retention, setRetention] = useState(() => ({
+ openSources,
+ items,
+ answers,
+ kept: new Map() as ReadonlyMap,
+ closedWith: new Map() as ReadonlyMap,
+ }));
+ let { kept, closedWith } = retention;
+ if (retention.openSources !== openSources || retention.answers !== answers) {
+ kept = nextKeptItems({
+ previous: retention.items,
+ current: items,
+ kept: retention.kept,
+ answers,
+ keyOf: scopedInboxItemKey,
+ });
+ closedWith = new Map(
+ [...kept.keys()].map((key) => [key, retention.closedWith.get(key) ?? answeredSources]),
+ );
+ setRetention({ openSources, items, answers, kept, closedWith });
+ }
+ const shownItems = kept.size === 0 ? items : [...items, ...kept.values()].sort(compareInboxItems);
+ const answeredByKey = new Map(answered.map((item) => [scopedInboxItemKey(item), item]));
+ const closedOf = (item: PresentedHumanInboxItem): ClosedItem | undefined => {
+ const key = scopedInboxItemKey(item);
+ if (!kept.has(key)) return undefined;
+ const answer = answeredByKey.get(key);
+ const source = answeredSources.sources.find(
+ (candidate) => candidate.environmentId === item.environmentId,
+ );
+ return {
+ answered: answer === undefined ? null : { answeredBy: answer.answeredBy },
+ answeredReadSinceClose:
+ closedWith.get(key) !== answeredSources && source?.status === "ready" && !source.refreshing,
+ };
+ };
+
+ // An ask that leaves the open list rereads that server's answered list, so a kept item learns
+ // who answered, or that the agent withdrew it, as web's Inbox does.
+ const previousOpenKeys = useRef(new Map>());
+ // oxlint-disable-next-line t3code/react-effect-budget -- an ask leaving the open list rereads the answered list; it reacts to data arriving, not to a handler here.
+ useEffect(() => {
+ const next = new Map>();
+ for (const source of openSources.sources) {
+ if (source.data === null) continue;
+ const keys = new Set(
+ source.data.items.map((item) =>
+ scopedInboxItemKey({ ...item, environmentId: source.environmentId }),
+ ),
+ );
+ const previous = previousOpenKeys.current.get(source.environmentId);
+ if (
+ source.status === "ready" &&
+ previous !== undefined &&
+ [...previous].some((key) => !keys.has(key))
+ ) {
+ appAtomRegistry.refresh(answeredInboxQueryAtom(source.environmentId));
+ }
+ next.set(source.environmentId, keys);
+ }
+ previousOpenKeys.current = next;
+ }, [openSources]);
+
+ const [pendingKey, setPendingKey] = useState(null);
+ // An error belongs to the ask that was being answered: on a phone it is shown by that ask's
+ // answer box, which is where the person is looking.
+ const [error, setError] = useState<{ readonly key: string; readonly message: string } | null>(
+ null,
+ );
+ const attempts = useRef(new Map());
+
+ const answer = async (item: PresentedHumanInboxItem) => {
+ const itemKey = scopedInboxItemKey(item);
+ const message = answers[itemKey] ?? "";
+ if (message.length === 0 || !item.sourceReady) return;
+ const keep = keepForPersonScopes(personScopes);
+ for (const key of attempts.current.keys()) if (!keep(key)) attempts.current.delete(key);
+ await submitHumanInboxAnswer({
+ item,
+ message,
+ attempts: attempts.current,
+ randomUUID: uuidv4,
+ send: sendAnswer,
+ refresh: refreshAfterAnswer,
+ notifyChanged: notifyCountChanged,
+ onAccepted: () =>
+ setAnswers((current) => {
+ const next = { ...current };
+ delete next[itemKey];
+ return next;
+ }),
+ setPendingExchangeId: setPendingKey,
+ setError: (message) => setError(message === null ? null : { key: itemKey, message }),
+ });
+ };
+
+ return {
+ shownItems,
+ closedOf,
+ answerText: (item: PresentedHumanInboxItem) => answers[scopedInboxItemKey(item)] ?? "",
+ setAnswerText: (item: PresentedHumanInboxItem, text: string) => {
+ const key = scopedInboxItemKey(item);
+ setAnswers((current) => ({ ...current, [key]: text }));
+ },
+ answer,
+ pendingKey,
+ errorFor: (item: PresentedHumanInboxItem) =>
+ error !== null && error.key === scopedInboxItemKey(item) ? error.message : null,
+ };
+}
diff --git a/apps/mobile/src/j5/inbox/inboxSources.ts b/apps/mobile/src/j5/inbox/inboxSources.ts
index 47a3f2b5e5529..47199a9c53ada 100644
--- a/apps/mobile/src/j5/inbox/inboxSources.ts
+++ b/apps/mobile/src/j5/inbox/inboxSources.ts
@@ -30,6 +30,8 @@ export const openInboxQueryAtom = (environmentId: EnvironmentId) =>
j5Environment.inbox({ environmentId, input: { status: "open" } });
export const answeredInboxQueryAtom = (environmentId: EnvironmentId) =>
j5Environment.inbox({ environmentId, input: { status: "answered" } });
+export const inboxCountQueryAtom = (environmentId: EnvironmentId) =>
+ j5Environment.openCount({ environmentId, input: {} });
/** Every connected server's open asks for this person; the server's inbox signal rereads them. */
export const openInboxSourcesAtom = createJ5ReadSourcesAtom({