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
167 changes: 167 additions & 0 deletions apps/mobile/src/features/threads/McpSignInSheet.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import type { EnvironmentId, ProviderThreadId, ThreadId } from "@t3tools/contracts";
import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
import {
type AtomCommandResult,
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import * as Haptics from "expo-haptics";
import { msg, T, useGT, useMessages } from "gt-react-native";
import { useState } from "react";
import { ScrollView } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText";
import { Button } from "../../components/ui/Button";
import { Sheet } from "../../components/ui/Sheet";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";

export interface McpSignInTarget {
readonly threadId: ThreadId;
readonly providerThreadId: ProviderThreadId;
readonly server: string;
}

/**
* Signs an agent's MCP server in from the notice that says it needs one. The
* agent keeps the credential; the user approves in a browser, then pastes back
* the address it lands on, which is often a localhost page on another machine.
*/
export function McpSignInSheet(props: {
readonly environmentId: EnvironmentId;
readonly target: McpSignInTarget;
readonly onClose: () => void;
}) {
const gt = useGT();
const m = useMessages();
const insets = useSafeAreaInsets();
const { server } = props.target;
const start = useAtomCommand(threadEnvironment.mcpSignInStart, {
label: "start MCP sign-in",
reportFailure: false,
reportDefect: false,
});
const complete = useAtomCommand(threadEnvironment.mcpSignInComplete, {
label: "finish MCP sign-in",
reportFailure: false,
reportDefect: false,
});
const [url, setUrl] = useState<string | null>(null);
const [callbackUrl, setCallbackUrl] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);

const failed = (result: AtomCommandResult<unknown, unknown> & { readonly _tag: "Failure" }) => {
if (isAtomCommandInterrupted(result)) return;
setError(
errorDisplayMessage(squashAtomCommandFailure(result), m) ??
m(msg("The sign-in couldn't continue. Try again.")),
);
};
// The command marks the server signed in for the thread, which every notice about it shows.
const signedIn = () => {
void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);
props.onClose();
};
const openSignInPage = async () => {
setBusy(true);
setError(null);
let page = url;
if (page === null) {
const result = await start({ environmentId: props.environmentId, input: props.target });
if (result._tag === "Failure") {
setBusy(false);
failed(result);
return;
}
if (result.value.authorizationUrl === null) {
setBusy(false);
signedIn();
return;
}
page = result.value.authorizationUrl;
setUrl(page);
}
setBusy(false);
if (!(await tryOpenExternalUrl(page, "provider-auth"))) {
setError(gt("Could not open the sign-in page."));
}
};
const finish = async () => {
const pasted = callbackUrl.trim();
if (pasted.length === 0) return;
setBusy(true);
setError(null);
const result = await complete({
environmentId: props.environmentId,
input: { ...props.target, callbackUrl: pasted },
});
setBusy(false);
if (result._tag === "Success") signedIn();
else failed(result);
};

return (
<Sheet title={gt("Sign in to {server}", { server })} onClose={props.onClose}>
<ScrollView
className="flex-1 bg-sheet-solid"
contentInsetAdjustmentBehavior="automatic"
contentContainerClassName="gap-5 p-5"
contentContainerStyle={{ paddingBottom: insets.bottom + 20 }}
keyboardShouldPersistTaps="handled"
>
<Text className="font-sans text-sm leading-5 text-foreground-muted">
<T>
Approve access in your browser. It then opens a page that may not load: copy that page's
address and paste it here.
</T>
</Text>
<Button
label={gt("Open sign-in page")}
icon="globe"
tone="secondary"
disabled={busy}
onPress={() => void openSignInPage()}
fullWidth
/>
{url !== null ? (
<TextInput
accessibilityLabel={gt("Address of the page your browser opened")}
placeholder="http://127.0.0.1:…/callback?code=…"
value={callbackUrl}
onChangeText={setCallbackUrl}
editable={!busy}
autoCorrect={false}
autoCapitalize="none"
keyboardType="url"
spellCheck={false}
returnKeyType="done"
onSubmitEditing={() => void finish()}
/>
) : null}
{error !== null ? (
<Text
accessibilityRole="alert"
accessibilityLiveRegion="polite"
className="font-sans text-sm text-danger-foreground"
>
{error}
</Text>
) : null}
{url !== null ? (
<Button
label={gt("Finish sign-in")}
tone="primary"
loading={busy}
disabled={busy || callbackUrl.trim().length === 0}
onPress={() => void finish()}
fullWidth
/>
) : null}
<Button label={gt("Cancel")} tone="secondary" onPress={props.onClose} fullWidth />
</ScrollView>
</Sheet>
);
}
73 changes: 66 additions & 7 deletions apps/mobile/src/features/threads/thread-work-log.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
WorkLogPressable,
} from "./work-log-layout";
import { QuestionAnswerHistory } from "./QuestionAnswerHistory";
import { McpSignInSheet, type McpSignInTarget } from "./McpSignInSheet";
import { ThreadCommandOutput, useCommandOutputStreaming } from "./thread-command-output";
import {
getQuestionAnswerPreview,
Expand Down Expand Up @@ -51,6 +52,7 @@ import {
type ToolActivityIcon,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { Atom } from "effect/reactivity";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
Expand Down Expand Up @@ -866,6 +868,9 @@ function HighlightedCodeText({
);
}

// Rows that aren't sign-in notices read this, so every row reads an atom.
const NOT_SIGNED_IN = Atom.make(false);

const ThreadWorkLogRow = function ThreadWorkLogRow(
props: Omit<
ThreadWorkLogProps,
Expand All @@ -886,6 +891,19 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
const gt = useGT();
const messages = useMessages();
const openLinkedThread = useOpenLinkedThread();
const canSignInToMcp = useAtomValue(
threadEnvironment.mcpSignInStart.permissionAtom(props.environmentId),
);
const [mcpSignInOpen, setMcpSignInOpen] = useState(false);
const signInNotice = row.projectedItem.item;
const mcpSignedIn = useAtomValue(
signInNotice.type === "system_notice" && signInNotice.mcpSignIn !== undefined
? threadEnvironment.mcpSignedInAtom(props.environmentId, {
threadId: signInNotice.threadId,
server: signInNotice.mcpSignIn.server,
})
: NOT_SIGNED_IN,
);
const streamsOutput =
useCommandOutputStreaming(props.environmentId) &&
row.projectedItem.item.type === "command_execution";
Expand Down Expand Up @@ -982,7 +1000,21 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
row.projectedItem.item.type === "notification"
? notificationChildThreadId(row.projectedItem.item.source)
: undefined;
const canExpand = row.canExpand && notifiedSubagentThreadId === undefined;
const notice = row.projectedItem.item;
const mcpSignInTarget: McpSignInTarget | null =
canSignInToMcp &&
notice.type === "system_notice" &&
notice.mcpSignIn !== undefined &&
notice.providerThreadId !== null
? {
threadId: notice.threadId,
providerThreadId: notice.providerThreadId,
server: notice.mcpSignIn.server,
}
: null;
// A sign-in notice opens its sheet instead; a nested button would be out of VoiceOver's reach.
const canExpand =
row.canExpand && notifiedSubagentThreadId === undefined && mcpSignInTarget === null;
const reasoning = row.projectedItem.item.type === "reasoning" ? row.projectedItem.item : null;
const fetchedItem = fetchedDetail.data?.item ?? null;
const isRead = toolGroupAction(row.workEntry) === "read";
Expand Down Expand Up @@ -1057,7 +1089,11 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
>
<WorkLogPressable
accessibilityRole={
notifiedSubagentThreadId !== undefined ? "link" : canExpand ? "button" : undefined
notifiedSubagentThreadId !== undefined
? "link"
: canExpand || mcpSignInTarget !== null
? "button"
: undefined
}
accessibilityLabel={
failed
Expand All @@ -1067,11 +1103,13 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
accessibilityHint={
notifiedSubagentThreadId !== undefined
? gt("Opens this agent's thread. Long press to copy.")
: canExpand
? expanded
? gt("Double tap to hide full details. Long press to copy.")
: gt("Double tap to show full details. Long press to copy.")
: gt("Long press to copy.")
: mcpSignInTarget !== null
? gt("Opens the sign-in. Long press to copy.")
: canExpand
? expanded
? gt("Double tap to hide full details. Long press to copy.")
: gt("Double tap to show full details. Long press to copy.")
: gt("Long press to copy.")
}
accessibilityState={canExpand ? { expanded } : undefined}
onPress={() => {
Expand All @@ -1082,6 +1120,11 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
});
return;
}
if (mcpSignInTarget !== null) {
void Haptics.selectionAsync();
setMcpSignInOpen(true);
return;
}
if (canExpand) {
void Haptics.selectionAsync();
props.onToggleRow(row.id, props.anchorKey, row.groupStandIn?.groupId);
Expand Down Expand Up @@ -1150,6 +1193,15 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
<Text className="pr-1 font-t3-medium text-3xs text-adaptive-emerald-600-400">
<T>Copied</T>
</Text>
) : mcpSignInTarget !== null ? (
<Text
className={cn(
"pr-1 font-t3-medium text-sm",
mcpSignedIn ? "text-adaptive-emerald-600-400" : "text-primary",
)}
>
{mcpSignedIn ? <T>Signed in</T> : <T>Sign in</T>}
</Text>
) : null}
{failed && toolIcon !== undefined ? (
<View
Expand Down Expand Up @@ -1177,6 +1229,13 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
</View>
</View>
</WorkLogPressable>
{mcpSignInOpen && mcpSignInTarget !== null ? (
<McpSignInSheet
environmentId={props.environmentId}
target={mcpSignInTarget}
onClose={() => setMcpSignInOpen(false)}
/>
) : null}

{expanded &&
(reasoning ||
Expand Down
8 changes: 8 additions & 0 deletions apps/mobile/src/i18n/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -4223,6 +4223,14 @@
},
" kann nicht geladen werden"
],
"15f32e12fd49533f": "Die Anmeldung konnte nicht fortgesetzt werden. Versuche es erneut.",
"54789628a737f557": "Bei {server} anmelden",
"f8fde2e549c61546": "Adresse der Seite, die dein Browser geöffnet hat",
"d9f6244b252d11f6": "Anmeldung abschließen",
"8aecbd38f1facf71": "Erlaube den Zugriff in deinem Browser. Danach öffnet er eine Seite, die vielleicht nicht lädt: Kopiere die Adresse dieser Seite und füge sie hier ein.",
"6e5bcc452add4f9b": "Öffnet die Anmeldung. Lange drücken zum Kopieren.",
"83be7aade7ff6360": "Angemeldet",
"ec21b232e0eacd4a": "Anmelden",
"12ba9fa1445f92a2": "Arbeit der Subagenten",
"eaa6c91a05d95ce7": "Aktualisieren",
"4740c38b2edd194d": "Nur lesen. Diese Subagenten können keine Nachrichten annehmen.",
Expand Down
8 changes: 8 additions & 0 deletions apps/mobile/src/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -4224,6 +4224,14 @@
},
" app"
],
"15f32e12fd49533f": "The sign-in couldn't continue. Try again.",
"54789628a737f557": "Sign in to {server}",
"f8fde2e549c61546": "Address of the page your browser opened",
"d9f6244b252d11f6": "Finish sign-in",
"8aecbd38f1facf71": "Approve access in your browser. It then opens a page that may not load: copy that page's address and paste it here.",
"6e5bcc452add4f9b": "Opens the sign-in. Long press to copy.",
"83be7aade7ff6360": "Signed in",
"ec21b232e0eacd4a": "Sign in",
"12ba9fa1445f92a2": "Subagent work",
"eaa6c91a05d95ce7": "Refresh",
"4740c38b2edd194d": "Read only. These subagents cannot take messages.",
Expand Down
8 changes: 8 additions & 0 deletions apps/mobile/src/i18n/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -4216,6 +4216,14 @@
"v": "v"
}
],
"15f32e12fd49533f": "No se pudo continuar con el inicio de sesión. Vuelve a intentarlo.",
"54789628a737f557": "Iniciar sesión en {server}",
"f8fde2e549c61546": "Dirección de la página que abrió tu navegador",
"d9f6244b252d11f6": "Terminar de iniciar sesión",
"8aecbd38f1facf71": "Aprueba el acceso en tu navegador. Después abrirá una página que puede no cargar: copia la dirección de esa página y pégala aquí.",
"6e5bcc452add4f9b": "Abre el inicio de sesión. Mantén pulsado para copiar.",
"83be7aade7ff6360": "Sesión iniciada",
"ec21b232e0eacd4a": "Iniciar sesión",
"12ba9fa1445f92a2": "Trabajo del subagente",
"eaa6c91a05d95ce7": "Actualizar",
"4740c38b2edd194d": "Solo lectura. Estos subagentes no pueden recibir mensajes.",
Expand Down
8 changes: 8 additions & 0 deletions apps/mobile/src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -4217,6 +4217,14 @@
"v": "v"
}
],
"15f32e12fd49533f": "Impossible de poursuivre la connexion. Réessayez.",
"54789628a737f557": "Se connecter à {server}",
"f8fde2e549c61546": "Adresse de la page ouverte par votre navigateur",
"d9f6244b252d11f6": "Terminer la connexion",
"8aecbd38f1facf71": "Autorisez l’accès dans votre navigateur. Il ouvre ensuite une page qui peut ne pas se charger : copiez l’adresse de cette page et collez-la ici.",
"6e5bcc452add4f9b": "Ouvre la connexion. Appuyez longuement pour copier.",
"83be7aade7ff6360": "Connecté",
"ec21b232e0eacd4a": "Se connecter",
"12ba9fa1445f92a2": "Travail des sous-agents",
"eaa6c91a05d95ce7": "Actualiser",
"4740c38b2edd194d": "Lecture seule. Ces sous-agents ne peuvent pas recevoir de messages.",
Expand Down
8 changes: 8 additions & 0 deletions apps/mobile/src/i18n/translations/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -4210,6 +4210,14 @@
},
" アプリを読み込めません"
],
"15f32e12fd49533f": "サインインを続行できませんでした。もう一度お試しください。",
"54789628a737f557": "{server} にサインイン",
"f8fde2e549c61546": "ブラウザーが開いたページのアドレス",
"d9f6244b252d11f6": "サインインを完了",
"8aecbd38f1facf71": "ブラウザーでアクセスを許可してください。その後、読み込まれない場合があるページが開きます。そのページのアドレスをコピーして、ここに貼り付けてください。",
"6e5bcc452add4f9b": "サインインを開きます。長押しでコピーします。",
"83be7aade7ff6360": "サインイン済み",
"ec21b232e0eacd4a": "サインイン",
"12ba9fa1445f92a2": "サブエージェントの作業",
"eaa6c91a05d95ce7": "更新",
"4740c38b2edd194d": "読み取り専用です。これらのサブエージェントはメッセージを受け付けません。",
Expand Down
Loading
Loading