The best way to control Claude Code, Codex and more from any computer or phone
feat(mobile): view and control agent devices (#12531)
Julius Marminge committed
Sep 18, 2026 at 20:36 UTC
823119350ee29cca434b1295aa5c560f4c9ef98a
27 files changed
+1344
-60
apps/mobile/metro.config.js
+28
-1
@@ -17,6 +17,7 @@ const licenseGeneratorSource = path.join(
17
);
18
const escapedWorkspaceRoot = workspaceRoot.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
19
const mobileShikiRoot = path.dirname(require.resolve("shiki/package.json", { paths: [__dirname] }));
20
+const generatedDeviceStreamRoot = path.join(__dirname, ".generated", "device-stream");
21
const resolveShikiDependencyRoot = (packageName) => {
22
const entryPath = require.resolve(packageName, { paths: [mobileShikiRoot] });
23
let currentDir = path.dirname(entryPath);
@@ -46,6 +47,7 @@ config.resolver = {
47
extraNodeModules: {
48
...config.resolver?.extraNodeModules,
49
"@t3tools/mobile-third-party-licenses": generatedLicenseModuleRoot,
50
+ "@t3tools/mobile-device-stream": generatedDeviceStreamRoot,
51
shiki: mobileShikiRoot,
52
"@shikijs/core": resolveShikiDependencyRoot("@shikijs/core"),
53
"@shikijs/engine-javascript": resolveShikiDependencyRoot("@shikijs/engine-javascript"),
@@ -93,7 +95,32 @@ async function generateMobileThirdPartyLicenses() {
95
]);
96
}
97
96
-module.exports = generateMobileThirdPartyLicenses().then(() =>
98
+async function prepareDeviceStream() {
99
+ const { generateDeviceStreamScript } = await import(
100
+ pathToFileURL(path.join(__dirname, "scripts", "generate-device-stream.mts")).href
101
+ );
102
+ await generateDeviceStreamScript();
103
+ if (process.env.NODE_ENV !== "production") {
104
+ let rebuild = Promise.resolve();
105
+ for (const [directory, files] of [
106
+ [path.join(__dirname, "src/features/devices"), ["device-stream.browser.ts"]],
107
+ [
108
+ path.join(workspaceRoot, "packages/client-runtime/src/device"),
109
+ ["stream.ts", "hubAccess.ts"],
110
+ ],
111
+ ]) {
112
+ // The generated module participates in Metro's normal Fast Refresh.
113
+ fs.watch(directory, { persistent: false }, (_event, filename) => {
114
+ if (filename && !files.includes(String(filename))) return;
115
+ rebuild = rebuild.then(generateDeviceStreamScript).catch((error) => {
116
+ console.error("Could not rebuild the device stream:", error);
117
+ });
118
+ });
119
+ }
120
+ }
121
+}
122
+
123
+module.exports = Promise.all([generateMobileThirdPartyLicenses(), prepareDeviceStream()]).then(() =>
124
withUniwindConfig(config, {
125
cssEntryFile: "./global.css",
126
extraThemes,
apps/mobile/scripts/generate-device-stream.mts
new
+39
@@ -0,0 +1,39 @@
1
+import * as NodeFSP from "node:fs/promises";
2
+import * as NodePath from "node:path";
3
+import * as NodeURL from "node:url";
4
+import { build } from "vite-plus";
5
+
6
+const mobileRoot = NodePath.resolve(NodePath.dirname(NodeURL.fileURLToPath(import.meta.url)), "..");
7
+
8
+/** Metro embeds the shared browser transport as a small script in the native WebView. */
9
+export async function generateDeviceStreamScript() {
10
+ const result = await build({
11
+ configFile: false,
12
+ logLevel: "silent",
13
+ build: {
14
+ write: false,
15
+ target: "es2022",
16
+ minify: true,
17
+ lib: {
18
+ entry: NodePath.join(mobileRoot, "src/features/devices/device-stream.browser.ts"),
19
+ name: "T3DeviceStream",
20
+ formats: ["iife"],
21
+ },
22
+ },
23
+ });
24
+ const bundles = Array.isArray(result) ? result : [result];
25
+ const chunk = bundles
26
+ .flatMap((bundle) => ("output" in bundle ? bundle.output : []))
27
+ .find((output) => output.type === "chunk");
28
+ if (!chunk) throw new Error("Device stream build did not emit a script.");
29
+ const root = NodePath.join(mobileRoot, ".generated/device-stream");
30
+ await NodeFSP.mkdir(root, { recursive: true });
31
+ for (const [name, contents] of [
32
+ ["index.js", `module.exports = ${JSON.stringify(chunk.code)};\n`],
33
+ ["package.json", '{"main":"index.js"}\n'],
34
+ ] as const) {
35
+ const destination = NodePath.join(root, name);
36
+ const previous = await NodeFSP.readFile(destination, "utf8").catch(() => null);
37
+ if (previous !== contents) await NodeFSP.writeFile(destination, contents);
38
+ }
39
+}
apps/mobile/src/Stack.tsx
+11
@@ -30,6 +30,7 @@ import {
30
import { ReviewCommentComposerSheet } from "./features/review/ReviewCommentComposerSheet";
31
import { ReviewSheet } from "./features/review/ReviewSheet";
32
import { ThreadTerminalRouteScreen } from "./features/terminal/ThreadTerminalRouteScreen";
33
+import { DevicePreviewRouteScreen } from "./features/devices/DevicePreviewRouteScreen";
34
import { GitBranchesSheet } from "./features/threads/git/GitBranchesSheet";
35
import { GitCommitSheet } from "./features/threads/git/GitCommitSheet";
36
import { GitConfirmSheet } from "./features/threads/git/GitConfirmSheet";
@@ -449,6 +450,7 @@ const WORKSPACE_OVERLAY_ROUTES = new Set([
450
"SettingsLegal",
451
"SettingsSheet",
452
"ThreadReviewComment",
453
+ "ThreadDevicePreview",
454
"ThreadSettingsSheet",
455
]);
456
@@ -595,6 +597,15 @@ export const RootStack = createNativeStackNavigator({
597
linking: `${THREAD_LINKING_PREFIX}/terminal`,
598
options: SOLID_HEADER_OPTIONS,
599
}),
600
+ ThreadDevicePreview: createNativeStackScreen({
601
+ screen: DevicePreviewRouteScreen,
602
+ linking: `${THREAD_LINKING_PREFIX}/devices`,
603
+ options: {
604
+ presentation: "fullScreenModal",
605
+ headerShown: false,
606
+ gestureEnabled: false,
607
+ },
608
+ }),
609
ThreadReview: createNativeStackScreen({
610
screen: ReviewSheet,
611
linking: `${THREAD_LINKING_PREFIX}/review`,
apps/mobile/src/components/AppSymbol.tsx
+3
@@ -60,6 +60,7 @@ import IconGitBranch from "@tabler/icons-react-native/IconGitBranch";
60
import IconGitMerge from "@tabler/icons-react-native/IconGitMerge";
61
import IconGitPullRequest from "@tabler/icons-react-native/IconGitPullRequest";
62
import IconHammer from "@tabler/icons-react-native/IconHammer";
63
+import IconHome from "@tabler/icons-react-native/IconHome";
64
import IconInfoCircle from "@tabler/icons-react-native/IconInfoCircle";
65
import IconKeyboard from "@tabler/icons-react-native/IconKeyboard";
66
import IconKeyboardHide from "@tabler/icons-react-native/IconKeyboardHide";
@@ -161,6 +162,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
162
gearshape: IconSettings,
163
globe: IconWorld,
164
hammer: IconHammer,
165
+ house: IconHome,
166
"info.circle": IconInfoCircle,
167
internaldrive: IconDatabase,
168
keyboard: IconKeyboard,
@@ -194,6 +196,7 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
196
"sidebar.right": IconLayoutSidebarRight,
197
"slider.horizontal.3": IconAdjustmentsHorizontal,
198
"square.and.pencil": IconEdit,
199
+ "square.on.square": IconCopy,
200
"square.grid.2x2": IconApps,
201
"square.split.2x1": IconLayoutColumns,
202
star: IconStar,
apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx
new
+309
@@ -0,0 +1,309 @@
1
+import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
2
+import { createNativeStackNavigator } from "@react-navigation/native-stack";
3
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4
+import * as Cause from "effect/Cause";
5
+import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
6
+import { ActivityIndicator, Alert, AppState, Platform, Pressable, View } from "react-native";
7
+import { useSafeAreaInsets } from "react-native-safe-area-context";
8
+
9
+import { AppText } from "../../components/AppText";
10
+import { ScreenHeader, type ScreenHeaderMenuItem } from "../../components/ScreenHeader";
11
+import { NativeHeaderToolbar } from "../../native/StackHeader";
12
+import { deviceEnvironment, refreshDeviceHubAccess, useDeviceHubAccess } from "../../state/device";
13
+import { useEnvironmentQuery } from "../../state/query";
14
+import { useAtomCommand } from "../../state/use-atom-command";
15
+import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
16
+import { DeviceStreamWebView, type DeviceStreamRef } from "./DeviceStreamWebView";
17
+import {
18
+ selectedThreadDevicePreview,
19
+ threadDevicePreviews,
20
+ type ThreadDevicePreview,
21
+} from "./threadDevicePreviews";
22
+
23
+const DevicePreviewStack = createNativeStackNavigator<{ DevicePreview: undefined }>();
24
+
25
+type DevicePreviewRouteScreenProps = StaticScreenProps<{
26
+ readonly environmentId: string;
27
+ readonly threadId: string;
28
+}>;
29
+
30
+/** The nested native stack supplies the navigation bar inside the modal. */
31
+export function DevicePreviewRouteScreen({ route }: DevicePreviewRouteScreenProps) {
32
+ const navigation = useNavigation();
33
+ const onClose = useCallback(() => navigation.goBack(), [navigation]);
34
+ return (
35
+ <View collapsable={false} className="flex-1 bg-sheet">
36
+ <DevicePreviewStack.Navigator
37
+ screenOptions={{
38
+ headerShown: Platform.OS === "ios",
39
+ headerBackVisible: false,
40
+ headerShadowVisible: false,
41
+ headerTransparent: false,
42
+ headerTitleStyle: { fontSize: 17, fontWeight: "600" },
43
+ }}
44
+ >
45
+ <DevicePreviewStack.Screen name="DevicePreview">
46
+ {() => (
47
+ <DevicePreviewScreen
48
+ environmentId={EnvironmentId.make(route.params.environmentId)}
49
+ threadId={ThreadId.make(route.params.threadId)}
50
+ onClose={onClose}
51
+ />
52
+ )}
53
+ </DevicePreviewStack.Screen>
54
+ </DevicePreviewStack.Navigator>
55
+ </View>
56
+ );
57
+}
58
+
59
+function DevicePreviewScreen({
60
+ environmentId,
61
+ threadId,
62
+ onClose,
63
+}: {
64
+ readonly environmentId: EnvironmentId;
65
+ readonly threadId: ThreadId;
66
+ readonly onClose: () => void;
67
+}) {
68
+ const insets = useSafeAreaInsets();
69
+ const { themeVariables } = useAppearancePreferences();
70
+ const focused = useIsFocused();
71
+ const [foreground, setForeground] = useState(AppState.currentState === "active");
72
+ const [selectedKey, setSelectedKey] = useState<string | null>(null);
73
+ const [inputConnected, setInputConnected] = useState(false);
74
+ const [streamAttempt, setStreamAttempt] = useState(0);
75
+ const [shuttingDown, setShuttingDown] = useState(false);
76
+ const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false });
77
+ const streamRef = useRef<DeviceStreamRef>(null);
78
+ const state = useEnvironmentQuery(deviceEnvironment.state({ environmentId, input: {} }));
79
+ const previews = useMemo(
80
+ () => threadDevicePreviews(state.data, threadId),
81
+ [state.data, threadId],
82
+ );
83
+ const preview = selectedThreadDevicePreview(previews, selectedKey);
84
+ const onInputConnected = useCallback(
85
+ async (connected: boolean) => setInputConnected(connected),
86
+ [],
87
+ );
88
+ useEffect(() => {
89
+ const subscription = AppState.addEventListener("change", (state) =>
90
+ setForeground(state === "active"),
91
+ );
92
+ return () => subscription.remove();
93
+ }, []);
94
+ useEffect(() => {
95
+ if (focused && state.data !== null && previews.length === 0) onClose();
96
+ }, [focused, state.data, previews.length, onClose]);
97
+
98
+ const shutDownDevice = async () => {
99
+ if (!preview || shuttingDown) return;
100
+ setShuttingDown(true);
101
+ try {
102
+ const result = await shutdown({
103
+ environmentId,
104
+ input: {
105
+ hostId: preview.session.hostId,
106
+ deviceId: preview.session.deviceId,
107
+ platform: preview.session.platform,
108
+ },
109
+ });
110
+ if (result._tag === "Failure") {
111
+ Alert.alert("Could not shut down device", String(Cause.squash(result.cause)));
112
+ }
113
+ } finally {
114
+ setShuttingDown(false);
115
+ }
116
+ };
117
+
118
+ const controls: ScreenHeaderMenuItem[] = [
119
+ {
120
+ id: "reload",
121
+ title: "Reload stream",
122
+ icon: "arrow.clockwise",
123
+ disabled: !preview || shuttingDown,
124
+ onPress: () => {
125
+ setInputConnected(false);
126
+ setStreamAttempt((attempt) => attempt + 1);
127
+ },
128
+ },
129
+ ...(preview?.session.platform === "android"
130
+ ? [
131
+ {
132
+ id: "back",
133
+ title: "Back",
134
+ icon: "arrow.left",
135
+ disabled: !inputConnected,
136
+ onPress: () => streamRef.current?.back(),
137
+ },
138
+ ]
139
+ : []),
140
+ {
141
+ id: "app-switcher",
142
+ title: "App switcher",
143
+ icon: "square.on.square",
144
+ disabled: !inputConnected,
145
+ onPress: () => streamRef.current?.appSwitcher(),
146
+ },
147
+ ...(preview?.session.platform === "ios"
148
+ ? [
149
+ {
150
+ id: "rotate",
151
+ title: "Rotate device",
152
+ icon: "arrow.clockwise",
153
+ disabled: !inputConnected,
154
+ onPress: () => streamRef.current?.rotate(),
155
+ },
156
+ ]
157
+ : []),
158
+ {
159
+ id: "shutdown",
160
+ title: shuttingDown ? "Shutting down…" : "Shut down device",
161
+ icon: "power",
162
+ disabled: !preview || shuttingDown,
163
+ onPress: () => void shutDownDevice(),
164
+ },
165
+ ];
166
+ return (
167
+ <View className="flex-1 bg-sheet" style={{ paddingBottom: insets.bottom }}>
168
+ <ScreenHeader
169
+ title={preview?.name ?? "Devices"}
170
+ sidebar={false}
171
+ onBack={onClose}
172
+ options={{ headerBackVisible: false }}
173
+ actions={[
174
+ {
175
+ accessibilityLabel: "Home",
176
+ icon: "house",
177
+ disabled: !inputConnected,
178
+ onPress: () => streamRef.current?.home(),
179
+ },
180
+ ]}
181
+ menus={[
182
+ {
183
+ title: "Device options",
184
+ icon: "ellipsis",
185
+ items: [
186
+ ...(previews.length > 1
187
+ ? [
188
+ {
189
+ id: "devices",
190
+ title: "Devices",
191
+ inline: true,
192
+ items: previews.map((device) => ({
193
+ id: device.key,
194
+ title: device.name,
195
+ subtitle: device.description,
196
+ selected: device.key === preview?.key,
197
+ onPress: () => setSelectedKey(device.key),
198
+ })),
199
+ },
200
+ ]
201
+ : []),
202
+ ...controls,
203
+ ],
204
+ },
205
+ ]}
206
+ />
207
+ {Platform.OS === "ios" ? (
208
+ <NativeHeaderToolbar placement="left">
209
+ <NativeHeaderToolbar.Button
210
+ icon="xmark"
211
+ accessibilityLabel="Close device preview"
212
+ onPress={onClose}
213
+ separateBackground
214
+ />
215
+ </NativeHeaderToolbar>
216
+ ) : null}
217
+ {preview && focused && foreground ? (
218
+ <OpenDevicePreview
219
+ key={`${preview.key}:${streamAttempt}`}
220
+ environmentId={environmentId}
221
+ preview={preview}
222
+ streamRef={streamRef}
223
+ onInputConnected={onInputConnected}
224
+ />
225
+ ) : (
226
+ <View className="flex-1 items-center justify-center gap-4 px-6">
227
+ {state.error ? (
228
+ <>
229
+ <AppText selectable className="text-center text-sm text-foreground-muted">
230
+ {state.error}
231
+ </AppText>
232
+ <Pressable
233
+ accessibilityRole="button"
234
+ className="rounded-full bg-subtle px-6 py-3"
235
+ onPress={state.refresh}
236
+ >
237
+ <AppText>Retry</AppText>
238
+ </Pressable>
239
+ </>
240
+ ) : focused && foreground ? (
241
+ <ActivityIndicator color={themeVariables["--color-icon"]} />
242
+ ) : null}
243
+ </View>
244
+ )}
245
+ </View>
246
+ );
247
+}
248
+
249
+function OpenDevicePreview({
250
+ environmentId,
251
+ preview,
252
+ streamRef,
253
+ onInputConnected,
254
+}: {
255
+ readonly environmentId: EnvironmentId;
256
+ readonly preview: ThreadDevicePreview;
257
+ readonly streamRef: RefObject<DeviceStreamRef | null>;
258
+ readonly onInputConnected: (connected: boolean) => Promise<void>;
259
+}) {
260
+ const { session } = preview;
261
+ const { themeVariables } = useAppearancePreferences();
262
+ const { access, error, refresh } = useDeviceHubAccess(environmentId, session.hostId);
263
+ const onUnauthorized = useCallback(
264
+ async () => refreshDeviceHubAccess(environmentId),
265
+ [environmentId],
266
+ );
267
+ useEffect(() => {
268
+ refreshDeviceHubAccess(environmentId);
269
+ return () => void onInputConnected(false);
270
+ }, [environmentId, onInputConnected]);
271
+ return access ? (
272
+ <DeviceStreamWebView
273
+ ref={streamRef}
274
+ access={access}
275
+ platform={session.platform}
276
+ deviceId={session.deviceId}
277
+ colors={{
278
+ background: themeVariables["--color-sheet-solid"],
279
+ foreground: themeVariables["--color-foreground"],
280
+ muted: themeVariables["--color-foreground-muted"],
281
+ buttonBackground: themeVariables["--color-subtle"],
282
+ }}
283
+ onUnauthorized={onUnauthorized}
284
+ onInputConnected={onInputConnected}
285
+ />
286
+ ) : (
287
+ <View className="flex-1 items-center justify-center gap-4 px-6">
288
+ {error ? (
289
+ <>
290
+ <AppText selectable className="text-center text-sm text-foreground-muted">
291
+ {error}
292
+ </AppText>
293
+ <Pressable
294
+ accessibilityRole="button"
295
+ className="rounded-full bg-subtle px-6 py-3"
296
+ onPress={refresh}
297
+ >
298
+ <AppText>Retry</AppText>
299
+ </Pressable>
300
+ </>
301
+ ) : (
302
+ <>
303
+ <ActivityIndicator color={themeVariables["--color-icon"]} />
304
+ <AppText className="text-sm text-foreground-muted">Connecting to device...</AppText>
305
+ </>
306
+ )}
307
+ </View>
308
+ );
309
+}
apps/mobile/src/features/devices/DeviceStreamWebView.tsx
new
+109
@@ -0,0 +1,109 @@
1
+import deviceStreamScript from "@t3tools/mobile-device-stream";
2
+import { useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, type Ref } from "react";
3
+import { Platform } from "react-native";
4
+import { WebView } from "react-native-webview";
5
+
6
+import {
7
+ deviceStreamDocument,
8
+ deviceStreamMessage,
9
+ type DeviceStreamConfiguration,
10
+} from "./device-stream-document";
11
+
12
+export interface DeviceStreamRef {
13
+ home: () => void;
14
+ back: () => void;
15
+ appSwitcher: () => void;
16
+ rotate: () => void;
17
+}
18
+
19
+type NativeStreamBridge = {
20
+ readonly ref?: Ref<DeviceStreamRef>;
21
+ readonly onUnauthorized: () => Promise<void>;
22
+ readonly onInputConnected: (connected: boolean) => Promise<void>;
23
+};
24
+
25
+export function DeviceStreamWebView({
26
+ ref,
27
+ ...props
28
+}: DeviceStreamConfiguration & NativeStreamBridge) {
29
+ const [attempt, setAttempt] = useState(0);
30
+ const configuration = JSON.stringify({
31
+ access: props.access,
32
+ platform: props.platform,
33
+ deviceId: props.deviceId,
34
+ colors: props.colors,
35
+ });
36
+ return (
37
+ <DeviceStreamDocumentView
38
+ key={`${attempt}:${configuration}`}
39
+ ref={ref}
40
+ configuration={configuration}
41
+ background={props.colors.background}
42
+ onUnauthorized={props.onUnauthorized}
43
+ onInputConnected={props.onInputConnected}
44
+ onRetry={() => setAttempt((attempt) => attempt + 1)}
45
+ />
46
+ );
47
+}
48
+
49
+function DeviceStreamDocumentView({
50
+ ref,
51
+ configuration,
52
+ background,
53
+ onUnauthorized,
54
+ onInputConnected,
55
+ onRetry,
56
+}: NativeStreamBridge & {
57
+ readonly configuration: string;
58
+ readonly background: string;
59
+ readonly onRetry: () => void;
60
+}) {
61
+ const webView = useRef<WebView>(null);
62
+ const source = useMemo(
63
+ () => ({
64
+ html: deviceStreamDocument(configuration, deviceStreamScript),
65
+ // Android WebCodecs needs a secure document; streams still use the environment's URLs.
66
+ baseUrl: Platform.OS === "android" ? "https://localhost/" : "file:///",
67
+ }),
68
+ [configuration],
69
+ );
70
+ const command = (button: keyof DeviceStreamRef) => {
71
+ webView.current?.injectJavaScript(
72
+ `window.T3DeviceStream?.command(${JSON.stringify(button)}); true;`,
73
+ );
74
+ };
75
+ useImperativeHandle(ref, () => ({
76
+ home: () => command("home"),
77
+ back: () => command("back"),
78
+ appSwitcher: () => command("appSwitcher"),
79
+ rotate: () => command("rotate"),
80
+ }));
81
+ useLayoutEffect(() => {
82
+ const view = webView.current;
83
+ return () => view?.injectJavaScript("window.T3DeviceStream?.stop(); true;");
84
+ }, []);
85
+ return (
86
+ <WebView
87
+ ref={webView}
88
+ source={source}
89
+ originWhitelist={["*"]}
90
+ scrollEnabled={false}
91
+ bounces={false}
92
+ mixedContentMode="always"
93
+ allowUniversalAccessFromFileURLs
94
+ contentInsetAdjustmentBehavior="never"
95
+ setSupportMultipleWindows={false}
96
+ style={{ flex: 1, backgroundColor: background }}
97
+ onLoadStart={() => void onInputConnected(false)}
98
+ onShouldStartLoadWithRequest={(request) =>
99
+ request.url === "about:blank" || request.url === source.baseUrl
100
+ }
101
+ onMessage={(event) => {
102
+ const message = deviceStreamMessage(event.nativeEvent.data);
103
+ if (message?.type === "unauthorized") void onUnauthorized();
104
+ else if (message?.type === "input") void onInputConnected(message.connected);
105
+ else if (message?.type === "retry") onRetry();
106
+ }}
107
+ />
108
+ );
109
+}
apps/mobile/src/features/devices/device-preview-button.tsx
new
+41
@@ -0,0 +1,41 @@
1
+import { Pressable, View } from "react-native";
2
+
3
+import { AppText } from "../../components/AppText";
4
+import { SymbolView } from "../../components/AppSymbol";
5
+
6
+export function DevicePreviewButton(props: {
7
+ readonly count: number;
8
+ readonly onPress: () => void;
9
+ readonly compact?: boolean;
10
+}) {
11
+ const compact = props.compact ?? true;
12
+ return (
13
+ <Pressable
14
+ accessibilityRole="button"
15
+ accessibilityLabel={props.count === 1 ? "View device" : `View ${props.count} devices`}
16
+ accessibilityHint="Watch and control devices open in this thread"
17
+ onPress={props.onPress}
18
+ className={
19
+ compact
20
+ ? "size-11 shrink-0 items-center justify-center rounded-full active:bg-subtle"
21
+ : "h-11 shrink-0 flex-row items-center justify-center gap-2 rounded-full px-4 active:bg-subtle"
22
+ }
23
+ >
24
+ <SymbolView
25
+ name={{ ios: "iphone", android: "smartphone" }}
26
+ size={20}
27
+ tintColorClassName="accent-icon"
28
+ type="monochrome"
29
+ />
30
+ {!compact ? (
31
+ <AppText className="font-t3-medium text-xs text-foreground">
32
+ {props.count === 1 ? "One device open" : `${props.count} devices open`}
33
+ </AppText>
34
+ ) : props.count > 1 ? (
35
+ <View className="absolute right-0.5 top-0.5 min-w-4 items-center rounded-full bg-primary px-1">
36
+ <AppText className="text-2xs font-t3-bold text-primary-foreground">{props.count}</AppText>
37
+ </View>
38
+ ) : null}
39
+ </Pressable>
40
+ );
41
+}
apps/mobile/src/features/devices/device-stream-document.test.ts
new
+49
@@ -0,0 +1,49 @@
1
+import * as NodeVM from "node:vm";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { deviceStreamDocument, deviceStreamMessage } from "./device-stream-document";
5
+
6
+describe("native device stream document", () => {
7
+ it("keeps ticket and device values from terminating the embedded script", () => {
8
+ const deviceId = '</script><script>alert("device")</script>';
9
+ const configuration = JSON.stringify({ deviceId, ticket: "<ticket>" });
10
+ const html = deviceStreamDocument(
11
+ configuration,
12
+ "var T3DeviceStream={start(input){return input}};",
13
+ );
14
+ const script = html.match(/<script>([\s\S]*)<\/script>/)?.[1];
15
+ expect(html.match(/<script>/g)).toHaveLength(1);
16
+ const input: unknown = NodeVM.runInNewContext(script!);
17
+ expect(input).toEqual({ deviceId, ticket: "<ticket>" });
18
+ });
19
+
20
+ it("preserves script strings containing an HTML closing delimiter", () => {
21
+ const html = deviceStreamDocument("{}", 'var text="</script>";');
22
+ expect(html.match(/<\/script>/g)).toHaveLength(1);
23
+ expect(html).toContain('var text="<\\/script>";');
24
+ });
25
+});
26
+
27
+describe("native device stream messages", () => {
28
+ it("accepts authentication renewal and input connection changes", () => {
29
+ expect(deviceStreamMessage('{"type":"unauthorized"}')).toEqual({ type: "unauthorized" });
30
+ expect(deviceStreamMessage('{"type":"input","connected":true}')).toEqual({
31
+ type: "input",
32
+ connected: true,
33
+ });
34
+ expect(deviceStreamMessage('{"type":"input","connected":false}')).toEqual({
35
+ type: "input",
36
+ connected: false,
37
+ });
38
+ expect(deviceStreamMessage('{"type":"retry"}')).toEqual({ type: "retry" });
39
+ });
40
+
41
+ it.each([
42
+ "invalid JSON",
43
+ "null",
44
+ '"input"',
45
+ "{}",
46
+ '{"type":"input","connected":"yes"}',
47
+ '{"type":"unknown"}',
48
+ ])("ignores invalid bridge messages: %s", (data) => expect(deviceStreamMessage(data)).toBeNull());
49
+});
apps/mobile/src/features/devices/device-stream-document.ts
new
+41
@@ -0,0 +1,41 @@
1
+import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access";
2
+import type { DevicePlatform } from "@t3tools/contracts";
3
+
4
+export interface DeviceStreamConfiguration {
5
+ readonly access: DeviceHubAccess;
6
+ readonly platform: DevicePlatform;
7
+ readonly deviceId: string;
8
+ readonly colors: {
9
+ readonly background: string;
10
+ readonly foreground: string;
11
+ readonly muted: string;
12
+ readonly buttonBackground: string;
13
+ };
14
+}
15
+
16
+export function deviceStreamDocument(configuration: string, script: string) {
17
+ // Tickets and device names are data, including any HTML delimiter characters.
18
+ const safeConfiguration = configuration.replace(/</g, "\\u003c");
19
+ const safeScript = script.replace(/<\/script/gi, "<\\/script");
20
+ return `<!doctype html><html><head><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"></head><body><script>${safeScript}\nT3DeviceStream.start(${safeConfiguration});</script></body></html>`;
21
+}
22
+
23
+export function deviceStreamMessage(data: string) {
24
+ try {
25
+ const message: unknown = JSON.parse(data);
26
+ if (typeof message !== "object" || message === null || !("type" in message)) return null;
27
+ if (message.type === "unauthorized" || message.type === "retry") {
28
+ return { type: message.type } as const;
29
+ }
30
+ if (
31
+ message.type === "input" &&
32
+ "connected" in message &&
33
+ typeof message.connected === "boolean"
34
+ ) {
35
+ return { type: message.type, connected: message.connected } as const;
36
+ }
37
+ } catch {
38
+ // Ignore messages that are not part of the stream bridge.
39
+ }
40
+ return null;
41
+}
apps/mobile/src/features/devices/device-stream.browser.ts
new
+223
@@ -0,0 +1,223 @@
1
+import {
2
+ createDeviceStreamClient,
3
+ type DeviceScreenSize,
4
+} from "@t3tools/client-runtime/device/stream";
5
+
6
+import type { DeviceStreamConfiguration } from "./device-stream-document";
7
+
8
+declare global {
9
+ interface Window {
10
+ ReactNativeWebView: { postMessage: (message: string) => void };
11
+ }
12
+}
13
+
14
+let activeClient: ReturnType<typeof createDeviceStreamClient> | null = null;
15
+let activeImage: HTMLImageElement | null = null;
16
+
17
+export function stop() {
18
+ activeClient?.stop();
19
+ activeClient = null;
20
+ activeImage?.removeAttribute("src");
21
+ activeImage = null;
22
+}
23
+
24
+export function command(button: "home" | "back" | "appSwitcher" | "rotate") {
25
+ if (button === "rotate") activeClient?.rotate();
26
+ else activeClient?.pressButton(button);
27
+}
28
+
29
+/** Bundled into the existing native WebView without React or Expo's web runtime. */
30
+export function start(configuration: DeviceStreamConfiguration) {
31
+ stop();
32
+ // oxlint-disable-next-line unicorn/require-post-message-target-origin -- The native WebView bridge takes one string.
33
+ const post = (message: object) => window.ReactNativeWebView.postMessage(JSON.stringify(message));
34
+ const { colors, platform } = configuration;
35
+ Object.assign(document.documentElement.style, { height: "100%", overflow: "hidden" });
36
+ Object.assign(document.body.style, {
37
+ margin: "0",
38
+ height: "100%",
39
+ overflow: "hidden",
40
+ background: colors.background,
41
+ color: colors.foreground,
42
+ fontFamily: "system-ui",
43
+ });
44
+ const container = document.createElement("div");
45
+ Object.assign(container.style, {
46
+ position: "fixed",
47
+ inset: "0",
48
+ containerType: "size",
49
+ display: "flex",
50
+ alignItems: "center",
51
+ justifyContent: "center",
52
+ });
53
+ const frame = document.createElement("div");
54
+ frame.setAttribute("role", "application");
55
+ frame.setAttribute(
56
+ "aria-label",
57
+ platform === "ios" ? "iOS Simulator screen" : "Android Emulator screen",
58
+ );
59
+ frame.tabIndex = 0;
60
+ Object.assign(frame.style, {
61
+ position: "relative",
62
+ touchAction: "none",
63
+ userSelect: "none",
64
+ webkitUserSelect: "none",
65
+ webkitTouchCallout: "none",
66
+ outline: "none",
67
+ });
68
+ const canvas = document.createElement("canvas");
69
+ const image = document.createElement("img");
70
+ image.alt = "";
71
+ image.draggable = false;
72
+ image.style.display = "none";
73
+ const overlay = document.createElement("div");
74
+ overlay.setAttribute("role", "status");
75
+ Object.assign(overlay.style, {
76
+ position: "fixed",
77
+ inset: "0",
78
+ display: "flex",
79
+ flexDirection: "column",
80
+ alignItems: "center",
81
+ justifyContent: "center",
82
+ gap: "16px",
83
+ padding: "24px",
84
+ textAlign: "center",
85
+ background: colors.background,
86
+ });
87
+ const detail = document.createElement("span");
88
+ const retry = document.createElement("button");
89
+ retry.textContent = "Retry";
90
+ Object.assign(retry.style, {
91
+ padding: "12px 24px",
92
+ borderRadius: "20px",
93
+ border: "0",
94
+ background: colors.buttonBackground,
95
+ color: colors.foreground,
96
+ font: "inherit",
97
+ display: "none",
98
+ });
99
+ retry.addEventListener("click", () => post({ type: "retry" }));
100
+ overlay.append(detail, retry);
101
+ const inputStatus = document.createElement("div");
102
+ inputStatus.setAttribute("role", "status");
103
+ inputStatus.textContent = "Reconnecting device controls...";
104
+ Object.assign(inputStatus.style, {
105
+ position: "fixed",
106
+ bottom: "12px",
107
+ left: "0",
108
+ right: "0",
109
+ textAlign: "center",
110
+ pointerEvents: "none",
111
+ fontSize: "13px",
112
+ color: colors.muted,
113
+ background: colors.background,
114
+ });
115
+ frame.append(canvas, image);
116
+ container.append(frame);
117
+ document.body.replaceChildren(container, overlay, inputStatus);
118
+
119
+ let pointerId: number | null = null;
120
+ let inputConnected = false;
121
+ let streaming = false;
122
+ const layout = (screen: DeviceScreenSize | null) => {
123
+ const landscape =
124
+ screen?.orientation === "landscape_left" || screen?.orientation === "landscape_right";
125
+ const aspect = screen
126
+ ? landscape
127
+ ? Math.max(screen.width, screen.height) / Math.min(screen.width, screen.height)
128
+ : Math.min(screen.width, screen.height) / Math.max(screen.width, screen.height)
129
+ : 9 / 19.5;
130
+ const rotation =
131
+ platform === "ios" && screen && screen.width <= screen.height
132
+ ? screen.orientation === "landscape_left"
133
+ ? 90
134
+ : screen.orientation === "landscape_right"
135
+ ? -90
136
+ : screen.orientation === "portrait_upside_down"
137
+ ? 180
138
+ : 0
139
+ : 0;
140
+ const sideways = Math.abs(rotation) === 90;
141
+ frame.style.width = `min(100cqw, ${aspect * 100}cqh)`;
142
+ frame.style.height = `min(100cqh, ${100 / aspect}cqw)`;
143
+ for (const media of [canvas, image]) {
144
+ Object.assign(media.style, {
145
+ position: "absolute",
146
+ width: sideways ? `${100 / aspect}%` : "100%",
147
+ height: sideways ? `${100 * aspect}%` : "100%",
148
+ left: "50%",
149
+ top: "50%",
150
+ transform: `translate(-50%, -50%) rotate(${rotation}deg)`,
151
+ pointerEvents: "none",
152
+ });
153
+ }
154
+ };
155
+ layout(null);
156
+ const unauthorized = () => {
157
+ if (activeClient === client) post({ type: "unauthorized" });
158
+ };
159
+ const client = createDeviceStreamClient(
160
+ { ...configuration, preferMjpeg: platform === "ios" },
161
+ canvas,
162
+ {
163
+ onStatus: (status, message) => {
164
+ streaming = status === "streaming";
165
+ overlay.style.display = streaming ? "none" : "flex";
166
+ inputStatus.style.display = streaming && !inputConnected ? "block" : "none";
167
+ detail.textContent =
168
+ status === "error" ? (message ?? "Device stream failed.") : "Connecting to device...";
169
+ retry.style.display = status === "error" ? "block" : "none";
170
+ },
171
+ onScreen: layout,
172
+ onMjpegFallback: (url) => {
173
+ canvas.style.display = "none";
174
+ image.style.display = "block";
175
+ image.src = url;
176
+ },
177
+ onUnauthorized: unauthorized,
178
+ onInputConnected: (connected) => {
179
+ inputConnected = connected;
180
+ inputStatus.style.display = streaming && !connected ? "block" : "none";
181
+ post({ type: "input", connected });
182
+ },
183
+ },
184
+ );
185
+ activeClient = client;
186
+ activeImage = image;
187
+ image.addEventListener("error", unauthorized);
188
+ const touch = (event: PointerEvent, phase: "begin" | "move" | "end") => {
189
+ const rect = frame.getBoundingClientRect();
190
+ client.sendTouch(
191
+ phase,
192
+ Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)),
193
+ Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height)),
194
+ );
195
+ };
196
+ frame.addEventListener("pointerdown", (event) => {
197
+ if (!inputConnected || pointerId !== null) return;
198
+ event.preventDefault();
199
+ pointerId = event.pointerId;
200
+ frame.setPointerCapture(event.pointerId);
201
+ frame.focus();
202
+ touch(event, "begin");
203
+ });
204
+ frame.addEventListener("pointermove", (event) => {
205
+ if (pointerId === event.pointerId) touch(event, "move");
206
+ });
207
+ const endTouch = (event: PointerEvent) => {
208
+ if (pointerId !== event.pointerId) return;
209
+ pointerId = null;
210
+ touch(event, "end");
211
+ };
212
+ frame.addEventListener("pointerup", endTouch);
213
+ frame.addEventListener("pointercancel", endTouch);
214
+ frame.addEventListener("lostpointercapture", endTouch);
215
+ frame.addEventListener("keydown", (event) => {
216
+ event.preventDefault();
217
+ client.sendKey(event, "down");
218
+ });
219
+ frame.addEventListener("keyup", (event) => client.sendKey(event, "up"));
220
+ window.addEventListener("pagehide", stop, { once: true });
221
+ post({ type: "input", connected: false });
222
+ client.start();
223
+}
apps/mobile/src/features/devices/threadDevicePreviews.test.ts
new
+106
@@ -0,0 +1,106 @@
1
+import { ThreadId, type DeviceServiceState } from "@t3tools/contracts";
2
+import { describe, expect, it } from "vite-plus/test";
3
+
4
+import { selectedThreadDevicePreview, threadDevicePreviews } from "./threadDevicePreviews";
5
+
6
+const threadId = ThreadId.make("thread");
7
+const state: DeviceServiceState = {
8
+ hosts: [
9
+ {
10
+ id: "local",
11
+ kind: "local",
12
+ label: "Local",
13
+ platforms: [],
14
+ hubInstalled: true,
15
+ agentDeviceInstalled: true,
16
+ },
17
+ {
18
+ id: "remote",
19
+ kind: "ssh",
20
+ label: "Mac mini",
21
+ platforms: [],
22
+ hubInstalled: true,
23
+ agentDeviceInstalled: true,
24
+ },
25
+ ],
26
+ hostStatus: "ready",
27
+ hostStatuses: {},
28
+ devices: [
29
+ {
30
+ hostId: "local",
31
+ id: "emulator-5554",
32
+ platform: "android",
33
+ name: "Pixel 9",
34
+ version: "Android 16",
35
+ booted: true,
36
+ physical: false,
37
+ },
38
+ {
39
+ hostId: "remote",
40
+ id: "emulator-5554",
41
+ platform: "android",
42
+ name: "Pixel 8",
43
+ version: "Android 15",
44
+ booted: true,
45
+ physical: false,
46
+ },
47
+ ],
48
+ sessions: [
49
+ {
50
+ threadId,
51
+ hostId: "local",
52
+ deviceId: "emulator-5554",
53
+ platform: "android",
54
+ openedAt: "2026-09-18T00:00:00Z",
55
+ },
56
+ {
57
+ threadId,
58
+ hostId: "remote",
59
+ deviceId: "emulator-5554",
60
+ platform: "android",
61
+ openedAt: "2026-09-18T00:01:00Z",
62
+ },
63
+ {
64
+ threadId: ThreadId.make("another-thread"),
65
+ hostId: "local",
66
+ deviceId: "iphone",
67
+ platform: "ios",
68
+ openedAt: "2026-09-18T00:02:00Z",
69
+ },
70
+ ],
71
+ onboardingCompleted: true,
72
+ agentAccessEnabled: true,
73
+ hubBasePath: "/api/device-hub",
74
+ revision: 1,
75
+};
76
+
77
+describe("thread device previews", () => {
78
+ it("keeps device names and selection distinct when hosts have the same Android serial", () => {
79
+ const previews = threadDevicePreviews(state, threadId);
80
+ expect(previews.map((preview) => preview.name)).toEqual(["Pixel 9", "Pixel 8"]);
81
+ expect(new Set(previews.map((preview) => preview.key)).size).toBe(2);
82
+ expect(selectedThreadDevicePreview(previews, previews[1]!.key)?.description).toBe(
83
+ "Android 15 · Mac mini",
84
+ );
85
+ });
86
+
87
+ it("selects another open device when the agent closes the selected session", () => {
88
+ const previews = threadDevicePreviews(state, threadId);
89
+ const selectedKey = previews[1]!.key;
90
+ const afterClose = threadDevicePreviews({ ...state, sessions: [state.sessions[0]!] }, threadId);
91
+ expect(selectedThreadDevicePreview(afterClose, selectedKey)?.name).toBe("Pixel 9");
92
+ expect(selectedThreadDevicePreview([], selectedKey)).toBeNull();
93
+ });
94
+
95
+ it("can view an open session before device discovery metadata arrives", () => {
96
+ const previews = threadDevicePreviews({ ...state, hosts: [], devices: [] }, threadId);
97
+ expect(previews[0]?.name).toBe("Android Emulator");
98
+ expect(previews[0]?.session.deviceId).toBe("emulator-5554");
99
+ expect(previews[0]?.description).toBe("");
100
+ });
101
+
102
+ it("offers no devices before state arrives or in a thread without sessions", () => {
103
+ expect(threadDevicePreviews(null, threadId)).toEqual([]);
104
+ expect(threadDevicePreviews(state, ThreadId.make("empty-thread"))).toEqual([]);
105
+ });
106
+});
apps/mobile/src/features/devices/threadDevicePreviews.ts
new
+28
@@ -0,0 +1,28 @@
1
+import type { DeviceServiceState, ThreadId } from "@t3tools/contracts";
2
+
3
+/** Host identity is part of the selection because Android serials repeat across hosts. */
4
+export function threadDevicePreviews(state: DeviceServiceState | null, threadId: ThreadId) {
5
+ return (state?.sessions ?? [])
6
+ .filter((session) => session.threadId === threadId)
7
+ .map((session) => {
8
+ const device = state?.devices.find(
9
+ (device) => device.hostId === session.hostId && device.id === session.deviceId,
10
+ );
11
+ const host = state?.hosts.find((host) => host.id === session.hostId);
12
+ return {
13
+ key: JSON.stringify([session.hostId, session.deviceId]),
14
+ session,
15
+ name: device?.name ?? (session.platform === "ios" ? "iOS Simulator" : "Android Emulator"),
16
+ description: [device?.version, host?.label].filter(Boolean).join(" · "),
17
+ };
18
+ });
19
+}
20
+
21
+export type ThreadDevicePreview = ReturnType<typeof threadDevicePreviews>[number];
22
+
23
+export function selectedThreadDevicePreview(
24
+ previews: ReadonlyArray<ThreadDevicePreview>,
25
+ selectedKey: string | null,
26
+) {
27
+ return previews.find((preview) => preview.key === selectedKey) ?? previews[0] ?? null;
28
+}
apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+25
@@ -13,6 +13,7 @@ import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp
13
import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";
14
import type { LegendListRef } from "@legendapp/list/react-native";
15
import { HeaderHeightContext } from "@react-navigation/elements";
16
+import { useNavigation } from "@react-navigation/native";
17
import type {
18
ApprovalRequestId,
19
EnvironmentId,
@@ -72,6 +73,9 @@ import type { DraftComposerAttachment } from "../../lib/composerImages";
73
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
74
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
75
import { editPendingThreadMessage } from "../../state/edit-pending-thread-message";
76
+import { deviceEnvironment } from "../../state/device";
77
+import { useEnvironmentQuery } from "../../state/query";
78
+import { threadDevicePreviews } from "../devices/threadDevicePreviews";
79
import type { QueuedThreadMessage } from "../../state/thread-outbox-model";
80
import { scopedThreadKey } from "../../lib/scopedEntities";
81
import type {
@@ -259,6 +263,21 @@ const USER_INPUT_TOGGLE_TIMING = {
263
};
264
265
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
266
+ const navigation = useNavigation();
267
+ const deviceState = useEnvironmentQuery(
268
+ deviceEnvironment.state({ environmentId: props.environmentId, input: {} }),
269
+ );
270
+ const devicePreviews = useMemo(
271
+ () => threadDevicePreviews(deviceState.data, props.selectedThread.id),
272
+ [deviceState.data, props.selectedThread.id],
273
+ );
274
+ const openDevicePreview = useCallback(() => {
275
+ Keyboard.dismiss();
276
+ navigation.navigate("ThreadDevicePreview", {
277
+ environmentId: props.environmentId,
278
+ threadId: props.selectedThread.id,
279
+ });
280
+ }, [navigation, props.environmentId, props.selectedThread.id]);
281
const insets = useSafeAreaInsets();
282
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
283
const liveKeyboardHeight = useKeyboardState((state) => state.height);
@@ -390,6 +409,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
409
// stable when reconnecting hands off to syncing and then to a running turn.
410
const showFloatingStatus =
411
showWorkingControl ||
412
+ devicePreviews.length > 0 ||
413
props.connectionStateLabel !== "connected" ||
414
props.queuedMessages.length > 0 ||
415
props.selectedThreadFeed.some(
@@ -936,6 +956,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
956
<FloatingWorkingControl
957
colorScheme={isDarkMode ? "dark" : "light"}
958
status={floatingStatus}
959
+ devicePreview={
960
+ devicePreviews.length > 0
961
+ ? { count: devicePreviews.length, onPress: openDevicePreview }
962
+ : null
963
+ }
964
showScrollToEnd={showScrollToEndButton}
965
onScrollToEnd={handleScrollToEnd}
966
/>
apps/mobile/src/features/threads/floating-working-control.tsx
+38
-14
@@ -24,6 +24,7 @@ import { AppText as Text } from "../../components/AppText";
24
import { SymbolView } from "../../components/AppSymbol";
25
import { ControlPill } from "../../components/ControlPill";
26
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
27
+import { DevicePreviewButton } from "../devices/device-preview-button";
28
import type { FloatingWorkingStatus } from "./floating-working-status";
29
import { ShimmeringWorkContent } from "./thread-work-log";
30
@@ -63,12 +64,18 @@ export const FLOATING_WORKING_CONTROL_COVERAGE = CONTROL_OVERLAY_OFFSET + CONTRO
64
export function FloatingWorkingControl(props: {
65
readonly colorScheme: "light" | "dark";
66
readonly status: FloatingWorkingStatus | null;
67
+ readonly devicePreview: { readonly count: number; readonly onPress: () => void } | null;
68
readonly showScrollToEnd: boolean;
69
readonly onScrollToEnd: () => void;
70
}) {
71
const { width: windowWidth } = useWindowDimensions();
72
const [overlayWidth, setOverlayWidth] = useState(windowWidth);
71
- const labelWidth = Math.max(0, Math.min(overlayWidth, windowWidth) - CONTROL_HEIGHT - 16);
73
+ const deviceControlWidth = props.devicePreview !== null ? CONTROL_HEIGHT : 0;
74
+ const hasCapsule = props.status !== null || props.devicePreview !== null;
75
+ const labelWidth = Math.max(
76
+ 0,
77
+ Math.min(overlayWidth, windowWidth) - CONTROL_HEIGHT - 16 - deviceControlWidth,
78
+ );
79
const separationProgress = useSharedValue(props.showScrollToEnd ? 1 : 0);
80
81
useEffect(() => {
@@ -111,25 +118,30 @@ export function FloatingWorkingControl(props: {
118
}));
119
// Zero until the first measurement lands, so the capsule never paints around
120
// a label it has not sized to yet.
114
- const capsuleSizerStyle = useAnimatedStyle(() => ({ width: capsuleWidth.value ?? 0 }));
121
+ const capsuleSizerStyle = useAnimatedStyle(() => ({
122
+ width: (capsuleWidth.value ?? 0) + deviceControlWidth,
123
+ }));
124
116
- if (props.status === null && !props.showScrollToEnd) {
125
+ if (!hasCapsule && !props.showScrollToEnd) {
126
return null;
127
}
128
129
// Only the connection label is a button (tap to reconnect); the others
130
// pass touches through to the feed like before.
131
const statusInteractive = props.status?.kind === "connection";
132
+ const capsuleInteractive = statusInteractive || props.devicePreview !== null;
133
// The host stays centered on the capsule, but its measurement constraint
134
// comes from the overlay, independent of the capsule's current width.
125
- const statusContent =
126
- props.status !== null ? (
135
+ const capsuleContent =
136
+ props.status === null && props.devicePreview !== null ? (
137
+ <DevicePreviewButton {...props.devicePreview} compact={false} />
138
+ ) : props.status !== null ? (
139
<>
140
<Animated.View className="h-11" style={capsuleSizerStyle} />
141
<View
130
- pointerEvents="box-none"
142
+ pointerEvents={statusInteractive ? "box-none" : "none"}
143
className="absolute h-11 items-center justify-center"
132
- style={{ width: labelWidth }}
144
+ style={{ width: labelWidth, transform: [{ translateX: -deviceControlWidth / 2 }] }}
145
>
146
<FloatingStatusLabel
147
key={
@@ -141,6 +153,18 @@ export function FloatingWorkingControl(props: {
153
onLayout={handleLabelLayout}
154
/>
155
</View>
156
+ {props.devicePreview !== null ? (
157
+ <>
158
+ <View
159
+ pointerEvents="none"
160
+ className="absolute h-4 w-px bg-border"
161
+ style={{ right: deviceControlWidth }}
162
+ />
163
+ <View className="absolute right-0">
164
+ <DevicePreviewButton {...props.devicePreview} />
165
+ </View>
166
+ </>
167
+ ) : null}
168
</>
169
) : null;
170
@@ -153,7 +177,7 @@ export function FloatingWorkingControl(props: {
177
entering={NATIVE_LIQUID_GLASS_SUPPORTED ? undefined : CONTROL_ENTERING}
178
exiting={NATIVE_LIQUID_GLASS_SUPPORTED ? undefined : CONTROL_EXITING}
179
>
156
- {props.status !== null && NATIVE_LIQUID_GLASS_SUPPORTED ? (
180
+ {hasCapsule && NATIVE_LIQUID_GLASS_SUPPORTED ? (
181
<UniwindGlassContainer
182
spacing={GLASS_MERGE_SPACING}
183
pointerEvents="box-none"
@@ -162,12 +186,12 @@ export function FloatingWorkingControl(props: {
186
<AnimatedGlassView
187
colorScheme={props.colorScheme}
188
glassEffectStyle="regular"
165
- isInteractive={statusInteractive}
166
- pointerEvents={statusInteractive ? "box-none" : "none"}
189
+ isInteractive={capsuleInteractive}
190
+ pointerEvents={capsuleInteractive ? "box-none" : "none"}
191
className="h-11 items-center justify-center overflow-hidden rounded-full"
192
style={capsuleStyle}
193
>
170
- {statusContent}
194
+ {capsuleContent}
195
</AnimatedGlassView>
196
197
<AnimatedGlassView
@@ -185,14 +209,14 @@ export function FloatingWorkingControl(props: {
209
</Animated.View>
210
</AnimatedGlassView>
211
</UniwindGlassContainer>
188
- ) : props.status !== null ? (
212
+ ) : hasCapsule ? (
213
<View pointerEvents="box-none" className="flex-row items-center gap-4">
214
<Animated.View
191
- pointerEvents={statusInteractive ? "box-none" : "none"}
215
+ pointerEvents={capsuleInteractive ? "box-none" : "none"}
216
className="h-11 items-center justify-center overflow-hidden rounded-full border border-border bg-card shadow-md shadow-black/10"
217
style={capsuleStyle}
218
>
195
- {statusContent}
219
+ {capsuleContent}
220
</Animated.View>
221
222
<Animated.View
apps/mobile/src/state/device.ts
new
+44
@@ -0,0 +1,44 @@
1
+import { createDeviceEnvironmentAtoms } from "@t3tools/client-runtime/state/device";
2
+import { resolveDeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
3
+import type { EnvironmentId } from "@t3tools/contracts";
4
+import * as Effect from "effect/Effect";
5
+import * as Option from "effect/Option";
6
+import { Atom } from "effect/unstable/reactivity";
7
+import { useMemo } from "react";
8
+
9
+import { connectionAtomRuntime } from "../connection/runtime";
10
+import { appAtomRegistry } from "./atom-registry";
11
+import { useEnvironmentQuery } from "./query";
12
+import { environmentSession, usePreparedConnection } from "./session";
13
+
14
+export const deviceEnvironment = createDeviceEnvironmentAtoms(connectionAtomRuntime);
15
+
16
+const deviceHubAccessAtom = Atom.family((environmentId: EnvironmentId) =>
17
+ connectionAtomRuntime
18
+ .atom((get) => {
19
+ const prepared = Option.getOrNull(
20
+ get(environmentSession.preparedConnectionValueAtom(environmentId)),
21
+ );
22
+ return prepared === null
23
+ ? Effect.never
24
+ : resolveDeviceHubAccess({ prepared, hubBasePath: "/api/device-hub" });
25
+ })
26
+ .pipe(Atom.setIdleTTL(60_000), Atom.withLabel(`mobile-device-hub-access:${environmentId}`)),
27
+);
28
+
29
+export function refreshDeviceHubAccess(environmentId: EnvironmentId) {
30
+ appAtomRegistry.refresh(deviceHubAccessAtom(environmentId));
31
+}
32
+
33
+export function useDeviceHubAccess(environmentId: EnvironmentId, hostId: string) {
34
+ const prepared = usePreparedConnection(environmentId);
35
+ const query = useEnvironmentQuery(deviceHubAccessAtom(environmentId));
36
+ const access = useMemo(
37
+ () =>
38
+ query.data && query.error === null && Option.isSome(prepared)
39
+ ? { ...query.data, query: { ...query.data.query, hostId } }
40
+ : null,
41
+ [query.data, query.error, prepared, hostId],
42
+ );
43
+ return { access, error: query.error, refresh: query.refresh };
44
+}
apps/mobile/src/types/mobile-device-stream.d.ts
new
+4
@@ -0,0 +1,4 @@
1
+declare module "@t3tools/mobile-device-stream" {
2
+ const script: string;
3
+ export default script;
4
+}
apps/web/src/components/device/DeviceStreamView.test.tsx
+1
-1
@@ -8,7 +8,7 @@ vi.mock("~/state/device", () => ({
8
refreshDeviceHubAccess: vi.fn(),
9
}));
10
const access = { httpBase: "http://test", wsBase: "ws://test", query: {}, credentials: true };
11
-vi.mock("./deviceStream", () => ({
11
+vi.mock("@t3tools/client-runtime/device/stream", () => ({
12
createDeviceStreamClient: (
13
_target: unknown,
14
_canvas: unknown,
apps/web/src/components/device/DeviceStreamView.tsx
+1
-1
@@ -11,7 +11,7 @@ import {
11
type DeviceScreenSize,
12
type DeviceStreamClient,
13
type DeviceStreamStatus,
14
-} from "./deviceStream";
14
+} from "@t3tools/client-runtime/device/stream";
15
16
const AX_POLL_INTERVAL_MS = 2_000;
17
apps/web/src/components/device/deviceStream.test.ts
+166
-1
@@ -6,7 +6,7 @@ import {
6
avcCodecString,
7
parseSemuPacket,
8
scanAccessUnit,
9
-} from "./deviceStream";
9
+} from "@t3tools/client-runtime/device/stream";
10
11
const envelope = (tag: number, payload: number[]) => {
12
const length = 1 + payload.length;
@@ -43,6 +43,171 @@ describe("AvccDemuxer", () => {
43
});
44
});
45
46
+describe("native device stream transport", () => {
47
+ afterEach(() => {
48
+ vi.useRealTimers();
49
+ vi.unstubAllGlobals();
50
+ });
51
+
52
+ function setup(platform: "ios" | "android") {
53
+ vi.useFakeTimers();
54
+ vi.stubGlobal("VideoDecoder", vi.fn());
55
+ vi.stubGlobal("EncodedVideoChunk", vi.fn());
56
+ let resolveOpened!: (socket: FakeSocket) => void;
57
+ const waitForSocket = () =>
58
+ new Promise<FakeSocket>((resolve) => {
59
+ resolveOpened = resolve;
60
+ });
61
+ const opened = waitForSocket();
62
+ class FakeSocket {
63
+ static OPEN = 1;
64
+ readyState = 1;
65
+ binaryType = "";
66
+ onopen: (() => void) | null = null;
67
+ onclose: ((event: { code: number; reason: string }) => void) | null = null;
68
+ send = vi.fn();
69
+ close = vi.fn();
70
+ readonly url: string;
71
+ constructor(url: string) {
72
+ this.url = url;
73
+ resolveOpened(this);
74
+ }
75
+ }
76
+ vi.stubGlobal("WebSocket", FakeSocket);
77
+ const fetch = vi.fn(() => Promise.resolve(new Response("frame")));
78
+ vi.stubGlobal("fetch", fetch);
79
+ const events = {
80
+ onStatus: vi.fn(),
81
+ onScreen: vi.fn(),
82
+ onUnauthorized: vi.fn(),
83
+ onMjpegFallback: vi.fn(),
84
+ onInputConnected: vi.fn(),
85
+ };
86
+ const client = createDeviceStreamClient(
87
+ {
88
+ platform,
89
+ deviceId: "test device",
90
+ preferMjpeg: platform === "ios",
91
+ access: {
92
+ httpBase: "https://environment.test/api/device-hub",
93
+ wsBase: "wss://environment.test/api/device-hub",
94
+ credentials: false,
95
+ query: { wsTicket: "stream-ticket", hostId: "ssh-host" },
96
+ },
97
+ },
98
+ { getContext: () => null } as unknown as HTMLCanvasElement,
99
+ events,
100
+ );
101
+ return { client, opened, waitForSocket, events, fetch };
102
+ }
103
+
104
+ it("uses authenticated iOS MJPEG and forwards controls without a cross-origin video fetch", async () => {
105
+ const { client, opened, events, fetch } = setup("ios");
106
+ client.start();
107
+ const socket = await opened;
108
+ const imageUrl = new URL(events.onMjpegFallback.mock.calls[0]![0] as string);
109
+ expect(imageUrl.pathname).toContain("test%20device/stream.mjpeg");
110
+ expect(imageUrl.searchParams.get("wsTicket")).toBe("stream-ticket");
111
+ expect(imageUrl.searchParams.get("hostId")).toBe("ssh-host");
112
+ expect(fetch).toHaveBeenCalledTimes(1);
113
+ socket.onopen?.();
114
+ client.pressButton("home");
115
+ client.sendTouch("begin", 0.25, 0.75);
116
+ const messages = socket.send.mock.calls.slice(1).map(([bytes]) => {
117
+ const packet = bytes as Uint8Array;
118
+ return {
119
+ tag: packet[0],
120
+ body: JSON.parse(new TextDecoder().decode(packet.subarray(1))) as unknown,
121
+ };
122
+ });
123
+ expect(messages).toEqual([
124
+ { tag: 0x04, body: { button: "home" } },
125
+ { tag: 0x03, body: { type: "begin", x: 0.25, y: 0.75 } },
126
+ ]);
127
+ client.stop();
128
+ expect(socket.close).toHaveBeenCalledTimes(1);
129
+ expect(vi.getTimerCount()).toBe(0);
130
+ });
131
+
132
+ it("forwards Android gestures and device controls through the ticketed host socket", async () => {
133
+ const { client, opened } = setup("android");
134
+ client.start();
135
+ const socket = await opened;
136
+ const url = new URL(socket.url);
137
+ expect(url.searchParams.get("device")).toBe("test device");
138
+ expect(url.searchParams.get("wsTicket")).toBe("stream-ticket");
139
+ expect(url.searchParams.get("hostId")).toBe("ssh-host");
140
+ client.sendTouch("begin", 0.2, 0.8);
141
+ client.sendTouch("move", 0.2, 0.4);
142
+ client.sendTouch("end", 0.2, 0.1);
143
+ client.pressButton("home");
144
+ client.pressButton("appSwitcher");
145
+ expect(
146
+ socket.send.mock.calls.map(([message]) => JSON.parse(message as string) as unknown),
147
+ ).toEqual([
148
+ { type: "touch", action: "down", x: 0.2, y: 0.8 },
149
+ { type: "touch", action: "move", x: 0.2, y: 0.4 },
150
+ { type: "touch", action: "up", x: 0.2, y: 0.1 },
151
+ { type: "home" },
152
+ { type: "recents" },
153
+ ]);
154
+ client.stop();
155
+ expect(socket.close).toHaveBeenCalledTimes(1);
156
+ });
157
+
158
+ it("renews an expired Android ticket when the HTTP upgrade is rejected instead of retrying it forever", async () => {
159
+ const { client, opened, events } = setup("android");
160
+ client.start();
161
+ const socket = await opened;
162
+ socket.onclose?.({ code: 1006, reason: "" });
163
+ expect(events.onUnauthorized).toHaveBeenCalledTimes(1);
164
+ expect(vi.getTimerCount()).toBe(0);
165
+ client.stop();
166
+ });
167
+
168
+ it.each(["ios", "android"] as const)(
169
+ "keeps a restarted %s stream connected when the discarded socket closes late",
170
+ async (platform) => {
171
+ const { client, opened, waitForSocket, events } = setup(platform);
172
+ client.start();
173
+ const discarded = await opened;
174
+ client.stop();
175
+ const reopened = waitForSocket();
176
+ client.start();
177
+ const replacement = await reopened;
178
+ replacement.onopen?.();
179
+ replacement.send.mockClear();
180
+ events.onInputConnected.mockClear();
181
+
182
+ discarded.onclose?.({ code: 1006, reason: "" });
183
+
184
+ expect(events.onUnauthorized).not.toHaveBeenCalled();
185
+ expect(events.onInputConnected).not.toHaveBeenCalled();
186
+ expect(replacement.close).not.toHaveBeenCalled();
187
+ client.pressButton("home");
188
+ expect(replacement.send).toHaveBeenCalledTimes(1);
189
+ client.stop();
190
+ expect(replacement.close).toHaveBeenCalledTimes(1);
191
+ expect(vi.getTimerCount()).toBe(0);
192
+ },
193
+ );
194
+
195
+ it.each(["ios", "android"] as const)(
196
+ "does not renew credentials or reconnect a stopped %s stream",
197
+ async (platform) => {
198
+ const { client, opened, events } = setup(platform);
199
+ client.start();
200
+ const socket = await opened;
201
+ events.onInputConnected.mockClear();
202
+ client.stop();
203
+ socket.onclose?.({ code: 1006, reason: "" });
204
+ expect(events.onUnauthorized).not.toHaveBeenCalled();
205
+ expect(events.onInputConnected).not.toHaveBeenCalled();
206
+ expect(vi.getTimerCount()).toBe(0);
207
+ },
208
+ );
209
+});
210
+
211
describe("serve-emu frames", () => {
212
it("strips the SEMU header and reads the keyframe flag and timestamp", () => {
213
const buffer = new ArrayBuffer(16 + 3);
apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx
+1
-1
@@ -35,7 +35,7 @@ import { useRightPanelStore } from "~/rightPanelStore";
35
import { useDeviceState } from "~/state/device";
36
37
import { DeviceStreamView } from "../device/DeviceStreamView";
38
-import type { DeviceScreenSize } from "../device/deviceStream";
38
+import type { DeviceScreenSize } from "@t3tools/client-runtime/device/stream";
39
import { previewBridge } from "./previewBridge";
40
import {
41
clampPreviewMiniPlayerPosition,
apps/web/src/components/preview/previewMiniPlayerLayout.ts
+1
-1
@@ -7,7 +7,7 @@ import {
7
} from "~/browser/browserViewportLayout";
8
import type { PreviewMiniPlayerPosition, PreviewMiniPlayerSize } from "~/previewMiniPlayerStore";
9
10
-import type { DeviceScreenSize } from "../device/deviceStream";
10
+import type { DeviceScreenSize } from "@t3tools/client-runtime/device/stream";
11
12
export const PREVIEW_MINI_PLAYER_EDGE_GAP = 12;
13
export const PREVIEW_MINI_PLAYER_CORNER_RADIUS = 12;
docs/user/devices.md
+7
-2
@@ -55,8 +55,13 @@ back from the device after a change.
55
When an agent opens a device, it floats over the chat in web and desktop clients
56
connected to the thread, the same way an agent-driven browser does. Turn off
57
**Auto-show floating preview** in **Settings → Integrations → Browser** to open a
58
-right-panel tab instead. Mobile clients show device activity in the thread
59
-timeline. Agents drive the device through the `agent-device` command line. T3
58
+right-panel tab instead. In the mobile app, open the agent's thread and tap the
59
+device button above the composer to watch the live screen and control it.
60
+If the thread has several devices open, choose one in the viewer. Closing the
61
+viewer stops streaming and leaves the device available to the agent. Device
62
+activity also appears in the thread timeline.
63
+
64
+Agents drive the device through the `agent-device` command line. T3
65
Code installs and starts it only after **Agent device access** is enabled. iOS
66
taps build a small test runner on first use, which takes a couple of minutes
67
once per server. Restart an existing agent session after granting access so it
knip.jsonc
+7
-2
@@ -58,8 +58,13 @@
58
"ignoreIssues": { "src/components/ui/*.tsx": ["exports", "nsExports", "duplicates"] },
59
},
60
"apps/mobile": {
61
- // Expo loads local config plugins by string; Metro handles platform variants.
62
- "entry": ["index.ts!", "plugins/*.cjs"],
61
+ // Expo loads plugins by string; Metro embeds the browser entry in the native WebView.
62
+ "entry": [
63
+ "index.ts!",
64
+ "plugins/*.cjs",
65
+ "scripts/generate-device-stream.mts",
66
+ "src/features/devices/device-stream.browser.ts!",
67
+ ],
68
// Fonts are configured as asset paths; Expo autolinks the native packages.
69
"ignoreDependencies": [
70
"@expo-google-fonts/dm-sans",
packages/client-runtime/package.json
+8
@@ -3,6 +3,14 @@
3
"private": true,
4
"type": "module",
5
"exports": {
6
+ "./device/stream": {
7
+ "types": "./src/device/stream.ts",
8
+ "default": "./src/device/stream.ts"
9
+ },
10
+ "./device/hub-access": {
11
+ "types": "./src/device/hubAccess.ts",
12
+ "default": "./src/device/hubAccess.ts"
13
+ },
14
"./worktree-setup": {
15
"types": "./src/worktreeSetup.ts",
16
"default": "./src/worktreeSetup.ts"
packages/client-runtime/src/device/hubAccess.ts
new
+18
@@ -0,0 +1,18 @@
1
+/** Credentials for media requests that cannot set bearer or DPoP headers. */
2
+export interface DeviceHubAccess {
3
+ /** Absolute environment URL ending in `/api/device-hub`. */
4
+ readonly httpBase: string;
5
+ /** Same base with the `ws(s)` scheme. */
6
+ readonly wsBase: string;
7
+ /** Empty for cookie sessions; includes a short-lived ticket for bearer and DPoP sessions. */
8
+ readonly query: Readonly<Record<string, string>>;
9
+ /** Whether requests must include session cookies. */
10
+ readonly credentials: boolean;
11
+}
12
+
13
+export const withDeviceHubQuery = (url: string, access: DeviceHubAccess): string => {
14
+ const entries = Object.entries(access.query);
15
+ if (entries.length === 0) return url;
16
+ const separator = url.includes("?") ? "&" : "?";
17
+ return `${url}${separator}${new URLSearchParams(entries).toString()}`;
18
+};
packages/client-runtime/src/device/stream.ts
renamed
+33
-18
@@ -1,3 +1,6 @@
1
+// @effect-diagnostics globalFetch:off globalTimers:off - This browser and WebView transport runs without an Effect runtime.
2
+/* oxlint-disable unicorn/prefer-add-event-listener -- Each client owns its sockets and their handlers. */
3
+
4
/**
5
* Framework-free client for expo-device-hub's per-device streams, reached
6
* through the T3 proxy. One class handles both platforms because the hub
@@ -16,8 +19,7 @@
19
* The decoder only runs while frames arrive and the viewer is attached; a
20
* hidden panel calls `stop()` so an idle device costs nothing on the GPU.
21
*/
19
-import type { DeviceHubAccess } from "@t3tools/client-runtime/state/deviceHubAccess";
20
-import { withDeviceHubQuery } from "@t3tools/client-runtime/state/deviceHubAccess";
22
+import { type DeviceHubAccess, withDeviceHubQuery } from "./hubAccess.ts";
23
import type { DevicePlatform } from "@t3tools/contracts";
24
25
export type DeviceStreamStatus = "connecting" | "streaming" | "error";
@@ -47,6 +49,8 @@ export interface DeviceStreamTarget {
49
readonly platform: DevicePlatform;
50
readonly deviceId: string;
51
readonly access: DeviceHubAccess;
52
+ /** Native iOS WebViews can use MJPEG without cross-origin fetch or secure-context support. */
53
+ readonly preferMjpeg?: boolean;
54
}
55
56
export type DeviceHardwareButton = "home" | "back" | "recents" | "power" | "appSwitcher";
@@ -280,7 +284,7 @@ export function createDeviceStreamClient(
284
const httpUrl = (path: string) =>
285
withDeviceHubQuery(`${access.httpBase}${vendor}${path}`, access);
286
const wsUrl = (path: string) => withDeviceHubQuery(`${access.wsBase}${vendor}${path}`, access);
283
- const useWebCodecs = isWebCodecsSupported();
287
+ const useWebCodecs = isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg);
288
289
let stopped = true;
290
let socket: WebSocket | null = null;
@@ -526,14 +530,20 @@ export function createDeviceStreamClient(
530
}
531
};
532
ws.onclose = (event) => {
529
- if (socket === ws) socket = null;
530
- if (!stopped) {
531
- events.onInputConnected(
532
- false,
533
- event.reason || (event.code === 1006 ? "input socket refused" : `closed ${event.code}`),
534
- );
535
- }
536
- if (event.code === 1008 || event.code === 4401) return handleUnauthorized();
533
+ if (socket !== ws) return;
534
+ socket = null;
535
+ if (stopped) return;
536
+ events.onInputConnected(
537
+ false,
538
+ event.reason || (event.code === 1006 ? "input socket refused" : `closed ${event.code}`),
539
+ );
540
+ // A rejected HTTP upgrade surfaces as 1006, including an expired stream ticket.
541
+ if (
542
+ event.code === 1008 ||
543
+ event.code === 4401 ||
544
+ (event.code === 1006 && access.query.wsTicket)
545
+ )
546
+ return handleUnauthorized();
547
scheduleRetry("input", () => void connectIosInput());
548
};
549
ws.onerror = () => ws.close();
@@ -580,14 +590,19 @@ export function createDeviceStreamClient(
590
decode(isKey, packet.data, packet.timestamp);
591
};
592
ws.onclose = (event) => {
583
- if (socket === ws) socket = null;
593
+ if (socket !== ws) return;
594
+ socket = null;
595
closeDecoder();
585
- if (!stopped) events.onInputConnected(false, event.reason || `closed ${event.code}`);
586
- if (event.code === 1008 || event.code === 4401) return handleUnauthorized();
587
- if (!stopped) {
588
- setStatus("connecting", event.reason || undefined);
589
- scheduleRetry("input", connectAndroid);
590
- }
596
+ if (stopped) return;
597
+ events.onInputConnected(false, event.reason || `closed ${event.code}`);
598
+ if (
599
+ event.code === 1008 ||
600
+ event.code === 4401 ||
601
+ (event.code === 1006 && access.query.wsTicket)
602
+ )
603
+ return handleUnauthorized();
604
+ setStatus("connecting", event.reason || undefined);
605
+ scheduleRetry("input", connectAndroid);
606
};
607
ws.onerror = () => ws.close();
608
};
packages/client-runtime/src/state/deviceHubAccess.ts
+3
-18
@@ -20,19 +20,11 @@ import { environmentEndpointUrl } from "../environment/endpoint.ts";
20
import { ManagedRelayDpopSigner } from "../relay/managedRelay.ts";
21
import type { RemoteEnvironmentRequestError } from "../rpc/http.ts";
22
import { executeAuthenticatedEnvironmentHttpRequest } from "./environmentHttpAuth.ts";
23
+import type { DeviceHubAccess } from "../device/hubAccess.ts";
24
24
-const TICKET_TIMEOUT_MS = 8_000;
25
+export { type DeviceHubAccess, withDeviceHubQuery } from "../device/hubAccess.ts";
26
26
-export interface DeviceHubAccess {
27
- /** Absolute origin-relative base, e.g. `https://env.example/api/device-hub`. */
28
- readonly httpBase: string;
29
- /** Same base with the `ws(s)` scheme. */
30
- readonly wsBase: string;
31
- /** Query parameters to append to every hub request; empty for cookie sessions. */
32
- readonly query: Readonly<Record<string, string>>;
33
- /** Whether requests must include cookies (same-origin session). */
34
- readonly credentials: boolean;
35
-}
27
+const TICKET_TIMEOUT_MS = 8_000;
28
29
export const resolveDeviceHubAccess = Effect.fn("clientRuntime.state.resolveDeviceHubAccess")(
30
function* (input: {
@@ -64,10 +56,3 @@ export const resolveDeviceHubAccess = Effect.fn("clientRuntime.state.resolveDevi
56
};
57
},
58
);
67
-
68
-export const withDeviceHubQuery = (url: string, access: DeviceHubAccess): string => {
69
- const entries = Object.entries(access.query);
70
- if (entries.length === 0) return url;
71
- const separator = url.includes("?") ? "&" : "?";
72
- return `${url}${separator}${new URLSearchParams(entries).toString()}`;
73
-};