The best way to control Claude Code, Codex and more from any computer or phone
feat(mobile): long-press an image to save it to Photos (#29598)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Nov 8, 2026 at 16:42 UTC
9028d760b49e523145ff5a7fe92592f2b47ecd96
6 files changed
+226
-32
apps/mobile/modules/t3-native-controls/android/src/main/java/expo/modules/t3nativecontrols/T3NativeControlsModule.kt
+45
@@ -1,7 +1,14 @@
1
package expo.modules.t3nativecontrols
2
3
+import android.content.ContentValues
4
+import android.content.Context
5
import android.content.Intent
6
+import android.net.Uri
7
+import android.os.Build
8
+import android.os.Environment
9
+import android.provider.MediaStore
10
import android.text.format.DateFormat
11
+import androidx.annotation.RequiresApi
12
import androidx.core.content.FileProvider
13
import expo.modules.kotlin.Promise
14
import expo.modules.kotlin.modules.Module
@@ -44,6 +51,15 @@ class T3NativeControlsModule : Module() {
51
}
52
}
53
54
+ AsyncFunction("saveImageToLibrary") { uri: String, mimeType: String, name: String ->
55
+ val context = appContext.reactContext ?: error("The app is not active.")
56
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
57
+ saveImageToPictures(context, Uri.parse(uri), mimeType, name)
58
+ } else {
59
+ error("Saving images needs Android 10 or later.")
60
+ }
61
+ }
62
+
63
OnActivityResult { _, (requestCode) ->
64
if (requestCode == 7343) {
65
filePreviewPromise?.resolve(null)
@@ -84,3 +100,32 @@ class T3NativeControlsModule : Module() {
100
}
101
}
102
}
103
+
104
+// Android 10+ lets apps add their own media without a storage permission.
105
+@RequiresApi(Build.VERSION_CODES.Q)
106
+private fun saveImageToPictures(context: Context, source: Uri, mimeType: String, name: String) {
107
+ val resolver = context.contentResolver
108
+ val values = ContentValues().apply {
109
+ put(MediaStore.Images.Media.DISPLAY_NAME, name)
110
+ put(MediaStore.Images.Media.MIME_TYPE, mimeType)
111
+ put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/T3 Code")
112
+ put(MediaStore.Images.Media.IS_PENDING, 1)
113
+ }
114
+ val target = resolver.insert(
115
+ MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY),
116
+ values
117
+ ) ?: error("Could not create the image in Pictures.")
118
+ runCatching {
119
+ val input = resolver.openInputStream(source) ?: error("The image is no longer available.")
120
+ input.use { from ->
121
+ val output = resolver.openOutputStream(target) ?: error("Could not write the image.")
122
+ output.use { from.copyTo(it) }
123
+ }
124
+ resolver.update(
125
+ target,
126
+ ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) },
127
+ null,
128
+ null
129
+ )
130
+ }.onFailure { resolver.delete(target, null, null) }.getOrThrow()
131
+}
apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift
+36
@@ -1,7 +1,9 @@
1
import AVFoundation
2
import ExpoModulesCore
3
+import Photos
4
import Security
5
import UIKit
6
+import UniformTypeIdentifiers
7
8
@ExpoModule("T3NativeControls")
9
public final class T3NativeControlsModule: Module {
@@ -123,6 +125,11 @@ public final class T3NativeControlsModule: Module {
125
AsyncFunction("shareFileFromSource") { (url: URL, title: String, identifier: String, promise: Promise) in
126
try self.shareFile(url: url, title: title, sourceIdentifier: identifier, promise: promise)
127
}.runOnQueue(.main)
128
+
129
+ // Photos names the asset itself, so iOS ignores the Android display name.
130
+ AsyncFunction("saveImageToLibrary") { (url: URL, mimeType: String, name: String, promise: Promise) in
131
+ Self.saveImageToLibrary(url: url, mimeType: mimeType, name: name, promise: promise)
132
+ }
133
}
134
135
// UIKit presenters are main-actor isolated rather than run on the JS thread
@@ -297,6 +304,35 @@ public final class T3NativeControlsModule: Module {
304
if filePresentation?.identifier == identifier { filePresentation?.dismiss() }
305
}
306
307
+ private static func saveImageToLibrary(url: URL, mimeType: String, name: String, promise: Promise) {
308
+ PHPhotoLibrary.requestAuthorization(for: .addOnly) { status in
309
+ guard status == .authorized || status == .limited else {
310
+ promise.reject(NSError(
311
+ domain: "T3NativePhotos",
312
+ code: 1,
313
+ userInfo: [NSLocalizedDescriptionKey: "Allow T3 Code to add photos in Settings."]
314
+ ))
315
+ return
316
+ }
317
+ PHPhotoLibrary.shared().performChanges({
318
+ let options = PHAssetResourceCreationOptions()
319
+ options.uniformTypeIdentifier = UTType(mimeType: mimeType)?.identifier
320
+ options.originalFilename = name
321
+ PHAssetCreationRequest.forAsset().addResource(with: .photo, fileURL: url, options: options)
322
+ }, completionHandler: { saved, error in
323
+ if saved {
324
+ promise.resolve(nil)
325
+ } else {
326
+ promise.reject(error ?? NSError(
327
+ domain: "T3NativePhotos",
328
+ code: 2,
329
+ userInfo: [NSLocalizedDescriptionKey: "Photos could not save this image."]
330
+ ))
331
+ }
332
+ })
333
+ }
334
+ }
335
+
336
private func shareFile(url: URL, title: String, sourceIdentifier: String, promise: Promise) throws {
337
guard let presenter = appContext?.utilities?.currentViewController() else {
338
throw NSError(
apps/mobile/src/lib/mediaActions.test.ts
+33
@@ -11,6 +11,8 @@ const state = vi.hoisted(() => ({
11
sessions: new Map<string, Pick<AuthSessionState, "authenticated" | "scopes">>(),
12
refresh: vi.fn(),
13
download: vi.fn(),
14
+ downloadPreview: vi.fn(),
15
+ saveImage: vi.fn(),
16
shareLocal: vi.fn(),
17
shareDraft: vi.fn(),
18
navigate: vi.fn(),
@@ -52,8 +54,17 @@ vi.mock("../state/atom-registry", () => ({
54
}));
55
vi.mock("./attachmentDownload", () => ({
56
downloadAndShareAttachment: state.download,
57
+ downloadAttachmentForPreview: state.downloadPreview,
58
shareLocalAttachment: state.shareLocal,
59
}));
60
+vi.mock("./saveImageToLibrary", () => ({
61
+ canSaveImageToLibrary: (mimeType: string) => mimeType === "image/png",
62
+ saveImageToLibrary: state.saveImage,
63
+}));
64
+vi.mock("expo-haptics", () => ({
65
+ notificationAsync: async () => {},
66
+ NotificationFeedbackType: { Success: "success" },
67
+}));
68
vi.mock("./copyTextWithHaptic", () => ({ copyTextWithHaptic: state.copy }));
69
vi.mock("./localAttachmentPreview", () => ({
70
loadLocalAttachmentPreview: async () => ({ share: state.shareDraft, dispose: vi.fn() }),
@@ -90,6 +101,8 @@ beforeEach(() => {
101
state.sessions.set(environmentId, denied);
102
state.refresh.mockReset().mockResolvedValue("https://host.test/image.png");
103
state.download.mockReset().mockResolvedValue(undefined);
104
+ state.downloadPreview.mockReset();
105
+ state.saveImage.mockReset().mockResolvedValue(undefined);
106
state.shareLocal.mockReset().mockResolvedValue(undefined);
107
state.shareDraft.mockReset().mockResolvedValue(undefined);
108
state.navigate.mockReset();
@@ -109,6 +122,7 @@ it.each(["workspace-file", "media-file"] as const)(
122
expect(state.navigate).not.toHaveBeenCalled();
123
expect(state.copy).toHaveBeenCalledWith("/repo/image.png");
124
expect(media.actions.find(({ id }) => id === "save")?.disabled).toBe(true);
125
+ expect(media.actions.find(({ id }) => id === "save-image")?.disabled).toBe(true);
126
expect(media.actions.find(({ id }) => id === "open-file")?.disabled).toBe(true);
127
},
128
);
@@ -178,3 +192,22 @@ it.each(["https://cdn.test/image.png", "file:///device/image.png"])(
192
expect(uri.startsWith("file:") ? state.shareLocal : state.download).toHaveBeenCalledOnce();
193
},
194
);
195
+
196
+it("saves a host image from its downloaded file, then removes the file", async () => {
197
+ state.sessions.set(environmentId, granted);
198
+ const disposed = Promise.withResolvers<void>();
199
+ state.downloadPreview.mockResolvedValue({
200
+ uri: "file:///cache/image.png",
201
+ dispose: disposed.resolve,
202
+ });
203
+
204
+ useMediaActions(hostSource())
205
+ .actions.find(({ id }) => id === "save-image")!
206
+ .run();
207
+ await disposed.promise;
208
+
209
+ expect(state.downloadPreview).toHaveBeenCalledWith(
210
+ expect.objectContaining({ url: "https://host.test/image.png" }),
211
+ );
212
+ expect(state.saveImage).toHaveBeenCalledWith("file:///cache/image.png", "image/png", "image.png");
213
+});
apps/mobile/src/lib/saveImageToLibrary.ts
new
+23
@@ -0,0 +1,23 @@
1
+import { requireNativeModule } from "expo";
2
+import { Platform } from "react-native";
3
+
4
+const SAVABLE_IMAGE_MIME_TYPE = /^image\/(png|jpe?g|gif|webp|heic|heif)$/i;
5
+
6
+function baseMimeType(mimeType: string): string {
7
+ return mimeType.split(";", 1)[0]?.trim() ?? "";
8
+}
9
+
10
+// Android 9 and older need a storage permission to add photos, so they keep the share sheet.
11
+export function canSaveImageToLibrary(mimeType: string): boolean {
12
+ return (
13
+ SAVABLE_IMAGE_MIME_TYPE.test(baseMimeType(mimeType)) &&
14
+ (Platform.OS === "ios" || (Platform.OS === "android" && Platform.Version >= 29))
15
+ );
16
+}
17
+
18
+/** Adds a local image file to Photos on iOS or Pictures/T3 Code on Android. */
19
+export function saveImageToLibrary(uri: string, mimeType: string, name: string): Promise<void> {
20
+ return requireNativeModule<{
21
+ saveImageToLibrary(uri: string, mimeType: string, name: string): Promise<void>;
22
+ }>("T3NativeControls").saveImageToLibrary(uri, baseMimeType(mimeType), name);
23
+}
apps/mobile/src/state/mediaActions.ts
+88
-32
@@ -14,15 +14,21 @@ import {
14
} from "@t3tools/contracts";
15
import { normalizeNativeMarkdownUrl } from "../lib/markdownLinks";
16
import { AsyncResult } from "effect/reactivity";
17
+import * as Haptics from "expo-haptics";
18
import { useEffect, useRef, useState } from "react";
19
20
import { useRefreshAssetUrl } from "./assets";
21
import { appAtomRegistry } from "./atom-registry";
22
import { useEnvironmentQuery } from "./query";
23
import { environmentSession } from "./session";
23
-import { downloadAndShareAttachment, shareLocalAttachment } from "../lib/attachmentDownload";
24
+import {
25
+ downloadAndShareAttachment,
26
+ downloadAttachmentForPreview,
27
+ shareLocalAttachment,
28
+} from "../lib/attachmentDownload";
29
import { copyTextWithHaptic } from "../lib/copyTextWithHaptic";
30
import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview";
31
+import { canSaveImageToLibrary, saveImageToLibrary } from "../lib/saveImageToLibrary";
32
33
function allowsHostMedia(session: SessionGrantInput | null) {
34
return session === null || sessionGrantsScope(session, AuthFilesystemReadScope);
@@ -53,41 +59,23 @@ export function useMediaActions(source: MediaActionsSource | undefined, onOpenFi
59
source && "resource" in source ? source.resource : null,
60
);
61
const controller = useRef<AbortController | null>(null);
56
- const [sharing, setSharing] = useState(false);
57
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the in-flight media share when the component unmounts
62
+ const [busy, setBusy] = useState<"share" | "save-image" | null>(null);
63
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- aborts the in-flight media task when the component unmounts
64
useEffect(() => () => controller.current?.abort(), []);
65
60
- const share = () => {
66
+ const run = (
67
+ kind: "share" | "save-image",
68
+ task: (source: MediaActionsSource, signal: AbortSignal) => Promise<void>,
69
+ ) => {
70
if (!source || controller.current || !canReadHostMedia(hostEnvironmentId)) return;
71
const request = new AbortController();
72
controller.current = request;
64
- setSharing(true);
65
- return (async () => {
66
- if ("attachment" in source) {
67
- const preview = await loadLocalAttachmentPreview(source.attachment, request.signal);
68
- if (!preview) return;
69
- const shared = await settlePromise(() =>
70
- preview.share(request.signal, source.sourceIdentifier),
71
- );
72
- preview.dispose();
73
- if (AsyncResult.isFailure(shared)) throw squashAtomCommandFailure(shared);
74
- return;
75
- }
76
- const uri = "uri" in source ? normalizeNativeMarkdownUrl(source.uri) : await refresh();
77
- if (request.signal.aborted || !canReadHostMedia(hostEnvironmentId)) return;
78
- if (uri === null) throw new Error("The file could not be loaded. Reconnect and try again.");
79
- const input = {
80
- attachment: { name: source.name, mimeType: source.mimeType },
81
- signal: request.signal,
82
- sourceIdentifier: source.sourceIdentifier,
83
- };
84
- if (/^(file|content):/i.test(uri)) await shareLocalAttachment({ ...input, uri });
85
- else await downloadAndShareAttachment({ ...input, url: uri });
86
- })()
73
+ setBusy(kind);
74
+ return task(source, request.signal)
75
.catch((error: unknown) => {
76
if (!request.signal.aborted) {
77
Dialog.alert(
90
- "Could not share file",
78
+ kind === "share" ? "Could not share file" : "Could not save image",
79
error instanceof Error ? error.message : "Try again.",
80
);
81
}
@@ -95,11 +83,64 @@ export function useMediaActions(source: MediaActionsSource | undefined, onOpenFi
83
.finally(() => {
84
if (controller.current === request) {
85
controller.current = null;
98
- if (!request.signal.aborted) setSharing(false);
86
+ if (!request.signal.aborted) setBusy(null);
87
}
88
});
89
};
90
91
+ const hostUri = async (source: MediaActionsSource, signal: AbortSignal) => {
92
+ const uri = "uri" in source ? normalizeNativeMarkdownUrl(source.uri) : await refresh();
93
+ if (signal.aborted || !canReadHostMedia(hostEnvironmentId)) return null;
94
+ if (uri === null) throw new Error("The file could not be loaded. Reconnect and try again.");
95
+ return uri;
96
+ };
97
+
98
+ const share = () =>
99
+ run("share", async (source, signal) => {
100
+ if ("attachment" in source) {
101
+ const preview = await loadLocalAttachmentPreview(source.attachment, signal);
102
+ if (!preview) return;
103
+ const shared = await settlePromise(() => preview.share(signal, source.sourceIdentifier));
104
+ preview.dispose();
105
+ if (AsyncResult.isFailure(shared)) throw squashAtomCommandFailure(shared);
106
+ return;
107
+ }
108
+ const uri = await hostUri(source, signal);
109
+ if (uri === null) return;
110
+ const input = {
111
+ attachment: { name: source.name, mimeType: source.mimeType },
112
+ signal,
113
+ sourceIdentifier: source.sourceIdentifier,
114
+ };
115
+ if (/^(file|content):/i.test(uri)) await shareLocalAttachment({ ...input, uri });
116
+ else await downloadAndShareAttachment({ ...input, url: uri });
117
+ });
118
+
119
+ const localImageFile = async (source: MediaActionsSource, signal: AbortSignal) => {
120
+ if ("attachment" in source) return loadLocalAttachmentPreview(source.attachment, signal);
121
+ const uri = await hostUri(source, signal);
122
+ if (uri === null) return null;
123
+ if (/^(file|content):/i.test(uri)) return { uri, dispose: () => {} };
124
+ return downloadAttachmentForPreview({
125
+ url: uri,
126
+ attachment: { name: source.name, mimeType: source.mimeType },
127
+ signal,
128
+ });
129
+ };
130
+
131
+ const saveImage = () =>
132
+ run("save-image", async (source, signal) => {
133
+ const file = await localImageFile(source, signal);
134
+ if (!file) return;
135
+ const saved = signal.aborted
136
+ ? null
137
+ : await settlePromise(() => saveImageToLibrary(file.uri, source.mimeType, source.name));
138
+ file.dispose();
139
+ if (saved === null) return;
140
+ if (AsyncResult.isFailure(saved)) throw squashAtomCommandFailure(saved);
141
+ void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(() => {});
142
+ });
143
+
144
const reference = source?.reference;
145
const relativePath = reference?.kind === "file" ? reference.relativePath : undefined;
146
const threadId = source && "threadId" in source ? source.threadId : undefined;
@@ -152,18 +193,33 @@ export function useMediaActions(source: MediaActionsSource | undefined, onOpenFi
193
},
194
]
195
: []),
196
+ ...(canSaveImageToLibrary(source.mimeType)
197
+ ? [
198
+ {
199
+ id: "save-image" as const,
200
+ title: busy === "save-image" ? "Saving image…" : "Save image",
201
+ run: saveImage,
202
+ disabled: busy !== null || !canReadMedia,
203
+ },
204
+ ]
205
+ : []),
206
{
207
id: "save" as const,
157
- title: sharing ? "Opening share sheet…" : "Save or share",
208
+ title:
209
+ busy === "share"
210
+ ? "Opening share sheet…"
211
+ : canSaveImageToLibrary(source.mimeType)
212
+ ? "Share"
213
+ : "Save or share",
214
run: share,
159
- disabled: sharing || !canReadMedia,
215
+ disabled: busy !== null || !canReadMedia,
216
},
217
]
218
: [];
219
return {
220
title: reference?.kind === "file" ? reference.path : reference?.url,
221
actions,
166
- sharing,
222
+ sharing: busy === "share",
223
share,
224
};
225
}
packages/client-runtime/src/mediaActions.ts
+1
@@ -11,4 +11,5 @@ export type MediaActionId =
11
| "copy-url"
12
| "open-file"
13
| "save"
14
+ | "save-image"
15
| "copy-image";