paseo-plugin-secure-input 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/LICENSE +21 -0
  2. package/OVERVIEW.md +28 -0
  3. package/README.md +105 -2
  4. package/SECURITY.md +84 -0
  5. package/assets/icon.png +0 -0
  6. package/client/card.tsx +74 -0
  7. package/client/codes.ts +32 -0
  8. package/client/diagnostics-rows.ts +139 -0
  9. package/client/dialog-state.ts +59 -0
  10. package/client/dialog.tsx +292 -0
  11. package/client/envelope-cache.ts +85 -0
  12. package/client/fields.tsx +255 -0
  13. package/client/file-entry.ts +142 -0
  14. package/client/form-state.ts +198 -0
  15. package/client/globals.d.ts +19 -0
  16. package/client/outcome.ts +96 -0
  17. package/client/presentation.ts +114 -0
  18. package/client/sealing.ts +27 -0
  19. package/client/self-test.ts +96 -0
  20. package/client/settings.tsx +160 -0
  21. package/client/submit.ts +92 -0
  22. package/client/text.ts +47 -0
  23. package/client/tone.ts +36 -0
  24. package/client/web.ts +184 -0
  25. package/index.client.tsx +29 -0
  26. package/index.server.ts +6 -0
  27. package/npm-shrinkwrap.json +60 -0
  28. package/package.json +68 -4
  29. package/paseo-plugin.json +6 -0
  30. package/server/core/continuation.ts +151 -0
  31. package/server/core/entries.ts +89 -0
  32. package/server/core/outbox.ts +555 -0
  33. package/server/core/registry-store.ts +185 -0
  34. package/server/core/registry.ts +1031 -0
  35. package/server/core/selftest.ts +60 -0
  36. package/server/core/view.ts +38 -0
  37. package/server/io/atomic.ts +119 -0
  38. package/server/io/deadline.ts +28 -0
  39. package/server/io/descriptor.ts +36 -0
  40. package/server/io/directory.ts +40 -0
  41. package/server/io/drop.ts +434 -0
  42. package/server/io/legacy-shim.ts +108 -0
  43. package/server/io/ownership.ts +8 -0
  44. package/server/io/private-file.ts +86 -0
  45. package/server/paseo/bounded.ts +13 -0
  46. package/server/paseo/handlers.ts +124 -0
  47. package/server/paseo/hooks.ts +106 -0
  48. package/server/paseo/plugin.ts +341 -0
  49. package/server/paseo/runtime.ts +409 -0
  50. package/server/paseo/tools.ts +178 -0
  51. package/shared/bytes.ts +100 -0
  52. package/shared/canonical.ts +32 -0
  53. package/shared/card.ts +41 -0
  54. package/shared/contracts.ts +128 -0
  55. package/shared/errors.ts +48 -0
  56. package/shared/limits.ts +118 -0
  57. package/shared/request-id.ts +9 -0
  58. package/shared/request.ts +66 -0
  59. package/shared/sanitize.ts +101 -0
  60. package/shared/seal.ts +292 -0
  61. package/shared/shown.ts +12 -0
  62. package/shared/text.ts +39 -0
  63. package/shared/view.ts +42 -0
  64. package/skills/secure-input/SKILL.md +150 -0
@@ -0,0 +1,292 @@
1
+ import type { PluginHostProps } from "@getpaseo/plugin/client";
2
+ import { useRpc } from "@getpaseo/plugin/client";
3
+ import { Icon, Modal } from "@getpaseo/plugin/client/ui";
4
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
+ import { Text, View } from "react-native";
6
+ import { declineRequest, fulfillRequest, getRequest } from "../shared/contracts";
7
+ import { LIMITS } from "../shared/limits";
8
+ import type { RequestView } from "../shared/view";
9
+ import { applyOutcome, applyRead, arrowAction, declineAction, openedDialog, type DialogState } from "./dialog-state";
10
+ import { keepAfter, type SealedSubmission } from "./envelope-cache";
11
+ import { takeFile, wipeFile, type FileValue } from "./file-entry";
12
+ import { ANNOUNCED, FileRow, IconButton, MONO, RowLine, TextRow } from "./fields";
13
+ import { addRow, checkForm, clearFile, fillFile, formFromView, removeRow, setName, setText, toFileRow, wipeForm, type FormState } from "./form-state";
14
+ import { afterDecline, afterLostReply } from "./outcome";
15
+ import { A11Y, FORM_BADGE, dialogScreen, formTitle } from "./presentation";
16
+ import { sealEntries } from "./sealing";
17
+ import { submitEntries, type SubmitDeps, type SubmitOutcome } from "./submit";
18
+ import { tone } from "./tone";
19
+ import { canPickFiles, pickFile, useFileDrop } from "./web";
20
+
21
+ interface DialogProps extends PluginHostProps {
22
+ requestId: string;
23
+ /** A fresh number each time the form opens. The pill keys the form by the request and this, so every opening of every request starts from nothing. */
24
+ session: number;
25
+ onClose(): void;
26
+ }
27
+
28
+ /**
29
+ * A value the component renders as it was last set, and that its handlers read as it is now: a press, a blur and a
30
+ * file that arrives late all act on the latest form, not on the one of the render they were made in.
31
+ */
32
+ function useHeld<T>(initial: () => T): [T, { readonly current: T }, (next: T) => void] {
33
+ const ref = useRef<{ current: T } | null>(null);
34
+ if (ref.current === null) ref.current = { current: initial() };
35
+ const held = ref.current;
36
+ const [value, setValue] = useState<T>(held.current);
37
+ const set = useCallback(
38
+ (next: T) => {
39
+ held.current = next;
40
+ setValue(next);
41
+ },
42
+ [held],
43
+ );
44
+ return [value, held, set];
45
+ }
46
+
47
+ /**
48
+ * The form over the chat. It holds what the human types and the files they give, reads the request once
49
+ * when it opens, and does what `outcome.ts`, `submit.ts` and `dialog-state.ts` decide. However it goes (closed by the
50
+ * human, by an answer, or unmounted with its row by the chat's list), it takes no file's bytes along: they are wiped.
51
+ */
52
+ export function RequestDialog({ requestId, session, onClose, theme, layout }: DialogProps) {
53
+ const colors = tone(theme.colors);
54
+ const get = useRpc(getRequest);
55
+ const fulfill = useRpc(fulfillRequest);
56
+ const decline = useRpc(declineRequest);
57
+ const [state, stateRef, setState] = useHeld<DialogState>(openedDialog);
58
+ const [form, formRef, setForm] = useHeld<FormState>(() => ({ rows: [] }));
59
+ /** What is under way: «→» (a reading or a submission), or «✕». Nothing else is taken meanwhile. */
60
+ const [busy, setBusy] = useState<"arrow" | "decline" | null>(null);
61
+ const working = useRef(false);
62
+ /** The envelope of the last submission with the entries it was sealed from. Component memory only; gone with the form. */
63
+ const sealed = useRef<SealedSubmission | null>(null);
64
+ const mounted = useRef(true);
65
+ /** The number the next row of the human's is given. Never one that was given before, so no row takes another's place. */
66
+ const nextRow = useRef(1);
67
+ const body = useRef<View>(null);
68
+ const latestGet = useRef(get);
69
+ latestGet.current = get;
70
+
71
+ useEffect(() => {
72
+ mounted.current = true;
73
+ return () => {
74
+ mounted.current = false;
75
+ wipeForm(formRef.current);
76
+ sealed.current = null;
77
+ };
78
+ }, [formRef]);
79
+
80
+ /** A change to the form, made on the latest form and once: a change that wipes a file wipes it here. */
81
+ const update = (change: (current: FormState) => FormState) => {
82
+ const next = change(formRef.current);
83
+ if (next !== formRef.current) setForm(next);
84
+ };
85
+
86
+ /** A reading of the request, and the form for its fields when it is the first view the form holds. */
87
+ const land = useCallback(
88
+ (loaded: RequestView | null) => {
89
+ if (!mounted.current) return;
90
+ const before = stateRef.current;
91
+ const after = applyRead(before, requestId, loaded);
92
+ setState(after);
93
+ if (before.view === null && after.view !== null) setForm(formFromView(after.view));
94
+ },
95
+ [requestId, stateRef, setState, setForm],
96
+ );
97
+
98
+ // Read once per opening. There is no interval and no refetch on focus: nothing may change on screen while the human types.
99
+ useEffect(() => {
100
+ let current = true;
101
+ latestGet.current({ requestId }).then(
102
+ (loaded) => {
103
+ if (current) land(loaded);
104
+ },
105
+ () => {
106
+ if (current) land(null);
107
+ },
108
+ );
109
+ return () => {
110
+ current = false;
111
+ };
112
+ }, [requestId, session, land]);
113
+
114
+ function close() {
115
+ wipeForm(formRef.current);
116
+ sealed.current = null;
117
+ onClose();
118
+ }
119
+
120
+ /** Does exactly what the outcome says. */
121
+ function perform(outcome: SubmitOutcome) {
122
+ if (!mounted.current) return;
123
+ sealed.current = outcome.cache;
124
+ setState(applyOutcome(stateRef.current, outcome));
125
+ if (outcome.next.clearForm) {
126
+ wipeForm(formRef.current);
127
+ setForm({ rows: [] });
128
+ }
129
+ if (outcome.next.close) close();
130
+ }
131
+
132
+ /** One thing at a time. A task never rejects; if one fails all the same, the form asks for «→» again and keeps everything. */
133
+ async function run(kind: "arrow" | "decline", task: () => Promise<void>) {
134
+ if (working.current) return;
135
+ working.current = true;
136
+ setBusy(kind);
137
+ try {
138
+ await task();
139
+ } catch {
140
+ if (mounted.current) setState(applyOutcome(stateRef.current, { next: afterLostReply(), view: null }));
141
+ } finally {
142
+ working.current = false;
143
+ if (mounted.current) setBusy(null);
144
+ }
145
+ }
146
+
147
+ const deps: SubmitDeps = { get, fulfill, seal: sealEntries };
148
+
149
+ function pressArrow() {
150
+ const { entries } = checkForm(formRef.current);
151
+ const action = arrowAction(stateRef.current, entries !== null);
152
+ if (action === "read") {
153
+ void run("arrow", async () => {
154
+ let loaded: RequestView | null;
155
+ try {
156
+ loaded = await get({ requestId });
157
+ } catch {
158
+ loaded = null;
159
+ }
160
+ land(loaded);
161
+ });
162
+ } else if (action === "submit") {
163
+ const view = stateRef.current.view;
164
+ if (view === null || entries === null) return;
165
+ void run("arrow", async () => perform(await submitEntries(deps, { requestId, view, entries, cache: sealed.current })));
166
+ }
167
+ }
168
+
169
+ function pressDecline() {
170
+ if (working.current) return;
171
+ if (declineAction(stateRef.current) === "close") return close();
172
+ void run("decline", async () => {
173
+ let succeeded = false;
174
+ try {
175
+ await decline({ requestId });
176
+ succeeded = true;
177
+ } catch {
178
+ // Closed by someone else, or the plugin is unreachable: the form says so with its line, and the pill shows the real state.
179
+ }
180
+ const next = afterDecline(succeeded);
181
+ perform({ next, cache: keepAfter(sealed.current, next), view: null });
182
+ });
183
+ }
184
+
185
+ /** A file for a row: taken only while the form is on screen and nothing is under way, and only into an empty file row; any other is wiped (`takeFile`, `fillFile`). */
186
+ const took = (id: string) => (file: FileValue) => takeFile(file, mounted.current && !working.current, (taken) => update((current) => fillFile(current, id, taken)));
187
+
188
+ /** The paperclip of a text row of the human's: the row becomes a file row, and where the app can pick a file, it is picked now. */
189
+ const toFile = (id: string) => {
190
+ update((current) => toFileRow(current, id));
191
+ if (canPickFiles) {
192
+ void pickFile().then((file) => {
193
+ if (file !== null) took(id)(file);
194
+ });
195
+ }
196
+ };
197
+
198
+ // A file dropped on the form but not on a file row is taken by nothing, and goes nowhere else either.
199
+ useFileDrop(body, wipeFile);
200
+
201
+ const checked = useMemo(() => checkForm(form), [form]);
202
+ const labels = useMemo(() => new Map((state.view?.fields ?? []).map((field) => [field.key, field.label] as const)), [state.view]);
203
+ const screen = dialogScreen(state);
204
+ const locked = busy !== null;
205
+ const arrowReady = busy === null && arrowAction(state, checked.entries !== null) !== null;
206
+
207
+ return (
208
+ <Modal title={formTitle(form.rows.length)} icon={<Icon name="ShieldCheck" size={18} color={colors.accent} />} open onOpenChange={(open) => (open ? undefined : close())}>
209
+ {/* The host's own scrolling body: the sheet on a phone, with its swipe down and its keyboard handling, and on the desktop a box no taller than the form. */}
210
+ <Modal.Content contentContainerStyle={{ padding: layout.compact ? 16 : 20, gap: 0 }}>
211
+ <View ref={body} style={{ gap: 8 }}>
212
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 8 }}>
213
+ <View style={{ borderWidth: 1, borderColor: colors.border, borderRadius: 6, paddingHorizontal: 6, paddingVertical: 2 }}>
214
+ <Text style={{ color: colors.accent, fontFamily: MONO, fontSize: 11 }}>{FORM_BADGE}</Text>
215
+ </View>
216
+ <View style={{ flex: 1 }} />
217
+ <IconButton icon="X" label={A11Y.decline} color={colors.muted} disabled={locked} onPress={pressDecline} />
218
+ </View>
219
+
220
+ {state.top === null ? null : (
221
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 6 }}>
222
+ <Icon name="CircleAlert" size={14} color={colors.danger} />
223
+ <Text {...ANNOUNCED} style={{ color: colors.danger, fontSize: 12, flexShrink: 1 }}>
224
+ {state.top}
225
+ </Text>
226
+ </View>
227
+ )}
228
+
229
+ {screen === "form"
230
+ ? form.rows.map((row) => {
231
+ const error = checked.errors.get(row.id) ?? null;
232
+ const onName = (key: string) => update((current) => setName(current, row.id, key));
233
+ const onRemove = () => update((current) => removeRow(current, row.id));
234
+ return row.value.kind === "text" ? (
235
+ <TextRow
236
+ key={row.id}
237
+ row={row}
238
+ hint={row.declared ? (labels.get(row.key) ?? "") : ""}
239
+ error={error}
240
+ colors={colors}
241
+ locked={locked}
242
+ onText={(text) => update((current) => setText(current, row.id, text))}
243
+ onName={onName}
244
+ onToFile={() => toFile(row.id)}
245
+ onRemove={onRemove}
246
+ />
247
+ ) : (
248
+ <FileRow
249
+ key={row.id}
250
+ row={row}
251
+ hint={row.declared ? (labels.get(row.key) ?? "") : ""}
252
+ error={error}
253
+ colors={colors}
254
+ locked={locked}
255
+ onName={onName}
256
+ onFile={took(row.id)}
257
+ onClearFile={() => update((current) => clearFile(current, row.id))}
258
+ onRemove={onRemove}
259
+ />
260
+ );
261
+ })
262
+ : null}
263
+
264
+ {screen === "loading" ? null : (
265
+ <View style={{ flexDirection: "row", alignItems: "center", gap: 8, marginTop: 4 }}>
266
+ {screen === "form" ? (
267
+ <IconButton
268
+ icon="Plus"
269
+ label={A11Y.add}
270
+ color={colors.muted}
271
+ fill={colors.raised}
272
+ disabled={locked || form.rows.length >= LIMITS.fields}
273
+ onPress={() => update((current) => addRow(current, nextRow.current++))}
274
+ />
275
+ ) : null}
276
+ <View style={{ flex: 1, alignItems: "center" }}>{screen === "form" && checked.total !== null ? <RowLine text={checked.total} colors={colors} /> : null}</View>
277
+ <IconButton
278
+ icon="ArrowRight"
279
+ label={A11Y.submit}
280
+ color={colors.onAccent}
281
+ fill={colors.accent}
282
+ busy={busy === "arrow"}
283
+ disabled={!arrowReady}
284
+ onPress={pressArrow}
285
+ />
286
+ </View>
287
+ )}
288
+ </View>
289
+ </Modal.Content>
290
+ </Modal>
291
+ );
292
+ }
@@ -0,0 +1,85 @@
1
+ import type { PayloadEntry, SealedEnvelope } from "../shared/seal";
2
+ import type { Next } from "./outcome";
3
+
4
+ /**
5
+ * What an envelope was sealed to. The ciphertext is bound to the request and to the digest of what it asked for
6
+ * (`buildAad`) and readable only with the request's key, so an envelope is good for exactly this and nothing else.
7
+ */
8
+ export interface SealTarget {
9
+ requestId: string;
10
+ publicKey: string;
11
+ requestDigest: string;
12
+ }
13
+
14
+ /**
15
+ * The envelope of the last submission together with the entries it was sealed from, kept in component memory while the
16
+ * form is open. The daemon recognises a submission by the digest of its ciphertext: the same envelope sent again is
17
+ * answered with the same result, but the same values sealed anew are a second, different submission, and one that
18
+ * arrives after the first was accepted is refused as `request_closed` and flagged as tampering.
19
+ */
20
+ export interface SealedSubmission {
21
+ target: SealTarget;
22
+ entries: readonly PayloadEntry[];
23
+ envelope: SealedEnvelope;
24
+ /** True after a call whose reply never came: the daemon may or may not have taken this envelope. */
25
+ lostReply: boolean;
26
+ }
27
+
28
+ export type EnvelopeChoice = { reuse: true; envelope: SealedEnvelope } | { reuse: false };
29
+
30
+ function sameTarget(a: SealTarget, b: SealTarget): boolean {
31
+ return a.requestId === b.requestId && a.publicKey === b.publicKey && a.requestDigest === b.requestDigest;
32
+ }
33
+
34
+ /** The same key, and the same text or the same file: a text and a file are never the same, whatever characters they have. */
35
+ function sameEntry(a: PayloadEntry, b: PayloadEntry): boolean {
36
+ if (a.key !== b.key) return false;
37
+ if ("file" in a) return "file" in b && a.file === b.file;
38
+ return !("file" in b) && a.value === b.value;
39
+ }
40
+
41
+ /** Same entries, same order. The values are compared where they already are, in memory; nothing derived from one is made. */
42
+ function sameEntries(a: readonly PayloadEntry[], b: readonly PayloadEntry[]): boolean {
43
+ if (a.length !== b.length) return false;
44
+ return a.every((entry, index) => {
45
+ const other = b[index];
46
+ return other !== undefined && sameEntry(entry, other);
47
+ });
48
+ }
49
+
50
+ /** The kept envelope when the entries are the ones it was sealed from, to the same request. Otherwise the caller seals anew. */
51
+ export function chooseEnvelope(cache: SealedSubmission | null, target: SealTarget, entries: readonly PayloadEntry[]): EnvelopeChoice {
52
+ if (cache !== null && sameTarget(cache.target, target) && sameEntries(cache.entries, entries)) {
53
+ return { reuse: true, envelope: cache.envelope };
54
+ }
55
+ return { reuse: false };
56
+ }
57
+
58
+ /**
59
+ * Takes its own copy of the entries, of each its key and its text or its file and nothing else: what the caller does
60
+ * with its list afterwards must not change what the envelope was sealed from.
61
+ */
62
+ export function remember(target: SealTarget, entries: readonly PayloadEntry[], envelope: SealedEnvelope): SealedSubmission {
63
+ const copies = entries.map((entry): PayloadEntry => ("file" in entry ? { key: entry.key, file: entry.file } : { key: entry.key, value: entry.value }));
64
+ return { target: { ...target }, entries: copies, envelope, lostReply: false };
65
+ }
66
+
67
+ /** The call was made and no reply came. */
68
+ export function markLost(cache: SealedSubmission): SealedSubmission {
69
+ return { ...cache, lostReply: true };
70
+ }
71
+
72
+ /** An answer came, even a refusal: whether the daemon took the envelope is known again. */
73
+ export function markKnown(cache: SealedSubmission): SealedSubmission {
74
+ return { ...cache, lostReply: false };
75
+ }
76
+
77
+ /** True when what is kept was sent to this request and nobody knows whether it was taken. */
78
+ export function unknownOutcome(cache: SealedSubmission | null, target: SealTarget): boolean {
79
+ return cache !== null && cache.lostReply && sameTarget(cache.target, target);
80
+ }
81
+
82
+ /** What is kept once the answer is known: the same, unless the answer says the envelope is of no further use. */
83
+ export function keepAfter(cache: SealedSubmission | null, next: Pick<Next, "dropEnvelope">): SealedSubmission | null {
84
+ return next.dropEnvelope ? null : cache;
85
+ }
@@ -0,0 +1,255 @@
1
+ import { Icon, TextInput } from "@getpaseo/plugin/client/ui";
2
+ import { useEffect, useMemo, useRef, useState } from "react";
3
+ import { ActivityIndicator, Platform, Pressable, Text, View } from "react-native";
4
+ import { checkedFile, fileLine, fromPasted, takeFile, type FileValue } from "./file-entry";
5
+ import type { FormRow } from "./form-state";
6
+ import { A11Y, KEY_PLACEHOLDER, eye } from "./presentation";
7
+ import type { Tone } from "./tone";
8
+ import { canPickFiles, pickFile, useFileDrop } from "./web";
9
+
10
+ export const MONO = Platform.select({ ios: "Menlo", default: "monospace" });
11
+
12
+ /**
13
+ * What stops an input from suggesting, completing or remembering what is typed in it. Every one of these exists on the
14
+ * SDK's `TextInput` (React Native's own props).
15
+ */
16
+ const PRIVATE_INPUT = {
17
+ autoCapitalize: "none",
18
+ autoCorrect: false,
19
+ autoComplete: "off",
20
+ spellCheck: false,
21
+ textContentType: "none",
22
+ importantForAutofill: "no",
23
+ } as const;
24
+
25
+ /** The box of a row: red when the row has a line under it, dashed while a file row waits for its file. */
26
+ function boxStyle(colors: Tone, error: boolean, dashed = false) {
27
+ return {
28
+ flexDirection: "row",
29
+ alignItems: "center",
30
+ gap: 8,
31
+ minHeight: 42,
32
+ paddingHorizontal: 10,
33
+ borderWidth: 1,
34
+ borderRadius: 9,
35
+ borderStyle: dashed ? "dashed" : "solid",
36
+ borderColor: error ? colors.danger : colors.border,
37
+ backgroundColor: colors.surface,
38
+ } as const;
39
+ }
40
+
41
+ interface IconButtonProps {
42
+ icon: string;
43
+ label: string;
44
+ /** What a screen reader says after the label: the agent's label of the field the button is for. None when empty. */
45
+ hint?: string;
46
+ color: string;
47
+ onPress(): void;
48
+ disabled?: boolean;
49
+ /** A background for a button that stands by itself, as «+» and «→» do. */
50
+ fill?: string;
51
+ /** While what it started is under way: it shows an indicator in place of its icon, and takes no press. */
52
+ busy?: boolean;
53
+ }
54
+
55
+ /** A control with an icon and no words: what it does is its accessibility label, in Ukrainian, and the field it is for its hint. */
56
+ export function IconButton({ icon, label, hint, color, onPress, disabled = false, fill, busy = false }: IconButtonProps) {
57
+ return (
58
+ <Pressable
59
+ accessibilityRole="button"
60
+ accessibilityLabel={label}
61
+ accessibilityHint={hint === undefined || hint === "" ? undefined : hint}
62
+ accessibilityState={{ disabled: disabled || busy, busy }}
63
+ disabled={disabled || busy}
64
+ onPress={onPress}
65
+ hitSlop={6}
66
+ style={{ width: 34, height: 34, borderRadius: 9, alignItems: "center", justifyContent: "center", backgroundColor: fill ?? "transparent", opacity: disabled && !busy ? 0.4 : 1 }}
67
+ >
68
+ {busy ? <ActivityIndicator size="small" color={color} /> : <Icon name={icon} size={16} color={color} />}
69
+ </Pressable>
70
+ );
71
+ }
72
+
73
+ /**
74
+ * Props that have a screen reader say a line the moment it appears, as a problem: the line under a row, and the one at
75
+ * the top of the form. The role `alert` is a live region in the web build (the desktop app), and Android reads a polite
76
+ * live region as it changes. iOS has no live region: VoiceOver reads the line when it comes to it.
77
+ */
78
+ export const ANNOUNCED = { accessibilityRole: "alert", accessibilityLiveRegion: "polite" } as const;
79
+
80
+ /** A line under a row, in the colour of a problem, said to a screen reader as it appears. */
81
+ export function RowLine({ text, colors }: { text: string; colors: Tone }) {
82
+ return (
83
+ <Text {...ANNOUNCED} style={{ color: colors.danger, fontSize: 12, marginLeft: 4 }}>
84
+ {text}
85
+ </Text>
86
+ );
87
+ }
88
+
89
+ /** The key of a field the agent asked for, inside the box on the left: dimmer when the field may stay empty. */
90
+ function KeyText({ row, colors }: { row: FormRow; colors: Tone }) {
91
+ return (
92
+ <Text numberOfLines={1} style={{ color: colors.muted, opacity: row.optional ? 0.55 : 1, fontFamily: MONO, fontSize: 12, flexShrink: 1, maxWidth: "45%" }}>
93
+ {row.key}
94
+ </Text>
95
+ );
96
+ }
97
+
98
+ /** The name of a key the human adds. A name is not a secret, so it is shown as typed; a screen reader is told what it is. */
99
+ function NameInput({ row, colors, locked, onName }: { row: FormRow; colors: Tone; locked: boolean; onName(key: string): void }) {
100
+ return (
101
+ <TextInput
102
+ value={row.key}
103
+ onChangeText={onName}
104
+ accessibilityLabel={A11Y.name}
105
+ placeholder={KEY_PLACEHOLDER}
106
+ placeholderTextColor={colors.muted}
107
+ editable={!locked}
108
+ {...PRIVATE_INPUT}
109
+ autoCapitalize="characters"
110
+ style={{ width: 120, paddingVertical: 8, paddingRight: 8, borderRightWidth: 1, borderRightColor: colors.border, color: colors.text, fontFamily: MONO, fontSize: 12 }}
111
+ />
112
+ );
113
+ }
114
+
115
+ interface RowProps {
116
+ row: FormRow;
117
+ /** The agent's label, which a screen reader reads as the hint of the row's controls. It is shown nowhere. */
118
+ hint: string;
119
+ /** The line under the row, from `checkForm`, or null. */
120
+ error: string | null;
121
+ colors: Tone;
122
+ /** While the form is being sent: the row is faint and takes nothing. */
123
+ locked: boolean;
124
+ onName(key: string): void;
125
+ onRemove(): void;
126
+ }
127
+
128
+ interface TextRowProps extends RowProps {
129
+ onText(text: string): void;
130
+ onToFile(): void;
131
+ }
132
+
133
+ /**
134
+ * A row for a line of text: the key (or, in a row of the human's, the name they type), the value hidden on one line,
135
+ * and the eye that shows it on the same line. A row of the human's has a paperclip that makes it a file row, and «✕».
136
+ * A value of several lines goes through a file row, where its line breaks are kept. While the form is locked no control
137
+ * of the row takes a press, the eye included.
138
+ */
139
+ export function TextRow({ row, hint, error, colors, locked, onText, onName, onToFile, onRemove }: TextRowProps) {
140
+ const [shown, setShown] = useState(false);
141
+ const look = eye(shown);
142
+ const text = row.value.kind === "text" ? row.value.text : "";
143
+ return (
144
+ <View style={{ gap: 4, opacity: locked ? 0.5 : 1 }}>
145
+ <View style={boxStyle(colors, error !== null)}>
146
+ {row.declared ? <KeyText row={row} colors={colors} /> : <NameInput row={row} colors={colors} locked={locked} onName={onName} />}
147
+ <TextInput
148
+ value={text}
149
+ onChangeText={onText}
150
+ secureTextEntry={!shown}
151
+ editable={!locked}
152
+ accessibilityLabel={row.key.trim() === "" ? undefined : row.key.trim()}
153
+ accessibilityHint={hint === "" ? undefined : hint}
154
+ {...PRIVATE_INPUT}
155
+ style={{ flex: 1, paddingVertical: 8, color: colors.text, fontFamily: MONO, fontSize: 13 }}
156
+ />
157
+ <IconButton icon={look.icon} label={look.label} color={colors.muted} disabled={locked} onPress={() => setShown((current) => !current)} />
158
+ {row.declared ? null : (
159
+ <>
160
+ <IconButton icon="Paperclip" label={A11Y.pick} color={colors.muted} disabled={locked} onPress={onToFile} />
161
+ <IconButton icon="X" label={A11Y.remove} color={colors.muted} disabled={locked} onPress={onRemove} />
162
+ </>
163
+ )}
164
+ </View>
165
+ {error === null ? null : <RowLine text={error} colors={colors} />}
166
+ </View>
167
+ );
168
+ }
169
+
170
+ interface FileRowProps extends RowProps {
171
+ /** A file picked, dropped or pasted. The form takes it only into an empty row, and wipes any it does not take. */
172
+ onFile(file: FileValue): void;
173
+ onClearFile(): void;
174
+ }
175
+
176
+ /**
177
+ * A row for a whole file. Empty, it has the paperclip (where the app can pick files), the clipboard, which opens an area
178
+ * under the row to paste into, and it takes a file dropped on it. Filled, it shows the file's name, size and check, and
179
+ * «✕» to take it out. Its content is never shown; the paste area shows what is pasted while it is open, and when it
180
+ * loses focus its text becomes the file and the area closes. The agent's label is the hint of each of its controls.
181
+ */
182
+ export function FileRow({ row, hint, error, colors, locked, onName, onFile, onClearFile, onRemove }: FileRowProps) {
183
+ const box = useRef<View>(null);
184
+ const alive = useRef(true);
185
+ useEffect(() => {
186
+ alive.current = true;
187
+ return () => {
188
+ alive.current = false;
189
+ };
190
+ }, []);
191
+ const [pasting, setPasting] = useState(false);
192
+ const [pasted, setPasted] = useState("");
193
+ const file = row.value.kind === "file" ? row.value.file : null;
194
+ const line = useMemo(() => (file === null ? null : fileLine(file, row.format, checkedFile(file, row.format))), [file, row.format]);
195
+
196
+ // A file is handed on only while the row is unlocked and mounted, and wiped otherwise (`takeFile`).
197
+ const take = (value: FileValue) =>
198
+ takeFile(value, !locked && alive.current, (taken) => {
199
+ // Whatever filled the row, the paste area closes, and what was pasted into it is let go.
200
+ setPasting(false);
201
+ setPasted("");
202
+ onFile(taken);
203
+ });
204
+ useFileDrop(box, take);
205
+ const pick = () => {
206
+ void pickFile().then((value) => {
207
+ if (value !== null) take(value);
208
+ });
209
+ };
210
+ const endPaste = () => {
211
+ const value = fromPasted(pasted);
212
+ setPasted("");
213
+ setPasting(false);
214
+ if (value !== null) take(value);
215
+ };
216
+
217
+ return (
218
+ <View style={{ gap: 4, opacity: locked ? 0.5 : 1 }}>
219
+ <View ref={box} style={boxStyle(colors, error !== null, file === null)}>
220
+ {row.declared ? <KeyText row={row} colors={colors} /> : <NameInput row={row} colors={colors} locked={locked} onName={onName} />}
221
+ {row.format === "any" ? null : <Text style={{ color: colors.muted, opacity: 0.7, fontFamily: MONO, fontSize: 11 }}>{row.format}</Text>}
222
+ {line === null ? (
223
+ <>
224
+ <View style={{ flex: 1 }} />
225
+ {canPickFiles ? <IconButton icon="Paperclip" label={A11Y.pick} hint={hint} color={colors.muted} disabled={locked} onPress={pick} /> : null}
226
+ <IconButton icon="ClipboardPaste" label={A11Y.paste} hint={hint} color={colors.muted} disabled={locked} onPress={() => setPasting(true)} />
227
+ </>
228
+ ) : (
229
+ <>
230
+ <Text numberOfLines={1} style={{ flex: 1, color: colors.text, fontSize: 12 }}>
231
+ {line}
232
+ </Text>
233
+ <IconButton icon="X" label={A11Y.removeFile} hint={hint} color={colors.muted} disabled={locked} onPress={onClearFile} />
234
+ </>
235
+ )}
236
+ {row.declared ? null : <IconButton icon="X" label={A11Y.remove} color={colors.muted} disabled={locked} onPress={onRemove} />}
237
+ </View>
238
+ {pasting ? (
239
+ <TextInput
240
+ value={pasted}
241
+ onChangeText={setPasted}
242
+ onBlur={endPaste}
243
+ accessibilityLabel={A11Y.pasteArea}
244
+ accessibilityHint={hint === "" ? undefined : hint}
245
+ multiline
246
+ autoFocus
247
+ editable={!locked}
248
+ {...PRIVATE_INPUT}
249
+ style={{ minHeight: 96, padding: 8, borderWidth: 1, borderRadius: 9, borderColor: colors.accent, color: colors.text, fontFamily: MONO, fontSize: 12, textAlignVertical: "top" }}
250
+ />
251
+ ) : null}
252
+ {error === null ? null : <RowLine text={error} colors={colors} />}
253
+ </View>
254
+ );
255
+ }