Skip to content

Commit 6a776e5

Browse files
committed
feat(web,mobile): take over a device an idle thread still holds
A thread keeps its device session after its run ends, so its agent-device claim refuses other threads' agents with DEVICE_IN_USE and names only a session hash. Nothing showed which thread held the device or offered a way to release it. The Device panel and the mobile device viewer now name other threads that have the same device open, linked to the thread. When that thread isn't running, Take over closes the device there through the existing device.close request, which releases its agent-device claim.
1 parent 09a54f0 commit 6a776e5

5 files changed

Lines changed: 236 additions & 3 deletions

File tree

‎apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx‎

Lines changed: 82 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,21 @@
11
import { SheetCloseButton } from "../../components/ui/SheetHeader";
22
import { Button } from "../../components/ui/Button";
33
import * as Dialog from "../../components/ui/Dialog";
4+
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
45
import {
56
deviceToolVersionLabels,
67
deviceToolUpdateOwnership,
78
deviceToolUpdatePolicy,
9+
otherThreadDeviceSessions,
810
} from "@t3tools/client-runtime/state/device";
9-
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
10-
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
11+
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
12+
import {
13+
StackActions,
14+
useIsFocused,
15+
useNavigation,
16+
type StaticScreenProps,
17+
} from "@react-navigation/native";
18+
import { EnvironmentId, ThreadId, type DeviceSession } from "@t3tools/contracts";
1119
import * as Cause from "effect/Cause";
1220
import { useEffect, useRef, useState, type RefObject } from "react";
1321
import * as Haptics from "expo-haptics";
@@ -35,6 +43,7 @@ import { deriveBottomControlInsets } from "../../lib/reserved-regions";
3543
import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
3644
import { uuidv4 } from "../../lib/uuid";
3745
import { deviceEnvironment, useDeviceHubAccess } from "../../state/device";
46+
import { useThreadShell } from "../../state/entities";
3847
import { useEnvironmentQuery } from "../../state/query";
3948
import { useAtomCommand } from "../../state/use-atom-command";
4049
import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
@@ -89,6 +98,7 @@ export function DevicePreviewScreen({
8998
readonly initialDeviceKey?: string;
9099
}) {
91100
const embedded = onMaximize !== undefined;
101+
const navigation = useNavigation();
92102
const insets = useSafeAreaInsets();
93103
// In a pane the stream sits below the pane's bar, which content otherwise slides under.
94104
const barOverlap = useBarOverlap();
@@ -104,10 +114,14 @@ export function DevicePreviewScreen({
104114
const [controlsVisible, setControlsVisible] = useState(true);
105115
const retryHost = useAtomCommand(deviceEnvironment.list);
106116
const shutdown = useAtomCommand(deviceEnvironment.shutdown, { reportFailure: false });
117+
const close = useAtomCommand(deviceEnvironment.close, { reportFailure: false });
107118
const streamRef = useRef<DeviceStreamRef>(null);
108119
const state = useEnvironmentQuery(deviceEnvironment.state({ environmentId, input: {} }));
109120
const previews = threadDevicePreviews(state.data, threadId);
110121
const preview = selectedThreadDevicePreview(previews, selectedKey);
122+
const holders = preview
123+
? otherThreadDeviceSessions(state.data?.sessions ?? [], preview.session)
124+
: [];
111125
const onInputConnected = async (connected: boolean) => {
112126
setInputConnected(connected);
113127
if (!connected) setControlsVisible(true);
@@ -149,6 +163,29 @@ export function DevicePreviewScreen({
149163
}
150164
};
151165

166+
const takeOver = async (holder: DeviceSession) => {
167+
const result = await close({
168+
environmentId,
169+
input: { threadId: holder.threadId, hostId: holder.hostId, deviceId: holder.deviceId },
170+
});
171+
if (result._tag === "Failure") {
172+
Dialog.alert("Could not take over device", String(Cause.squash(result.cause)));
173+
}
174+
};
175+
const holderBanners = holders.map((holder) => (
176+
<DeviceHolderBanner
177+
key={holder.threadId}
178+
environmentId={environmentId}
179+
holder={holder}
180+
onOpenThread={() =>
181+
navigation.dispatch(
182+
StackActions.replace("Thread", { environmentId, threadId: holder.threadId }),
183+
)
184+
}
185+
onTakeOver={() => takeOver(holder)}
186+
/>
187+
));
188+
152189
const controls: AppBarMenuItem[] = [
153190
...(state.data?.hosts
154191
.filter(
@@ -281,6 +318,9 @@ export function DevicePreviewScreen({
281318
]}
282319
/>
283320
<View style={{ height: barOverlap }} />
321+
{holderBanners.length > 0 ? (
322+
<View className="gap-2 px-3 pb-2">{holderBanners}</View>
323+
) : null}
284324
</>
285325
) : null}
286326
{preview && focused && foreground ? (
@@ -348,6 +388,7 @@ export function DevicePreviewScreen({
348388
/>
349389
<DeviceOptionsMenu items={menuItems} />
350390
</GlassSurface>
391+
{holderBanners.length > 0 ? <View className="mt-2 gap-2">{holderBanners}</View> : null}
351392
</View>
352393
</Animated.View>
353394
) : (
@@ -373,6 +414,45 @@ export function DevicePreviewScreen({
373414
);
374415
}
375416

417+
function DeviceHolderBanner(props: {
418+
readonly environmentId: EnvironmentId;
419+
readonly holder: DeviceSession;
420+
readonly onOpenThread: () => void;
421+
readonly onTakeOver: () => Promise<void>;
422+
}) {
423+
const shell = useThreadShell(scopeThreadRef(props.environmentId, props.holder.threadId));
424+
const running = threadRuntimeIsActive(shell?.runtime);
425+
const [takingOver, setTakingOver] = useState(false);
426+
const title = shell?.title.trim() || "another thread";
427+
return (
428+
<GlassSurface className="flex-row items-center gap-3 px-3 py-2">
429+
<Pressable
430+
accessibilityRole="link"
431+
accessibilityLabel={`Open thread ${title}`}
432+
className="min-w-0 flex-1"
433+
onPress={props.onOpenThread}
434+
>
435+
<AppText numberOfLines={2} className="text-sm text-foreground-muted">
436+
Busy in <AppText className="font-t3-medium text-sm text-foreground">{title}</AppText>
437+
{running ? ", which is running." : ", which isn't running."}
438+
</AppText>
439+
</Pressable>
440+
{running ? null : (
441+
<Button
442+
label="Take over"
443+
tone="primary"
444+
size="compact"
445+
loading={takingOver}
446+
onPress={() => {
447+
setTakingOver(true);
448+
void props.onTakeOver().finally(() => setTakingOver(false));
449+
}}
450+
/>
451+
)}
452+
</GlassSurface>
453+
);
454+
}
455+
376456
function DeviceOptionsMenu({ items }: { readonly items: ReadonlyArray<AppBarMenuItem> }) {
377457
return (
378458
<Menu

‎apps/web/src/components/device/DevicePanel.browser.test.tsx‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ const mocks = vi.hoisted(() => ({
2323
list: vi.fn<(request: unknown) => Promise<CommandResult>>(),
2424
openDevice: vi.fn(),
2525
closeSurface: vi.fn(),
26+
holderStatus: "idle" as "idle" | "running",
2627
}));
2728
const phone = {
2829
hostId: "local",
@@ -96,6 +97,14 @@ vi.mock("~/rightPanelStore", () => ({
9697
},
9798
selectThreadRightPanelState: () => ({ isOpen: false, activeSurfaceId: null, surfaces: [] }),
9899
}));
100+
vi.mock("~/state/entities", () => ({
101+
useThreadShell: () => ({ runtime: { status: mocks.holderStatus } }),
102+
}));
103+
vi.mock("~/components/ThreadContextChip", () => ({
104+
ThreadContextChip: ({ record }: { record: { threadId: string } }) => (
105+
<a href={`/${record.threadId}`}>{record.threadId}</a>
106+
),
107+
}));
99108
vi.mock("~/components/device/DeviceHostUpdates", () => ({ DeviceHostUpdates: () => null }));
100109
vi.mock("~/components/device/DeviceWorkspace", () => ({
101110
DeviceWorkspace: ({ onPowerOff }: { onPowerOff: () => void }) => (
@@ -154,6 +163,7 @@ const errors = () => container.querySelectorAll('[role="alert"]');
154163
function setup() {
155164
vi.resetAllMocks();
156165
mocks.list.mockResolvedValue({ _tag: "Success", value: { hostId: "local", deviceId: "" } });
166+
mocks.holderStatus = "idle";
157167
currentState = deviceState;
158168
container = document.createElement("div");
159169
container.style.width = "480px";
@@ -199,6 +209,60 @@ describe("DevicePanel thread switches", () => {
199209
});
200210
});
201211

212+
describe("DevicePanel takeover", () => {
213+
const holder = ThreadId.make("thread-holder");
214+
const session = {
215+
hostId: "local",
216+
deviceId: "phone",
217+
platform: "ios",
218+
openedAt: "2026-01-01T00:00:00.000Z",
219+
} as const;
220+
const shared: DeviceServiceState = {
221+
...deviceState,
222+
sessions: [
223+
...deviceState.sessions,
224+
{ ...session, threadId: holder },
225+
// The same serial on another host is a different device.
226+
{ ...session, threadId: ThreadId.make("thread-elsewhere"), hostId: "ssh" },
227+
],
228+
};
229+
const openPhone: Extract<RightPanelSurface, { kind: "device" }> = {
230+
...picker,
231+
target: { ...phoneTarget, platform: "ios" },
232+
};
233+
234+
it("closes the idle holder's session so this thread's agent can claim the device", async () => {
235+
setup();
236+
currentState = shared;
237+
mocks.close.mockResolvedValue(opened);
238+
await using screen = await render(devicePanel(threadA, openPhone), { container });
239+
240+
await expect.element(screen.getByText("thread-elsewhere")).not.toBeInTheDocument();
241+
await screen.getByRole("button", { name: "Take over" }).click();
242+
243+
expect(mocks.close.mock.calls).toEqual([
244+
[
245+
{
246+
environmentId: threadA.environmentId,
247+
input: { threadId: holder, hostId: "local", deviceId: "phone" },
248+
},
249+
],
250+
]);
251+
});
252+
253+
it("offers no takeover while the holder is running", async () => {
254+
setup();
255+
currentState = shared;
256+
mocks.holderStatus = "running";
257+
await using screen = await render(devicePanel(threadA, openPhone), { container });
258+
259+
await expect
260+
.element(screen.getByRole("status"))
261+
.toHaveTextContent("Busy in thread-holder, which is running.");
262+
await expect.element(screen.getByRole("button", { name: "Take over" })).not.toBeInTheDocument();
263+
});
264+
});
265+
202266
describe("DevicePanel host probe", () => {
203267
it("probes the hosts once while setup shows inside the panel", async () => {
204268
setup();

‎apps/web/src/components/device/DevicePanel.tsx‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
import { DeviceHostUpdates } from "./DeviceHostUpdates";
2+
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
3+
import { otherThreadDeviceSessions } from "@t3tools/client-runtime/state/device";
4+
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
25
import type {
36
DevicePlatform,
47
DeviceServiceState,
8+
DeviceSession,
59
DeviceSummary,
10+
EnvironmentId,
611
ScopedThreadRef,
712
} from "@t3tools/contracts";
813
import { ArrowUpRight, CircleAlert, Play, Smartphone, X } from "lucide-react";
@@ -29,8 +34,10 @@ import {
2934
NO_DEVICE_PROBE_ATOM,
3035
useDeviceState,
3136
} from "~/state/device";
37+
import { useThreadShell } from "~/state/entities";
3238
import { formatEnvironmentQueryError } from "~/state/query";
3339
import { useAtomCommand } from "~/state/use-atom-command";
40+
import { ThreadContextChip } from "../ThreadContextChip";
3441
import { DeviceLoadingView } from "./DeviceLoadingView";
3542
import {
3643
DeviceSetup,
@@ -95,6 +102,7 @@ export function DevicePanel(props: {
95102
const activeHost = activeDevice
96103
? state.hosts.find((host) => host.id === activeDevice.hostId)
97104
: undefined;
105+
const holders = activeSession ? otherThreadDeviceSessions(state.sessions, activeSession) : [];
98106

99107
const grouped = groupDevices(state);
100108

@@ -174,6 +182,16 @@ export function DevicePanel(props: {
174182
});
175183
};
176184

185+
const takeOver = (holder: DeviceSession) => {
186+
const settleOperation = startOperation(null);
187+
return close({
188+
environmentId,
189+
input: { threadId: holder.threadId, hostId: holder.hostId, deviceId: holder.deviceId },
190+
}).then((result) =>
191+
settleOperation(result._tag === "Failure" ? formatEnvironmentQueryError(result.cause) : null),
192+
);
193+
};
194+
177195
const bootingDevices =
178196
state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
179197
const { ready: hostReady, busy: hostBusy } = deviceHubReadiness(state);
@@ -242,6 +260,14 @@ export function DevicePanel(props: {
242260
minute.
243261
</div>
244262
) : null}
263+
{holders.map((holder) => (
264+
<DeviceHolderNotice
265+
key={holder.threadId}
266+
environmentId={environmentId}
267+
holder={holder}
268+
onTakeOver={() => takeOver(holder)}
269+
/>
270+
))}
245271
{operationError ? (
246272
<DeviceNotice onDismiss={() => setOperation(null)}>{operationError}</DeviceNotice>
247273
) : null}
@@ -386,6 +412,46 @@ export function DevicePanel(props: {
386412
);
387413
}
388414

415+
function DeviceHolderNotice(props: {
416+
readonly environmentId: EnvironmentId;
417+
readonly holder: DeviceSession;
418+
readonly onTakeOver: () => Promise<unknown>;
419+
}) {
420+
const shell = useThreadShell(scopeThreadRef(props.environmentId, props.holder.threadId));
421+
const running = threadRuntimeIsActive(shell?.runtime);
422+
const [takingOver, setTakingOver] = useState(false);
423+
return (
424+
<div
425+
role="status"
426+
className="flex flex-wrap items-center gap-x-2 gap-y-1 border-b px-3 py-2 text-xs text-muted-foreground"
427+
>
428+
<span className="min-w-0 flex-1 basis-56">
429+
Busy in{" "}
430+
<ThreadContextChip
431+
record={{
432+
environmentId: props.environmentId,
433+
threadId: props.holder.threadId,
434+
title: "another thread",
435+
}}
436+
/>
437+
{running ? ", which is running." : ", which isn't running."}
438+
</span>
439+
{running ? null : (
440+
<Button
441+
size="xs"
442+
disabled={takingOver}
443+
onClick={() => {
444+
setTakingOver(true);
445+
void props.onTakeOver().finally(() => setTakingOver(false));
446+
}}
447+
>
448+
{takingOver ? "Taking over…" : "Take over"}
449+
</Button>
450+
)}
451+
</div>
452+
);
453+
}
454+
389455
function DeviceNotice(props: { readonly onDismiss: () => void; readonly children: ReactNode }) {
390456
return (
391457
<div

‎docs/user/devices.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,11 @@ If the thread has several devices open, choose one in the viewer. Closing the
7979
viewer stops streaming and leaves the device available to the agent. Device
8080
activity also appears in the thread timeline.
8181

82+
Only one thread's agent can drive a device at a time. When another thread also
83+
has the device open, the Device panel and the mobile viewer name that thread;
84+
select the name to go there. If that thread isn't running, choose **Take over**
85+
to close the device there so this thread's agent can use it.
86+
8287
Agents drive the device through the `agent-device` command line. T3
8388
Code installs and starts it only after **Agents can use devices** is on. iOS
8489
taps build a small test runner on first use, which takes a couple of minutes

‎packages/client-runtime/src/state/device.ts‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { type DeviceToolVersions, WS_METHODS } from "@t3tools/contracts";
1+
import { type DeviceSession, type DeviceToolVersions, WS_METHODS } from "@t3tools/contracts";
22
import { Atom } from "effect/reactivity";
33

44
import type { EnvironmentRegistry } from "../connection/registry.ts";
@@ -116,5 +116,23 @@ export function deviceToolUpdatePolicy(tools: DeviceToolVersions | undefined) {
116116
? "Update pending. Required tools will install automatically when next used. The host needs network access; an older install is not used as a fallback."
117117
: "Required tools are installed automatically when needed. Checking versions does not install or start anything.";
118118
}
119+
120+
/**
121+
* Other threads with the same device open. Any of them may hold the agent-device
122+
* claim that refuses this thread's agent with DEVICE_IN_USE; closing their session
123+
* releases it. Android serials repeat across hosts, so the host is part of the match.
124+
*/
125+
export function otherThreadDeviceSessions(
126+
sessions: ReadonlyArray<DeviceSession>,
127+
session: Pick<DeviceSession, "threadId" | "hostId" | "deviceId">,
128+
) {
129+
return sessions.filter(
130+
(other) =>
131+
other.threadId !== session.threadId &&
132+
other.hostId === session.hostId &&
133+
other.deviceId === session.deviceId,
134+
);
135+
}
136+
119137
export const deviceToolUpdateOwnership =
120138
"This environment's T3 server chooses device tool versions for itself and its SSH hosts. Update that server to receive newer tool versions; updating only your browser or mobile app does not update a remote server.";

0 commit comments

Comments
 (0)