Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.modules.Module
Expand Down Expand Up @@ -44,7 +45,13 @@ class T3SecretInputModule : Module() {
}
Prop("editable") { view: T3SecretInputView, value: Boolean -> view.input.isEnabled = value }
Prop("revealed") { view: T3SecretInputView, value: Boolean -> view.setRevealed(value) }
Prop("returnKey") { view: T3SecretInputView, value: String ->
view.input.imeOptions =
if (value == "next") EditorInfo.IME_ACTION_NEXT else EditorInfo.IME_ACTION_DONE
}
Events("onChangeText", "onSubmit")

AsyncFunction("focus") { view: T3SecretInputView -> view.focusInput() }
}
}
}
Expand Down Expand Up @@ -103,7 +110,12 @@ class T3SecretInputView(context: Context, appContext: AppContext) : ExpoView(con
}
)
input.setOnEditorActionListener { _, actionId, event ->
if (actionId == EditorInfo.IME_ACTION_DONE || event?.keyCode == KeyEvent.KEYCODE_ENTER) {
// Next is submitted too: JS moves focus to the following field.
if (
actionId == EditorInfo.IME_ACTION_DONE ||
actionId == EditorInfo.IME_ACTION_NEXT ||
event?.keyCode == KeyEvent.KEYCODE_ENTER
) {
// Hardware Enter reports IME_NULL on Android 13 and earlier, and both key down and key up.
if (event == null || event.action == KeyEvent.ACTION_DOWN) {
onSubmit(mapOf("value" to input.text.toString()))
Expand Down Expand Up @@ -147,6 +159,12 @@ class T3SecretInputView(context: Context, appContext: AppContext) : ExpoView(con
applyingValue = false
}

fun focusInput() {
input.requestFocus()
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.showSoftInput(input, InputMethodManager.SHOW_IMPLICIT)
}

fun setCursorColor(color: Int) {
input.highlightColor = Color.argb(0x52, Color.red(color), Color.green(color), Color.blue(color))
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
Expand Down
35 changes: 30 additions & 5 deletions apps/mobile/src/components/ui/SecretTextInput.android.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { requireNativeView } from "expo";
import { useState } from "react";
import { useState, type Ref } from "react";
import { processColor, View, type NativeSyntheticEvent, type ViewProps } from "react-native";

import { cn } from "../../lib/cn";
import { flattenThemeColor } from "../../lib/mobileTheme";
import { useUniwindTheme } from "../../lib/useUniwindTheme";
import { SecretRevealButton } from "./SecretRevealButton";
import type { SecretTextInputProps } from "./SecretTextInput.types";

interface NativeSecretInputRef {
focus: () => Promise<void>;
}

interface NativeSecretInputProps extends ViewProps {
readonly ref?: Ref<NativeSecretInputRef>;
readonly inputLabel: string;
readonly value: string;
readonly placeholder: string;
Expand All @@ -17,6 +23,7 @@ interface NativeSecretInputProps extends ViewProps {
readonly fontSize: number;
readonly editable: boolean;
readonly revealed: boolean;
readonly returnKey: "next" | "done";
readonly onChangeText: (event: NativeSyntheticEvent<{ readonly value: string }>) => void;
readonly onSubmit: (event: NativeSyntheticEvent<{ readonly value: string }>) => void;
}
Expand All @@ -36,13 +43,28 @@ function nativeColor(value: string) {
* offer logins above the keyboard. This field is a native EditText that reports no autofill type.
* The frame matches AppTextInput's.
*/
export function SecretTextInput(props: SecretTextInputProps) {
export function SecretTextInput({ onMount, secret = true, ...props }: SecretTextInputProps) {
const theme = useUniwindTheme();
const surface = theme["--color-input"];
const [revealed, setRevealed] = useState(false);
return (
<View className="min-h-13.5 flex-row items-center gap-1 rounded-2xl border border-input-border bg-input pr-1.5 pl-3.5">
<View
className={cn(
"min-h-13.5 flex-row items-center gap-1 rounded-2xl border border-input-border bg-input pl-3.5",
secret ? "pr-1.5" : "pr-3.5",
)}
>
<NativeSecretInput
ref={
onMount === undefined
? undefined
: (native: NativeSecretInputRef | null) =>
onMount(
native === null
? null
: { focus: () => void native.focus().catch(() => undefined) },
)
}
inputLabel={props.accessibilityLabel}
value={props.value}
placeholder={props.placeholder}
Expand All @@ -51,12 +73,15 @@ export function SecretTextInput(props: SecretTextInputProps) {
cursorColor={nativeColor(flattenThemeColor(theme["--color-focus"], surface))}
fontSize={FONT_SIZE}
editable={props.editable}
revealed={revealed}
revealed={!secret || revealed}
returnKey={props.returnKeyType ?? "done"}
onChangeText={(event) => props.onChangeText(event.nativeEvent.value)}
onSubmit={(event) => props.onSubmitEditing(event.nativeEvent.value)}
style={{ flex: 1, height: LINE_HEIGHT }}
/>
<SecretRevealButton revealed={revealed} onPress={() => setRevealed(!revealed)} />
{secret ? (
<SecretRevealButton revealed={revealed} onPress={() => setRevealed(!revealed)} />
) : null}
</View>
);
}
19 changes: 12 additions & 7 deletions apps/mobile/src/components/ui/SecretTextInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,35 @@ import { SecretRevealButton } from "./SecretRevealButton";
import type { SecretTextInputProps } from "./SecretTextInput.types";

/** Masked field for a value that must stay out of password managers and suggestions. */
export function SecretTextInput(props: SecretTextInputProps) {
export function SecretTextInput({ onMount, secret = true, ...props }: SecretTextInputProps) {
const [revealed, setRevealed] = useState(false);
const returnKeyType = props.returnKeyType ?? "done";
return (
<View className="justify-center">
<AppTextInput
className="pr-12"
ref={onMount}
className={secret ? "pr-12" : undefined}
accessibilityLabel={props.accessibilityLabel}
placeholder={props.placeholder}
value={props.value}
onChangeText={props.onChangeText}
editable={props.editable}
secureTextEntry={!revealed}
secureTextEntry={secret && !revealed}
autoCorrect={false}
autoCapitalize="none"
autoComplete="off"
textContentType="none"
importantForAutofill="no"
spellCheck={false}
returnKeyType="done"
returnKeyType={returnKeyType}
submitBehavior={returnKeyType === "next" ? "submit" : "blurAndSubmit"}
onSubmitEditing={(event) => props.onSubmitEditing(event.nativeEvent.text)}
/>
<View className="absolute right-1.5">
<SecretRevealButton revealed={revealed} onPress={() => setRevealed(!revealed)} />
</View>
{secret ? (
<View className="absolute right-1.5">
<SecretRevealButton revealed={revealed} onPress={() => setRevealed(!revealed)} />
</View>
) : null}
</View>
);
}
9 changes: 9 additions & 0 deletions apps/mobile/src/components/ui/SecretTextInput.types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
export interface SecretTextInputHandle {
readonly focus: () => void;
}

export interface SecretTextInputProps {
readonly accessibilityLabel: string;
readonly placeholder: string;
Expand All @@ -6,4 +10,9 @@ export interface SecretTextInputProps {
/** Receives the field's current text, so a submit never uses a stale render of it. */
readonly onSubmitEditing: (value: string) => void;
readonly editable: boolean;
/** False shows the text with no eye toggle, for a value such as an email. Defaults to true. */
readonly secret?: boolean;
/** "next" keeps the keyboard open for the following field. */
readonly returnKeyType?: "next" | "done";
readonly onMount?: (handle: SecretTextInputHandle | null) => void;
}
77 changes: 59 additions & 18 deletions apps/mobile/src/features/threads/SecretRequestCard.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import {
SECRET_REQUEST_DEFAULT_PLACEHOLDER,
secretRequestAnswerInput,
secretRequestDisplay,
secretRequestFailureMessage,
secretRequestInputs,
secretRequestLink,
secretRequestPrivacyNote,
secretRequestReference,
secretRequestSources,
secretRequestValue,
type SecretRequestItem,
type SecretRequestReply,
type SecretRequestSource,
} from "@t3tools/client-runtime/secret-request";
import {
isAtomCommandInterrupted,
Expand All @@ -27,6 +29,7 @@ import { View, type ColorValue } from "react-native";
import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
import { SecretTextInput } from "../../components/ui/SecretTextInput";
import type { SecretTextInputHandle } from "../../components/ui/SecretTextInput.types";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
Expand All @@ -35,6 +38,7 @@ import { Chip } from "../../components/ui/Chip";

const LOCK_SYMBOL: AppSymbolName = { ios: "lock", android: "lock" };
const PRIVATE_SYMBOL: AppSymbolName = { ios: "checkmark.shield", android: "lock" };
const NO_SOURCES: ReadonlyArray<SecretRequestSource> = [];

export function SecretRequestCard(props: {
readonly environmentId: EnvironmentId;
Expand Down Expand Up @@ -84,46 +88,59 @@ function PendingSecretRequestForm(props: {
reportFailure: false,
reportDefect: false,
});
const inputs = secretRequestInputs(item, m);
const multiple = item.fields !== undefined;
const config = useAtomValue(serverEnvironment.configValueAtom(props.environmentId));
const sources = secretRequestSources(config, config?.settings.secretProviders ?? {}, m);
// A reference answers one value, so a card with fields is always typed.
const sources = multiple
? NO_SOURCES
: secretRequestSources(config, config?.settings.secretProviders ?? {}, m);
const [sourceId, setSourceId] = useState<SecretProviderId | null>(null);
const source = sources.find((candidate) => candidate.id === sourceId) ?? null;
const [secret, setSecret] = useState("");
const [values, setValues] = useState<Readonly<Record<string, string>>>({});
const [reference, setReference] = useState("");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Submit then a tap can both run before a re-render; this guard is synchronous.
const inFlight = useRef(false);
const inputRefs = useRef<Array<SecretTextInputHandle | null>>([]);

const send = async (reply: SecretRequestReply) => {
const input = secretRequestAnswerInput(item, reply);
if (input === null || inFlight.current) return;
inFlight.current = true;
setSubmitting(true);
setError(null);
// iOS offers to save a masked field that leaves the screen with text in it as a login
// password, so the card is emptied before it closes; a failed answer puts the values back.
const typed = reply.type === "save" ? reply.values : values;
setValues({});
const result = await answer({ environmentId: props.environmentId, input }).finally(() => {
inFlight.current = false;
setSubmitting(false);
});
if (result._tag === "Success") {
setSecret("");
setReference("");
return;
}
setValues(typed);
if (!isAtomCommandInterrupted(result)) {
setError(secretRequestFailureMessage(squashAtomCommandFailure(result), m));
}
};
const save = () => {
const save = (typed: Readonly<Record<string, string>>) => {
if (source === null) {
void send({ type: "save", secret });
void send({ type: "save", values: typed });
} else if (secretRequestReference(source, reference) === undefined) {
setError(source.invalidReferenceMessage);
} else {
void send({ type: "reference", source, reference });
}
};
const draft = source === null ? secret : reference;
const canSave =
source === null
? secretRequestAnswerInput(item, { type: "save", values }) !== null
: reference.trim().length > 0;
const link = secretRequestLink(item);

return (
Expand Down Expand Up @@ -180,14 +197,38 @@ function PendingSecretRequestForm(props: {
</View>
) : null}
{source === null ? (
<SecretTextInput
accessibilityLabel={item.label}
placeholder={item.placeholder ?? m(SECRET_REQUEST_DEFAULT_PLACEHOLDER)}
value={secret}
onChangeText={setSecret}
editable={!submitting}
onSubmitEditing={(value) => void send({ type: "save", secret: value })}
/>
inputs.map((input, index) => {
const last = index === inputs.length - 1;
const field = (
<SecretTextInput
key={input.key}
// A single input is labelled by the card title.
accessibilityLabel={multiple ? input.label : item.label}
secret={input.secret}
onMount={(handle) => {
inputRefs.current[index] = handle;
}}
placeholder={input.placeholder}
value={secretRequestValue(values, input.key)}
onChangeText={(value) => setValues((current) => ({ ...current, [input.key]: value }))}
editable={!submitting}
returnKeyType={last ? "done" : "next"}
onSubmitEditing={(value) =>
last
? save({ ...values, [input.key]: value })
: inputRefs.current[index + 1]?.focus()
}
/>
);
return multiple ? (
<View key={input.key} className="gap-1.5">
<Text className="font-t3-medium text-sm text-foreground-muted">{input.label}</Text>
{field}
</View>
) : (
field
);
})
) : (
<TextInput
key={source.id}
Expand All @@ -209,7 +250,7 @@ function PendingSecretRequestForm(props: {
importantForAutofill="no"
spellCheck={false}
returnKeyType="done"
onSubmitEditing={save}
onSubmitEditing={() => save(values)}
/>
)}
{error !== null ? (
Expand All @@ -225,8 +266,8 @@ function PendingSecretRequestForm(props: {
label={gt("Save securely")}
tone="primary"
fullWidth
disabled={submitting || draft.trim().length === 0}
onPress={save}
disabled={submitting || !canSave}
onPress={() => save(values)}
/>
<View className="flex-row items-center justify-between gap-2">
<View className="flex-1 flex-row items-center gap-1.5">
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/i18n/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@
"1fa38fb049c6b56e": "Filter {number} braucht einen Pfad unter body, headers oder query und mindestens einen Wert.",
"31ec02bdcb3920d1": "Filter {number} braucht einen Pfad unter body, headers oder query und einen Wert.",
"81f613bb68d85bb7": "Nicht im Chat, sondern in einer privaten Datei, die die Befehle dieses Agenten 24 Stunden lang lesen können",
"07b56c0c12bd2de1": "Nicht im Chat, sondern in privaten Dateien, die die Befehle dieses Agenten 24 Stunden lang lesen können",
"62ae4688ece05590": "Sicher gespeichert, dem Agenten nie angezeigt",
"8c2d901183b4e219": "Geheimnis einfügen",
"610aea624f895a78": "Sicher gespeichert und privat gehalten",
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@
"1fa38fb049c6b56e": "Filter {number} needs a path under body, headers or query, and at least one value.",
"31ec02bdcb3920d1": "Filter {number} needs a path under body, headers or query, and a value.",
"81f613bb68d85bb7": "Kept out of chat, in a private file this agent's commands can read for 24 hours",
"07b56c0c12bd2de1": "Kept out of chat, in private files this agent's commands can read for 24 hours",
"62ae4688ece05590": "Stored securely, never shown to the agent",
"8c2d901183b4e219": "Paste the secret",
"610aea624f895a78": "Saved securely and kept private",
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/i18n/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@
"1fa38fb049c6b56e": "El filtro {number} necesita una ruta dentro de body, headers o query, y al menos un valor.",
"31ec02bdcb3920d1": "El filtro {number} necesita una ruta dentro de body, headers o query, y un valor.",
"81f613bb68d85bb7": "Fuera del chat, en un archivo privado que los comandos de este agente pueden leer durante 24 horas",
"07b56c0c12bd2de1": "Fuera del chat, en archivos privados que los comandos de este agente pueden leer durante 24 horas",
"62ae4688ece05590": "Guardado de forma segura, nunca se muestra al agente",
"8c2d901183b4e219": "Pega el secreto",
"610aea624f895a78": "Guardado de forma segura y privada",
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@
"1fa38fb049c6b56e": "Le filtre {number} a besoin d’un chemin sous body, headers ou query, et d’au moins une valeur.",
"31ec02bdcb3920d1": "Le filtre {number} a besoin d’un chemin sous body, headers ou query, et d’une valeur.",
"81f613bb68d85bb7": "Hors de la discussion, dans un fichier privé que les commandes de cet agent peuvent lire pendant 24 heures",
"07b56c0c12bd2de1": "Hors de la discussion, dans des fichiers privés que les commandes de cet agent peuvent lire pendant 24 heures",
"62ae4688ece05590": "Stocké de façon sécurisée, jamais montré à l’agent",
"8c2d901183b4e219": "Collez le secret",
"610aea624f895a78": "Enregistré de façon sécurisée et gardé privé",
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/i18n/translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@
"1fa38fb049c6b56e": "フィルター {number} には body、headers、query 配下のパスと、少なくとも 1 つの値が必要です。",
"31ec02bdcb3920d1": "フィルター {number} には body、headers、query 配下のパスと値が必要です。",
"81f613bb68d85bb7": "チャットには表示せず、このエージェントのコマンドが 24 時間読み取れる非公開ファイルに保存します",
"07b56c0c12bd2de1": "チャットには表示せず、このエージェントのコマンドが 24 時間読み取れる非公開ファイルに保存します",
"62ae4688ece05590": "安全に保存され、エージェントには表示されません",
"8c2d901183b4e219": "シークレットを貼り付け",
"610aea624f895a78": "安全に保存し、非公開にしました",
Expand Down
Loading
Loading