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

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;
}

const isMcpSignInError = Schema.is(ProviderMcpSignInError);

/**
* 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 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);
// A result that lands after the sheet closed must not open a browser or report anything.
const closed = useRef(false);
const close = () => {
closed.current = true;
props.onClose();
};

const failed = (result: AtomCommandResult<unknown, unknown> & { readonly _tag: "Failure" }) => {
if (isAtomCommandInterrupted(result)) return;
const failure = squashAtomCommandFailure(result);
setError(
isMcpSignInError(failure) ? failure.detail : gt("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);
close();
};
const openSignInPage = async () => {
setBusy(true);
setError(null);
let page = url;
if (page === null) {
const result = await start({ environmentId: props.environmentId, input: props.target });
if (closed.current) return;
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 },
});
if (closed.current) return;
setBusy(false);
if (result._tag === "Success") signedIn();
else failed(result);
};

return (
<Sheet title={gt("Sign in to {server}", { server })} onClose={close}>
<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={close} fullWidth />
</ScrollView>
</Sheet>
);
}
80 changes: 74 additions & 6 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 @@ -50,6 +51,8 @@ import {
type ToolActivityIcon,
} from "@t3tools/contracts";
import { useAtomValue } from "@effect/atom-react";
import { Atom } from "effect/reactivity";
import * as DateTime from "effect/DateTime";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { environmentThreadDetails, threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
Expand Down Expand Up @@ -864,6 +867,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 @@ -882,6 +888,20 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
) {
const { row, expanded } = props;
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,
noticeAt: DateTime.toEpochMillis(signInNotice.updatedAt),
})
: NOT_SIGNED_IN,
);
const streamsOutput =
useCommandOutputStreaming(props.environmentId) &&
row.projectedItem.item.type === "command_execution";
Expand Down Expand Up @@ -969,7 +989,22 @@ 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;
// Signed in, the notice is an ordinary row again.
const opensMcpSignIn = mcpSignInTarget !== null && !mcpSignedIn;
// A sign-in notice opens its sheet instead; a nested button would be out of VoiceOver's reach.
const canExpand = row.canExpand && notifiedSubagentThreadId === undefined && !opensMcpSignIn;
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 @@ -1043,15 +1078,27 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
>
<WorkLogPressable
accessibilityRole={
notifiedSubagentThreadId !== undefined ? "link" : canExpand ? "button" : undefined
notifiedSubagentThreadId !== undefined
? "link"
: canExpand || opensMcpSignIn
? "button"
: undefined
}
accessibilityLabel={
failed
? `${accessiblePreview}, tool call failed`
: mcpSignInTarget !== null && mcpSignedIn
? `${accessiblePreview}, signed in`
: accessiblePreview
}
accessibilityLabel={failed ? `${accessiblePreview}, tool call failed` : accessiblePreview}
accessibilityHint={
notifiedSubagentThreadId !== undefined
? "Opens this agent's thread. Long press to copy."
: canExpand
? `Double tap to ${expanded ? "hide" : "show"} full details. Long press to copy.`
: "Long press to copy."
: opensMcpSignIn
? "Opens the sign-in. Long press to copy."
: canExpand
? `Double tap to ${expanded ? "hide" : "show"} full details. Long press to copy.`
: "Long press to copy."
}
accessibilityState={canExpand ? { expanded } : undefined}
onPress={() => {
Expand All @@ -1062,6 +1109,11 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
});
return;
}
if (opensMcpSignIn) {
void Haptics.selectionAsync();
setMcpSignInOpen(true);
return;
}
if (canExpand) {
void Haptics.selectionAsync();
props.onToggleRow(row.id, props.anchorKey, row.groupStandIn?.groupId);
Expand Down Expand Up @@ -1130,6 +1182,15 @@ const ThreadWorkLogRow = function ThreadWorkLogRow(
<Text className="pr-1 font-t3-medium text-3xs text-adaptive-emerald-600-400">
Copied
</Text>
) : mcpSignInTarget !== null ? (
<Text
className={cn(
"pr-1 font-t3-medium text-sm",
mcpSignedIn ? "text-adaptive-emerald-600-400" : "text-primary",
)}
>
{mcpSignedIn ? "Signed in" : "Sign in"}
</Text>
) : null}
{failed && toolIcon !== undefined ? (
<View
Expand Down Expand Up @@ -1157,6 +1218,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
11 changes: 10 additions & 1 deletion apps/mobile/src/i18n/translations/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,14 @@
"79b768229c9ef672": "Wartung",
"54b188d65247e42f": "Labs",
"f41ea186c275b56e": "Info",
"2a546119bf3879ee": "Archiv"
"2a546119bf3879ee": "Archiv",
"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",
"38574c0d1e49b278": "{preview}, angemeldet"
}
11 changes: 10 additions & 1 deletion apps/mobile/src/i18n/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,14 @@
"79b768229c9ef672": "Maintenance",
"54b188d65247e42f": "Labs",
"f41ea186c275b56e": "About",
"2a546119bf3879ee": "Archive"
"2a546119bf3879ee": "Archive",
"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",
"38574c0d1e49b278": "{preview}, signed in"
}
11 changes: 10 additions & 1 deletion apps/mobile/src/i18n/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,14 @@
"79b768229c9ef672": "Mantenimiento",
"54b188d65247e42f": "Labs",
"f41ea186c275b56e": "Acerca de",
"2a546119bf3879ee": "Archivados"
"2a546119bf3879ee": "Archivados",
"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",
"38574c0d1e49b278": "{preview}, sesión iniciada"
}
11 changes: 10 additions & 1 deletion apps/mobile/src/i18n/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,14 @@
"79b768229c9ef672": "Maintenance",
"54b188d65247e42f": "Labs",
"f41ea186c275b56e": "À propos",
"2a546119bf3879ee": "Archives"
"2a546119bf3879ee": "Archives",
"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",
"38574c0d1e49b278": "{preview}, connecté"
}
Loading