feat(devices): scope targets and sessions to their hosts (#10854)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-10 11:59:33 -07:00
1 parent dca7b59bea
commit e022fa430e
19 files changed
+649 -257

No files matched your search

+2 -1
View File
@@ -196,7 +196,7 @@ const handler = Effect.gen(function* () {
(!readOnly && /\/api\/stream-(mode|settings)$/.test(hubPath));
yield* authenticate(controlsDevice ? AuthOrchestrationOperateScope : AuthOrchestrationReadScope);
const devices = yield* DeviceService.DeviceService;
const ready = yield* devices.currentReadiness();
const ready = yield* devices.currentReadiness(url.value.searchParams.get("hostId") ?? undefined);
if (!ready) {
return HttpServerResponse.text("Device hub is not running", { status: 503 });
}
@@ -206,6 +206,7 @@ const handler = Effect.gen(function* () {
// The ticket authenticates here and must not travel on to the hub.
const upstreamSearch = new URLSearchParams(url.value.search);
upstreamSearch.delete("wsTicket");
upstreamSearch.delete("hostId");
const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";
const upstreamPath = `${hubPath}${search}`;
if (upgrade) {
@@ -0,0 +1,86 @@
import { expect, it } from "@effect/vitest";
import { ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ServerSettingsService } from "../serverSettings.ts";
import { DeviceHostError, DeviceHost } from "./DeviceHost.ts";
import { makeWithHosts } from "./DeviceService.ts";
it.effect("keeps hosts independent when serials collide and another host fails", () =>
Effect.gen(function* () {
const host = (id: string, failed = false): DeviceHost["Service"] => {
const ready = {
hub: { origin: `http://${id}` },
agentDevice: { baseUrl: `http://${id}`, token: "test", entryPath: "/agent-device" },
run: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }),
helpers: { serveSimAxSettings: null, serveSimCli: null },
};
return {
id,
summary: Effect.succeed({
id,
label: id,
kind: "local",
hubInstalled: true,
agentDeviceInstalled: true,
platforms: [{ platform: "android", available: true }],
}),
platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
ensureReady: () =>
failed
? Effect.fail(
new DeviceHostError({ hostId: id, step: "connect", cause: new Error("offline") }),
)
: Effect.succeed(ready),
ensureAgentReady: () => Effect.succeed(ready),
current: Effect.succeed(ready),
stopAgent: Effect.void,
stop: Effect.void,
};
};
const http = HttpClient.make((request) =>
Effect.succeed(
HttpClientResponse.fromWeb(
request,
Response.json({
simulators: [],
emulators: [
{
id: "emulator-5554",
name: "Pixel",
version: "36",
platform: "android",
booted: true,
physical: false,
},
],
}),
),
),
);
const hosts = new Map(["a", "b", "offline"].map((id) => [id, host(id, id === "offline")]));
const service = yield* makeWithHosts(hosts).pipe(
Effect.provideService(HttpClient.HttpClient, http),
);
const listed = yield* service.list;
expect(listed.devices.map((device) => device.hostId).sort()).toEqual(["a", "b"]);
expect(listed.hostStatuses.offline?.status).toBe("failed");
const threadId = ThreadId.make("thread");
for (const hostId of ["a", "b"])
yield* service.open({ threadId, hostId, deviceId: "emulator-5554", platform: "android" });
yield* service.close({ threadId, hostId: "a", deviceId: "emulator-5554" });
const state = yield* service.state;
expect(state.devices).toHaveLength(2);
expect(state.sessions.map((session) => session.hostId)).toEqual(["b"]);
expect(state.hostStatuses.a?.status).toBe("ready");
expect(state.hostStatuses.offline?.status).toBe("failed");
yield* service.agentReadinessIfSupported("b");
expect((yield* service.state).hostStatuses.b?.status).toBe("ready");
yield* service.configure({ enabled: false });
expect((yield* service.state).hostStatuses).toEqual({});
}).pipe(
Effect.provide(
ServerSettingsService.layerTest({ enableDeviceSupport: true, enableAgentDeviceAccess: true }),
),
),
);
@@ -21,6 +21,7 @@ import { type DeviceService, make, stateStream } from "./DeviceService.ts";
const baseState: DeviceServiceState = {
hosts: [],
hostStatus: "idle",
hostStatuses: {},
devices: [],
sessions: [],
onboardingCompleted: false,
+58 -51
View File
@@ -136,8 +136,9 @@ interface ServiceState {
const vendorPrefix = (platform: DevicePlatform) =>
platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
export const make = Effect.gen(function* () {
const localHost = yield* DeviceHost.DeviceHost;
export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* (
hosts: ReadonlyMap<DeviceHostId, DeviceHost.DeviceHost["Service"]>,
) {
const settings = yield* ServerSettings.ServerSettingsService;
const lifecycleLock = yield* Semaphore.make(1);
const readDeviceSettings = settings.getSettings.pipe(
@@ -152,9 +153,7 @@ export const make = Effect.gen(function* () {
),
);
const initialSettings = yield* readDeviceSettings;
const hosts: ReadonlyMap<DeviceHostId, DeviceHost.DeviceHost["Service"]> = new Map([
[localHost.id, localHost],
]);
const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
const statePubSub = yield* PubSub.unbounded<DeviceServiceState>();
const initialHosts = yield* Effect.forEach(hosts.values(), (host) => host.summary);
@@ -162,6 +161,7 @@ export const make = Effect.gen(function* () {
state: {
hosts: initialHosts,
hostStatus: initialSettings.enabled ? "idle" : "disabled",
hostStatuses: {},
devices: [],
sessions: [],
onboardingCompleted: initialSettings.onboardingCompleted,
@@ -187,6 +187,18 @@ export const make = Effect.gen(function* () {
return host;
});
const setHostStatus = (
hostId: DeviceHostId,
status: DeviceServiceState["hostStatuses"][string],
) =>
publish((state) => ({
...state,
...(hostId === LOCAL_DEVICE_HOST_ID
? { hostStatus: status.status, hostStatusDetail: status.detail }
: {}),
hostStatuses: { ...state.hostStatuses, [hostId]: status },
}));
const readiness: DeviceService["Service"]["readiness"] = Effect.fn("DeviceService.readiness")(
function* (hostId) {
const host = yield* resolveHost(hostId);
@@ -198,34 +210,19 @@ export const make = Effect.gen(function* () {
});
}
const ready = yield* host
.ensureReady((phase) =>
publish((state) => ({ ...state, hostStatus: phase, hostStatusDetail: undefined })).pipe(
Effect.asVoid,
),
)
.ensureReady((status) => setHostStatus(host.id, { status }).pipe(Effect.asVoid))
.pipe(
Effect.tapError((error) =>
publish((state) => ({
...state,
hostStatus: "failed",
hostStatusDetail: error.message,
})),
setHostStatus(host.id, { status: "failed", detail: error.message }),
),
Effect.mapError(
(error) => new DeviceHostUnavailableError({ hostId: host.id, reason: error.message }),
),
);
yield* SynchronizedRef.get(stateRef).pipe(
Effect.flatMap(({ state }) =>
state.hostStatus === "ready"
? Effect.void
: publish((current) => ({
...current,
hostStatus: "ready",
hostStatusDetail: undefined,
})),
),
);
const { state } = yield* SynchronizedRef.get(stateRef);
if (state.hostStatuses[host.id]?.status !== "ready") {
yield* setHostStatus(host.id, { status: "ready" });
}
return { hostId: host.id, ...ready };
},
lifecycleLock.withPermit,
@@ -249,25 +246,18 @@ export const make = Effect.gen(function* () {
const summary = yield* host.summary;
if (!summary.platforms.some((platform) => platform.available)) return null;
const ready = yield* host
.ensureAgentReady((phase) =>
publish((state) => ({ ...state, hostStatus: phase, hostStatusDetail: undefined })).pipe(
Effect.asVoid,
),
)
.ensureAgentReady((phase) => setHostStatus(host.id, { status: phase }).pipe(Effect.asVoid))
.pipe(
Effect.tapError((error) =>
publish((state) => ({
...state,
hostStatus: "failed",
hostStatusDetail: error.message,
})),
setHostStatus(host.id, { status: "failed", detail: error.message }),
),
Effect.mapError(
(error) => new DeviceHostUnavailableError({ hostId: host.id, reason: error.message }),
),
);
const hostSummaries = yield* Effect.forEach(hosts.values(), (candidate) => candidate.summary);
yield* publish((state) => ({ ...state, hosts: hostSummaries, hostStatus: "ready" }));
yield* publish((state) => ({ ...state, hosts: hostSummaries }));
yield* setHostStatus(host.id, { status: "ready" });
return { hostId: host.id, ...ready };
}, lifecycleLock.withPermit);
@@ -357,8 +347,15 @@ export const make = Effect.gen(function* () {
return yield* publish((state) => ({
...state,
hosts: hostSummaries,
devices,
hostStatusDetail: detail,
...(ready.hostId === LOCAL_DEVICE_HOST_ID ? { hostStatusDetail: detail } : {}),
devices: [
...state.devices.filter((device) => device.hostId !== ready.hostId),
...devices,
],
hostStatuses: {
...state.hostStatuses,
[ready.hostId]: { status: "ready", ...(detail ? { detail } : {}) },
},
}));
}),
);
@@ -366,18 +363,21 @@ export const make = Effect.gen(function* () {
const list: DeviceService["Service"]["list"] = Effect.gen(function* () {
if (!(yield* readDeviceSettings).enabled) return (yield* SynchronizedRef.get(stateRef)).state;
const ready = yield* readiness();
return yield* refresh(ready);
}).pipe(
Effect.tapError((error) =>
publish((state) =>
state.hostStatus === "disabled"
? state
: { ...state, hostStatus: "failed", hostStatusDetail: error.message },
),
),
Effect.withSpan("DeviceService.list"),
);
yield* Effect.forEach(
hosts.values(),
(host) =>
Effect.gen(function* () {
const ready = yield* readinessIfSupported(host.id);
if (ready) yield* refresh(ready);
}).pipe(
Effect.catch((error) =>
setHostStatus(host.id, { status: "failed", detail: error.message }),
),
),
{ concurrency: 4 },
);
return (yield* SynchronizedRef.get(stateRef)).state;
}).pipe(Effect.withSpan("DeviceService.list"));
const configure: DeviceService["Service"]["configure"] = Effect.fn("DeviceService.configure")(
function* (input) {
@@ -415,6 +415,7 @@ export const make = Effect.gen(function* () {
...state,
hostStatus: nextEnabled ? "idle" : "disabled",
hostStatusDetail: undefined,
hostStatuses: {},
devices: nextEnabled ? state.devices : [],
sessions: nextEnabled ? state.sessions : [],
bootingDevices: nextEnabled ? state.bootingDevices : [],
@@ -636,6 +637,7 @@ export const make = Effect.gen(function* () {
const closing = state.sessions.filter(
(session) =>
session.threadId === input.threadId &&
(input.hostId === undefined || session.hostId === input.hostId) &&
(input.deviceId === undefined || session.deviceId === input.deviceId),
);
if (closing.length === 0) return;
@@ -749,6 +751,11 @@ export const make = Effect.gen(function* () {
});
});
export const make = Effect.gen(function* () {
const host = yield* DeviceHost.DeviceHost;
return yield* makeWithHosts(new Map([[host.id, host]]));
});
export const layer = Layer.effect(DeviceService, make).pipe(Layer.provide(LocalDeviceHost.layer));
/** State stream for WS subscribers: current snapshot first, then every change. */
@@ -56,6 +56,7 @@ const state = {
},
],
hostStatus: "ready" as const,
hostStatuses: { local: { status: "ready" as const } },
devices: [device],
sessions: [],
onboardingCompleted: true,
@@ -161,7 +161,9 @@ const handlers = {
const target =
input.deviceId !== undefined
? { hostId: input.hostId ?? LOCAL_DEVICE_HOST_ID, deviceId: input.deviceId }
: sessions.at(-1);
: sessions
.filter((session) => input.hostId === undefined || session.hostId === input.hostId)
.at(-1);
if (!target) {
return yield* new DeviceToolUnavailableError({
reason: "No device is open in this thread. Call device_open first.",
@@ -183,6 +185,7 @@ const handlers = {
const devices = yield* DeviceService.DeviceService;
yield* devices.close({
threadId: scope.threadId,
...(input.hostId === undefined ? {} : { hostId: input.hostId }),
...(input.deviceId === undefined ? {} : { deviceId: input.deviceId }),
...(input.shutdown === undefined ? {} : { shutdown: input.shutdown }),
});
+2 -1
View File
@@ -1669,7 +1669,8 @@ const NodeHttpServerTestWithWsDeflate = HttpServer.layerTestClient.pipe(
const EMPTY_DEVICE_STATE: DeviceServiceState = {
hosts: [],
hostStatus: "idle",
hostStatus: "disabled",
hostStatuses: {},
devices: [],
sessions: [],
onboardingCompleted: false,
+59 -19
View File
@@ -4143,7 +4143,9 @@ export default function ChatView(props: ChatViewProps) {
if (!activeThreadRef || !supportsThreadPullRequests) return;
useRightPanelStore.getState().open(activeThreadRef, "pull-requests");
}, [activeThreadRef, supportsThreadPullRequests]);
const { state: deviceState } = useDeviceState(activeThreadRef?.environmentId ?? null);
const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState(
activeThreadRef?.environmentId ?? null,
);
const [deviceSetupThread, setDeviceSetupThread] = useState<ScopedThreadRef | null>(null);
const addDeviceSurface = useCallback(() => {
if (!activeThreadRef) return;
@@ -4153,24 +4155,53 @@ export default function ChatView(props: ChatViewProps) {
}
useRightPanelStore.getState().open(activeThreadRef, "device");
}, [activeThreadRef, deviceState.onboardingCompleted, deviceState.hostStatus]);
// An agent's `device_open` surfaces in every client the same way a
// `preview_open` does: the thread starts a device or gains a session and the panel
// opens on it. Closing the last session leaves the tab in place so the
// user keeps their picker; only new sessions raise the panel.
const threadDeviceSessionCount = activeThreadRef
? deviceState.sessions.filter((session) => session.threadId === activeThreadRef.threadId)
.length +
(deviceState.bootingDevices?.filter((device) => device.threadId === activeThreadRef.threadId)
.length ?? 0)
: 0;
const previousDeviceSessionCount = useRef(threadDeviceSessionCount);
// Reconcile new server sessions into separate tabs, including sessions opened
// by an agent or another client. The first snapshot is a baseline: persisted
// tabs restore themselves, and existing sessions must not resurrect closed tabs.
const previousDeviceSessions = useRef(new Map<string, Set<string>>());
useEffect(() => {
const previous = previousDeviceSessionCount.current;
previousDeviceSessionCount.current = threadDeviceSessionCount;
if (!activeThreadRef || threadDeviceSessionCount <= previous) return;
if (shouldUseRightPanelSheet) return;
useRightPanelStore.getState().open(activeThreadRef, "device");
}, [activeThreadRef, shouldUseRightPanelSheet, threadDeviceSessionCount]);
if (!activeThreadRef || !deviceStateLoaded) return;
const threadKey = `${activeThreadRef.environmentId}:${activeThreadRef.threadId}`;
const sessions = deviceState.sessions.filter(
(session) => session.threadId === activeThreadRef.threadId,
);
const key = (session: (typeof sessions)[number]) => `${session.hostId}:${session.deviceId}`;
const previous = previousDeviceSessions.current.get(threadKey);
previousDeviceSessions.current.set(threadKey, new Set(sessions.map(key)));
if (!previous || shouldUseRightPanelSheet) return;
for (const session of sessions) {
if (previous?.has(key(session))) continue;
const existing = useRightPanelStore
.getState()
.byThreadKey[scopedThreadKey(activeThreadRef)]?.surfaces.some(
(surface) =>
surface.kind === "device" &&
surface.target?.hostId === session.hostId &&
surface.target.deviceId === session.deviceId,
);
if (existing) continue;
const device = deviceState.devices.find(
(entry) => entry.hostId === session.hostId && entry.id === session.deviceId,
);
if (!device) continue;
useRightPanelStore.getState().openDevice(
activeThreadRef,
{
hostId: session.hostId,
deviceId: session.deviceId,
platform: device.platform,
name: device.name,
},
true,
);
}
}, [
activeThreadRef,
deviceStateLoaded,
shouldUseRightPanelSheet,
deviceState.sessions,
deviceState.devices,
]);
const openFileSurface = useCallback(
(relativePath: string) => {
if (!activeThreadRef || !activeProject) return;
@@ -8153,7 +8184,8 @@ export default function ChatView(props: ChatViewProps) {
<DevicePanel
mode="embedded"
threadRef={activeThreadRef}
deviceId={null}
key={renderedRightPanelSurface.id}
surface={renderedRightPanelSurface}
visible={rightPanelOpen}
onDismissSetup={() => {
closeRightPanelSurface(renderedRightPanelSurface);
@@ -8725,6 +8757,10 @@ export default function ChatView(props: ChatViewProps) {
terminalLabelsById={activeTerminalLabelsById}
onActivate={activateRightPanelSurface}
onCloseSurface={closeRightPanelSurface}
onRenameDevice={(surfaceId, title) => {
if (activeThreadRef)
useRightPanelStore.getState().renameDevice(activeThreadRef, surfaceId, title);
}}
onCloseOtherSurfaces={closeOtherRightPanelSurfaces}
onCloseSurfacesToRight={closeRightPanelSurfacesToRight}
onCloseAllSurfaces={closeAllRightPanelSurfaces}
@@ -8779,6 +8815,10 @@ export default function ChatView(props: ChatViewProps) {
terminalLabelsById={activeTerminalLabelsById}
onActivate={activateRightPanelSurface}
onCloseSurface={closeRightPanelSurface}
onRenameDevice={(surfaceId, title) => {
if (activeThreadRef)
useRightPanelStore.getState().renameDevice(activeThreadRef, surfaceId, title);
}}
onCloseOtherSurfaces={closeOtherRightPanelSurfaces}
onCloseSurfacesToRight={closeRightPanelSurfacesToRight}
onCloseAllSurfaces={closeAllRightPanelSurfaces}
+26
View File
@@ -2,6 +2,32 @@ import React, { type SVGProps, useId } from "react";
import { cn } from "~/lib/utils";
export type Icon = React.FC<SVGProps<SVGSVGElement>>;
// Apple brand mark from Simple Icons (CC0).
export const AppleIcon: Icon = (props) => (
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" {...props}>
<path d="M12.152 6.896c-.948 0-2.415-1.078-3.96-1.04-2.04.027-3.91 1.183-4.961 3.014-2.117 3.675-.546 9.103 1.519 12.09 1.013 1.454 2.208 3.09 3.792 3.039 1.52-.065 2.09-.987 3.935-.987 1.831 0 2.35.987 3.96.948 1.637-.026 2.676-1.48 3.676-2.948 1.156-1.688 1.636-3.325 1.662-3.415-.039-.013-3.182-1.221-3.22-4.857-.026-3.04 2.48-4.494 2.597-4.559-1.429-2.09-3.623-2.324-4.39-2.376-2-.156-3.675 1.09-4.61 1.09zM15.53 3.83c.843-1.012 1.4-2.427 1.245-3.83-1.207.052-2.662.805-3.532 1.818-.78.896-1.454 2.338-1.273 3.714 1.338.104 2.715-.688 3.559-1.701" />
</svg>
);
export const AndroidIcon: Icon = (props) => (
<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" {...props}>
<path
d="m8 3-1-2m9 2 1-2"
fill="none"
stroke="currentColor"
strokeWidth="1.4"
strokeLinecap="round"
/>
<path
fillRule="evenodd"
d="M5 10a7 7 0 0 1 14 0H5Zm4-4a.8.8 0 1 0 0 1.6A.8.8 0 0 0 9 6Zm6 0a.8.8 0 1 0 0 1.6A.8.8 0 0 0 15 6Z"
/>
<path d="M5 11h14v7a2 2 0 0 1-2 2v2a1.5 1.5 0 0 1-3 0v-2h-4v2a1.5 1.5 0 0 1-3 0v-2a2 2 0 0 1-2-2v-7Z" />
<rect x="1" y="11" width="3" height="8" rx="1.5" />
<rect x="20" y="11" width="3" height="8" rx="1.5" />
</svg>
);
export const LinuxIcon: Icon = ({ className, ...props }) => (
<svg {...props} className={className} viewBox="-2 -2 28 28" fill="currentColor">
<path d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.36.333.292.2.68.467 1.167.467.485 0 1.053-.267 1.398-.466.195-.135.445-.334.648-.467.156-.136.149-.267.279-.267.128.016.034.134-.147.332aLine truncated
+58 -15
View File
@@ -46,6 +46,7 @@ import type { RightPanelSurface } from "~/rightPanelStore";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import { Button } from "~/components/ui/button";
import { AndroidIcon, AppleIcon } from "~/components/Icons";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { Kbd } from "~/components/ui/kbd";
import {
@@ -97,6 +98,7 @@ interface RightPanelTabsProps {
previewRuntimeTabId?: ((tabId: string) => string) | undefined;
terminalLabelsById: ReadonlyMap<string, string>;
onActivate: (surface: RightPanelSurface) => void;
onRenameDevice?: (surfaceId: string, title: string) => void;
onCloseSurface: (surface: RightPanelSurface) => void;
onCloseOtherSurfaces: (surface: RightPanelSurface) => void;
onCloseSurfacesToRight: (surface: RightPanelSurface) => void;
@@ -182,6 +184,7 @@ const SURFACE_UNAVAILABLE_HINTS = {
} as const;
type TabContextMenuAction =
| "rename"
| "copy-path"
| "toggle-mute"
| "close"
@@ -648,7 +651,7 @@ function surfaceTitle(
case "agents":
return "Agents";
case "device":
return "Device";
return surface.title ?? surface.target?.name ?? "Device";
case "preview": {
const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
if (!snapshot || snapshot.navStatus._tag === "Idle") return "Browser";
@@ -733,7 +736,13 @@ function SurfaceIcon({
case "agents":
return <Bot className="size-3 shrink-0" />;
case "device":
return <Smartphone className="size-3 shrink-0" />;
return surface.target?.platform === "ios" ? (
<AppleIcon className="size-3 shrink-0" />
) : surface.target?.platform === "android" ? (
<AndroidIcon className="size-3 shrink-0" />
) : (
<Smartphone className="size-3 shrink-0" />
);
}
}
@@ -832,6 +841,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
const browserProfiles = useBrowserDefaults().profiles;
const { resolvedTheme } = useTheme();
const tabListRef = useRef<HTMLDivElement>(null);
const [renamingDevice, setRenamingDevice] = useState<string | null>(null);
const [addSurfaceMenuOpen, setAddSurfaceMenuOpen] = useState(false);
const [tabScrollState, setTabScrollState] = useState({
hasOverflow: false,
@@ -958,6 +968,8 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
if (surfaceIndex < 0) return;
const items: ContextMenuItem<TabContextMenuAction>[] = [];
if (surface.kind === "device" && props.onRenameDevice)
items.push({ id: "rename", label: "Rename" });
if (surface.kind === "file" && surface.attachment === undefined) {
items.push({ id: "copy-path", label: "Copy path" });
}
@@ -1001,6 +1013,9 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
const action = await api.contextMenu.show(items, { x: event.clientX, y: event.clientY });
switch (action) {
case "rename":
setRenamingDevice(surface.id);
break;
case "copy-path":
if (surface.kind === "file" && surface.attachment === undefined) {
props.onCopyFilePath(surface.relativePath);
@@ -1202,20 +1217,48 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<TooltipPopup>{audio === "muted" ? "Unmute tab" : "Mute tab"}</TooltipPopup>
</Tooltip>
)}
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
className="cursor-pointer flex min-w-0 items-center"
onClick={() => props.onActivate(surface)}
>
<span className="truncate">{title}</span>
</button>
}
{renamingDevice === surface.id ? (
<input
aria-label="Device tab name"
className="w-24 min-w-0 rounded-sm bg-background px-1 outline-none ring-1 ring-ring"
defaultValue={title}
ref={(element) => {
element?.focus();
element?.select();
}}
onBlur={(event) => {
props.onRenameDevice?.(surface.id, event.currentTarget.value);
setRenamingDevice(null);
}}
onKeyDown={(event) => {
event.stopPropagation();
if (event.key === "Enter") event.currentTarget.blur();
if (event.key === "Escape") {
event.currentTarget.value = title;
event.currentTarget.blur();
}
}}
/>
<TooltipPopup>{title}</TooltipPopup>
</Tooltip>
) : (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
onDoubleClick={() => {
if (surface.kind === "device" && props.onRenameDevice)
setRenamingDevice(surface.id);
}}
className="cursor-pointer flex min-w-0 items-center"
onClick={() => props.onActivate(surface)}
>
<span className="truncate">{title}</span>
</button>
}
/>
<TooltipPopup>{title}</TooltipPopup>
</Tooltip>
)}
</div>
);
})}
@@ -0,0 +1,47 @@
import { Smartphone } from "lucide-react";
import { Spinner } from "~/components/ui/spinner";
export function DeviceLoadingView(props: {
readonly name: string;
readonly description?: string;
readonly stage: "opening" | "stream";
readonly message: string;
readonly error?: boolean;
}) {
return (
<div
role={props.error ? "alert" : "status"}
className="flex size-full items-center justify-center bg-background px-6 py-10"
>
<div className="flex max-w-sm flex-col items-center gap-3 text-center">
<div className="grid size-12 place-items-center rounded-xl border bg-muted/30">
<Smartphone className="size-6 text-muted-foreground" />
</div>
<div className="space-y-1">
<p className="text-sm font-medium">{props.name}</p>
{props.description ? (
<p className="text-xs text-muted-foreground">{props.description}</p>
) : null}
</div>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{!props.error ? <Spinner className="size-3" /> : null}
<span>{props.message}</span>
</div>
{!props.error ? (
<div
className="flex w-24 gap-1"
aria-label={
props.stage === "opening" ? "Step 1 of 2: open device" : "Step 2 of 2: connect video"
}
>
<span className="h-1 flex-1 rounded-full bg-foreground/60" />
<span
className={`h-1 flex-1 rounded-full ${props.stage === "stream" ? "bg-foreground/60" : "bg-muted"}`}
/>
</div>
) : null}
</div>
</div>
);
}
+100 -148
View File
@@ -6,7 +6,6 @@ import type {
} from "@t3tools/contracts";
import {
ChevronLeft,
Circle,
Home,
Power,
RotateCcw,
@@ -15,21 +14,13 @@ import {
Square,
X,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { useRightPanelStore, type RightPanelSurface } from "~/rightPanelStore";
import { Button } from "~/components/ui/button";
import { DiscoveryList, DiscoveryListRow } from "~/components/ui/discovery-list";
import { Dialog } from "~/components/ui/dialog";
import { WizardPopup } from "~/components/ui/wizard";
import {
Select,
SelectGroup,
SelectGroupLabel,
SelectItem,
SelectPopup,
SelectTrigger,
SelectValue,
} from "~/components/ui/select";
import { Spinner } from "~/components/ui/spinner";
import { Toggle } from "~/components/ui/toggle";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
@@ -38,28 +29,22 @@ import { deviceEnvironment, useDeviceHubAccess, useDeviceState } from "~/state/d
import { formatEnvironmentQueryError } from "~/state/query";
import { useAtomCommand } from "~/state/use-atom-command";
import { DeviceStreamView, type DeviceStreamHandle } from "./DeviceStreamView";
import { DeviceLoadingView } from "./DeviceLoadingView";
import { DeviceSetup } from "./DeviceSetup";
import { DeviceToolsPanel } from "./DeviceToolsPanel";
import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell";
const NEW_DEVICE_VALUE = "__new__";
const platformLabel = (platform: DevicePlatform) =>
platform === "ios" ? "iOS Simulators" : "Android Emulators";
const deviceKey = (device: Pick<DeviceSummary, "hostId" | "id">) =>
`${device.hostId}\u0000${device.id}`;
/**
* The Device right-panel surface: one open device (from the thread's device
* sessions) with a picker to switch or boot another. Booting and streaming are
* server-owned; this panel only asks and renders.
*/
/** Each surface owns one host/device; only the visible surface streams. */
export function DevicePanel(props: {
readonly mode: PreviewPanelMode;
readonly threadRef: ScopedThreadRef;
/** `null` renders the picker with nothing open. */
readonly deviceId: string | null;
readonly surface: Extract<RightPanelSurface, { kind: "device" }>;
readonly visible: boolean;
readonly onDismissSetup: () => void;
}) {
@@ -69,7 +54,8 @@ export function DevicePanel(props: {
const open = useAtomCommand(deviceEnvironment.open);
const close = useAtomCommand(deviceEnvironment.close);
const [operationError, setOperationError] = useState<string | null>(null);
const [pendingDeviceKey, setPendingDeviceKey] = useState<string | null>(null);
const [pendingDevice, setPendingDevice] = useState<DeviceSummary | null>(null);
const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null;
const [handle, setHandle] = useState<DeviceStreamHandle | null>(null);
const [toolsOpen, setToolsOpen] = useState(false);
const [axOverlay, setAxOverlay] = useState(false);
@@ -87,10 +73,13 @@ export function DevicePanel(props: {
() => state.sessions.filter((session) => session.threadId === threadId),
[state.sessions, threadId],
);
const activeSession =
(props.deviceId
? sessions.find((session) => session.deviceId === props.deviceId)
: undefined) ?? sessions.at(-1);
const activeSession = props.surface.target
? sessions.find(
(session) =>
session.deviceId === props.surface.target?.deviceId &&
session.hostId === props.surface.target.hostId,
)
: undefined;
const activeDevice = activeSession
? state.devices.find(
(device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId,
@@ -99,51 +88,67 @@ export function DevicePanel(props: {
const grouped = useMemo(() => groupDevices(state), [state]);
const selectDevice = useCallback(
async (value: string) => {
if (value === NEW_DEVICE_VALUE) return;
const device = state.devices.find((candidate) => deviceKey(candidate) === value);
if (!device) return;
setOperationError(null);
setPendingDeviceKey(value);
try {
const result = await open({
environmentId,
input: {
threadId,
hostId: device.hostId,
deviceId: device.id,
platform: device.platform,
},
});
if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
} finally {
setPendingDeviceKey(null);
}
},
[environmentId, open, state.devices, threadId],
);
const closeActive = useCallback(
(powerOff: boolean) => {
if (!activeSession) return;
setOperationError(null);
void close({
const selectDevice = async (value: string) => {
const device = state.devices.find((candidate) => deviceKey(candidate) === value);
if (!device) return;
setOperationError(null);
setPendingDevice(device);
try {
const result = await open({
environmentId,
input: { threadId, deviceId: activeSession.deviceId, shutdown: powerOff },
}).then((result) => {
if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
input: {
threadId,
hostId: device.hostId,
deviceId: device.id,
platform: device.platform,
},
});
},
[activeSession, close, environmentId, threadId],
);
if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
else
useRightPanelStore.getState().openDevice(props.threadRef, {
hostId: result.value.hostId,
deviceId: result.value.deviceId,
platform: device.platform,
name: device.name,
});
} finally {
setPendingDevice(null);
}
};
const closeActive = (powerOff: boolean) => {
if (!powerOff) {
useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
return;
}
if (!activeSession) return;
setOperationError(null);
void close({
environmentId,
input: {
threadId,
hostId: activeSession.hostId,
deviceId: activeSession.deviceId,
shutdown: powerOff,
},
}).then((result) => {
if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
else useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
});
};
const bootingDevices =
state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
const hostReady = state.hostStatus === "ready";
const hostBusy = state.hostStatus === "installing" || state.hostStatus === "starting";
const hostReady = Object.values(state.hostStatuses).some((host) => host.status === "ready");
const hostBusy =
!hostReady &&
Object.values(state.hostStatuses).some(
(host) => host.status === "installing" || host.status === "starting",
);
const unavailablePlatforms = state.hosts.flatMap((host) =>
host.platforms.filter((platform) => !platform.available),
host.platforms
.filter((platform) => !platform.available)
.map((platform) => ({ ...platform, hostId: host.id, hostLabel: host.label })),
);
if (loaded && (!state.onboardingCompleted || hostDisabled)) {
@@ -164,63 +169,11 @@ export function DevicePanel(props: {
return (
<PreviewPanelShell mode={props.mode}>
<div className="flex h-9 shrink-0 items-center gap-1.5 border-b px-2">
<Select
value={activeDevice ? deviceKey(activeDevice) : NEW_DEVICE_VALUE}
onValueChange={(value) => {
if (value !== null) void selectDevice(value);
}}
disabled={!loaded || hostBusy || hostDisabled || pendingDeviceKey !== null}
>
<SelectTrigger size="sm" className="min-w-0 flex-1" aria-label="Device">
<SelectValue>
{activeDevice ? (
<span className="flex items-center gap-1.5 truncate">
<Smartphone className="size-3.5 shrink-0" />
<span className="truncate">{activeDevice.name}</span>
<span className="shrink-0 text-muted-foreground">{activeDevice.version}</span>
</span>
) : (
<span className="text-muted-foreground">
{hostBusy
? state.hostStatus === "installing"
? "Installing device tools…"
: "Starting device hub…"
: "Choose a device"}
</span>
)}
</SelectValue>
</SelectTrigger>
<SelectPopup align="start" alignItemWithTrigger={false} className="min-w-72">
{grouped.map((group) => (
<SelectGroup key={group.platform}>
<SelectGroupLabel>{platformLabel(group.platform)}</SelectGroupLabel>
{group.devices.map((device) => (
<SelectItem key={deviceKey(device)} value={deviceKey(device)}>
<span className="flex w-full items-center gap-2">
<Circle
className={cn(
"size-2 shrink-0",
device.booted ? "fill-success text-success" : "text-muted-foreground/50",
)}
/>
<span className="truncate">
{device.booted ? device.name : `Start ${device.name}`}
</span>
<span className="ml-auto shrink-0 text-xs text-muted-foreground">
{device.version}
</span>
</span>
</SelectItem>
))}
</SelectGroup>
))}
{grouped.length === 0 ? (
<SelectItem value={NEW_DEVICE_VALUE} disabled>
{loaded ? "No devices found" : "Loading…"}
</SelectItem>
) : null}
</SelectPopup>
</Select>
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground">
{props.surface.target
? `${state.hosts.find((host) => host.id === props.surface.target?.hostId)?.label ?? "Device host"} · ${activeDevice?.version ?? props.surface.target.platform}`
: (pendingDevice?.name ?? "Choose a device")}
</span>
{activeDevice ? (
<>
<DeviceButton
@@ -311,7 +264,10 @@ export function DevicePanel(props: {
key={deviceKey(activeDevice)}
environmentId={environmentId}
platform={activeDevice.platform}
deviceName={activeDevice.name}
deviceDescription={`${state.hosts.find((host) => host.id === activeDevice.hostId)?.label ?? "Device host"} · ${activeDevice.version}`}
deviceId={activeDevice.id}
hostId={activeDevice.hostId}
visible={props.visible}
axOverlay={axOverlay}
onHandle={setHandle}
@@ -330,6 +286,25 @@ export function DevicePanel(props: {
/>
) : null}
</>
) : pendingDevice || hostBusy || !loaded ? (
<DeviceLoadingView
name={pendingDevice?.name ?? "Devices"}
description={
pendingDevice
? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? "Device host"} · ${pendingDevice.version}`
: ""
}
stage="opening"
message={
pendingDevice
? pendingDevice.booted
? "Opening device…"
: "Starting device…"
: state.hostStatus === "installing"
? "Installing device support…"
: "Finding devices…"
}
/>
) : (
<div className="flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
<div
@@ -338,27 +313,13 @@ export function DevicePanel(props: {
grouped.length === 0 && "my-auto items-center text-center",
)}
>
{grouped.length === 0 || hostBusy || pendingDeviceKey ? (
{grouped.length === 0 ? (
<>
{hostBusy || pendingDeviceKey ? (
<Spinner />
) : (
<Smartphone className="size-6 opacity-60" />
)}
<Smartphone className="size-6 opacity-60" />
<p className="max-w-sm">
{state.hostStatus === "failed"
? (state.hostStatusDetail ?? "The device hub failed to start.")
: pendingDeviceKey
? "Booting device… this can take a minute."
: hostBusy
? state.hostStatus === "installing"
? "Installing device tools…"
: "Starting the device hub…"
: !loaded
? "Connecting…"
: grouped.length === 0
? "No simulators or emulators were found on this environment."
: "Choose a device to open."}
: "No simulators or emulators were found on this environment."}
</p>
</>
) : null}
@@ -380,7 +341,7 @@ export function DevicePanel(props: {
</span>
}
title={device.name}
description={`${device.version} · ${device.booted ? "Running" : "Stopped"}`}
description={`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? "Running" : "Stopped"}`}
disabled={pendingDeviceKey !== null}
aria-label={`${device.booted ? "Open" : "Start"} ${device.name}`}
onClick={() => void selectDevice(deviceKey(device))}
@@ -418,15 +379,6 @@ export function DevicePanel(props: {
Refresh devices
</Button>
) : null}
{unavailablePlatforms.length > 0 && hostReady ? (
<ul className="max-w-sm space-y-1 text-xs opacity-70">
{unavailablePlatforms.map((platform) => (
<li key={platform.platform}>
{platform.platform === "ios" ? "iOS" : "Android"}: {platform.reason}
</li>
))}
</ul>
) : null}
</div>
</div>
)}
@@ -36,6 +36,7 @@ it("removes MJPEG requests while hidden and reconnects when shown", async () =>
);
const view = (visible: boolean) => (
<DeviceStreamView
hostId="local"
environmentId={EnvironmentId.make("test")}
deviceId="test"
platform="ios"
@@ -3,7 +3,7 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { cn } from "~/lib/utils";
import { refreshDeviceHubAccess, useDeviceHubAccess } from "~/state/device";
import { Spinner } from "~/components/ui/spinner";
import { DeviceLoadingView } from "./DeviceLoadingView";
import { type DeviceAxElement, fetchDeviceAxTree } from "./deviceHubApi";
import {
createDeviceStreamClient,
@@ -32,13 +32,16 @@ export function DeviceStreamView(props: {
readonly environmentId: EnvironmentId;
readonly platform: DevicePlatform;
readonly deviceId: string;
readonly deviceName?: string;
readonly deviceDescription?: string;
readonly visible: boolean;
readonly hostId: string;
/** Draw accessibility element frames over the screen. */
readonly axOverlay?: boolean;
readonly onHandle?: (handle: DeviceStreamHandle | null) => void;
readonly onScreen?: (screen: DeviceScreenSize | null) => void;
}) {
const access = useDeviceHubAccess(props.environmentId);
const access = useDeviceHubAccess(props.environmentId, props.hostId);
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const clientRef = useRef<DeviceStreamClient | null>(null);
const [status, setStatus] = useState<DeviceStreamStatus>("connecting");
@@ -314,12 +317,14 @@ export function DeviceStreamView(props: {
</div>
) : null}
{status !== "streaming" ? (
<div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center gap-2 bg-background/70 text-sm text-muted-foreground">
{status === "connecting" ? <Spinner /> : null}
<span>{status === "error" ? (detail ?? "Stream failed.") : "Connecting to device…"}</span>
{status === "connecting" && detail ? (
<span className="max-w-xs text-center text-xs opacity-70">{detail}</span>
) : null}
<div className="pointer-events-none absolute inset-0">
<DeviceLoadingView
name={props.deviceName ?? "Device"}
description={props.deviceDescription ?? ""}
stage="stream"
message={status === "error" ? (detail ?? "Stream failed.") : "Connecting video…"}
error={status === "error"}
/>
</div>
) : null}
</div>
@@ -105,6 +105,7 @@ const deviceState = (overrides: Partial<DeviceServiceState> = {}): DeviceService
},
],
hostStatus: "ready",
hostStatuses: {},
devices: [],
sessions: [],
onboardingCompleted: false,
+81
View File
@@ -21,6 +21,87 @@ beforeEach(() => {
});
describe("rightPanelStore", () => {
it("gives each host/device its own tab and preserves renamed tabs", () => {
const store = useRightPanelStore.getState();
const android = {
hostId: "nucbox",
deviceId: "emulator-5580",
name: "Pixel",
platform: "android",
} as const;
const ios = { hostId: "macmini", deviceId: "ios-1", name: "iPhone", platform: "ios" } as const;
store.open(refA, "device");
store.openDevice(refA, android);
store.open(refA, "device");
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces,
).toHaveLength(2);
store.openDevice(refA, ios);
let state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces.map((surface) => surface.id)).toEqual([
"device:nucbox:emulator-5580",
"device:macmini:ios-1",
]);
store.renameDevice(refA, "device:nucbox:emulator-5580", "Android test");
store.openDevice(refA, android);
state = selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA);
expect(state.surfaces).toHaveLength(2);
expect(state.surfaces[0]).toMatchObject({ title: "Android test", target: android });
expect(state.activeSurfaceId).toBe("device:nucbox:emulator-5580");
store.closeSurface(refA, state.activeSurfaceId!);
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces,
).toEqual([expect.objectContaining({ target: ios })]);
});
it("does not collide when two hosts expose the same device id", () => {
const store = useRightPanelStore.getState();
const device = { deviceId: "emulator-5554", name: "Pixel", platform: "android" } as const;
store.openDevice(refA, { ...device, hostId: "a:b" });
store.openDevice(refA, { ...device, hostId: "a" });
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces,
).toHaveLength(2);
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refB).surfaces,
).toHaveLength(0);
});
it.each(["one", "all", "others", "right"])(
"keeps device tabs dismissed across reload after closing %s",
(mode) => {
const store = useRightPanelStore.getState();
const target = {
hostId: "nucbox",
deviceId: "emulator-5580",
name: "Pixel",
platform: "android",
} as const;
store.open(refA, "files");
store.openDevice(refA, target);
if (mode === "one") store.closeSurface(refA, "device:nucbox:emulator-5580");
if (mode === "all") store.closeAllSurfaces(refA);
if (mode === "others") store.closeOtherSurfaces(refA, "files");
if (mode === "right") store.closeSurfacesToRight(refA, "files");
const persisted = JSON.parse(
JSON.stringify({ byThreadKey: useRightPanelStore.getState().byThreadKey }),
);
useRightPanelStore.setState(migratePersistedRightPanelState(persisted));
store.openDevice(refA, target, true);
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces.some(
(surface) => surface.kind === "device",
),
).toBe(false);
store.openDevice(refA, target);
expect(
selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, refA).surfaces.some(
(surface) => surface.kind === "device",
),
).toBe(true);
},
);
const completedDiff = { id: "diff", kind: "diff" } as const;
const linkedPullRequest = pullRequestSurface({
projectId: "project-a",
+87 -10
View File
@@ -32,15 +32,17 @@ const RIGHT_PANEL_KINDS = [
] as const;
export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
export interface DeviceTabTarget {
hostId: string;
deviceId: string;
platform: "ios" | "android";
name: string;
}
export type RightPanelSurface =
| { id: `browser:${string}`; kind: "preview"; resourceId: string }
| { id: "browser:new"; kind: "preview"; resourceId: null }
/**
* One Device tab per thread. The tab is the surface; which device it shows
* comes from the thread's server-side device sessions, so an agent opening a
* device from another client lands in the same tab.
*/
| { id: "device"; kind: "device" }
| { id: "device" | `device:${string}`; kind: "device"; target?: DeviceTabTarget; title?: string }
| {
id: `terminal:${string}`;
kind: "terminal";
@@ -90,7 +92,7 @@ const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
// v10 keys pull-request surfaces by reference instead of a singleton tab.
// v11 stops persisting the pull-request list's shared panel, so a restart opens the page fresh.
// v12 adds the device surface.
const RIGHT_PANEL_STORAGE_VERSION = 12;
const RIGHT_PANEL_STORAGE_VERSION = 13;
/** A fixed workspace-level ref: each PR surface carries its own real environment. */
export const PULL_REQUESTS_PANEL_REF = scopeThreadRef(
@@ -108,6 +110,7 @@ export interface ThreadRightPanelState {
isOpen: boolean;
activeSurfaceId: string | null;
surfaces: RightPanelSurface[];
dismissedDeviceSurfaceIds?: string[];
}
interface RightPanelStoreState {
@@ -128,6 +131,8 @@ interface RightPanelStoreState {
ref: ScopedThreadRef,
kind: Exclude<RightPanelKind, "file" | "terminal" | "pull-request">,
) => void;
openDevice: (ref: ScopedThreadRef, target: DeviceTabTarget, automatic?: boolean) => void;
renameDevice: (ref: ScopedThreadRef, surfaceId: string, title: string) => void;
openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
openAttachment: (ref: ScopedThreadRef, attachment: ChatFileAttachment) => void;
@@ -281,7 +286,12 @@ const updateThread = (
): Record<string, ThreadRightPanelState> => {
const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
const next = updater(current);
if (!next.isOpen && next.activeSurfaceId === null && next.surfaces.length === 0) {
if (
!next.isOpen &&
next.activeSurfaceId === null &&
next.surfaces.length === 0 &&
!next.dismissedDeviceSurfaceIds?.length
) {
if (!(threadKey in byThreadKey)) return byThreadKey;
const { [threadKey]: _removed, ...rest } = byThreadKey;
return rest;
@@ -306,7 +316,25 @@ const userAction = (
threadKey: string,
updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
): Partial<RightPanelStoreState> => ({
byThreadKey: updateThread(state.byThreadKey, threadKey, updater),
byThreadKey: updateThread(state.byThreadKey, threadKey, (current) => {
const next = updater(current);
const removed = current.surfaces.filter(
(surface) =>
surface.kind === "device" &&
surface.target &&
!next.surfaces.some((entry) => entry.id === surface.id),
);
if (removed.length === 0) return next;
return {
...next,
dismissedDeviceSurfaceIds: [
...new Set([
...(next.dismissedDeviceSurfaceIds ?? []),
...removed.map((surface) => surface.id),
]),
],
};
}),
userActionRevisionByThreadKey: {
...state.userActionRevisionByThreadKey,
[threadKey]: (state.userActionRevisionByThreadKey[threadKey] ?? 0) + 1,
@@ -426,7 +454,22 @@ export function migratePersistedRightPanelState(persistedState: unknown): {
// first survivor instead of rendering an open empty panel.
const activeSurfaceId =
persistedActiveSurfaceId ?? (isOpen ? (surfaces[0]?.id ?? null) : null);
return [threadKey, { isOpen, surfaces, activeSurfaceId }];
return [
threadKey,
{
isOpen,
surfaces,
activeSurfaceId,
...(Array.isArray(validThreadState?.dismissedDeviceSurfaceIds)
? {
dismissedDeviceSurfaceIds:
validThreadState.dismissedDeviceSurfaceIds.filter(
(id): id is string => typeof id === "string",
),
}
: {}),
},
];
}),
)
: {};
@@ -472,6 +515,40 @@ export const useRightPanelStore = create<RightPanelStoreState>()(
return upsertSurface(current, singletonSurface(kind));
}),
),
openDevice: (ref, target, automatic = false) =>
set((state) =>
(automatic ? automaticUpdate : userAction)(state, scopedThreadKey(ref), (current) => {
const id =
`device:${encodeURIComponent(target.hostId)}:${encodeURIComponent(target.deviceId)}` as const;
if (automatic && current.dismissedDeviceSurfaceIds?.includes(id)) return current;
const surface: RightPanelSurface = { id, kind: "device", target };
const existing = current.surfaces.find((entry) => entry.id === id);
const surfaces = existing
? current.surfaces.filter((entry) => entry.id !== "device")
: current.surfaces.map((entry) => (entry.id === "device" ? surface : entry));
return upsertSurface(
{
...current,
surfaces,
dismissedDeviceSurfaceIds: (current.dismissedDeviceSurfaceIds ?? []).filter(
(entry) => entry !== id,
),
},
existing ?? surface,
);
}),
),
renameDevice: (ref, surfaceId, title) =>
set((state) =>
userAction(state, scopedThreadKey(ref), (current) => ({
...current,
surfaces: current.surfaces.map((surface) =>
surface.id === surfaceId && surface.kind === "device"
? { ...surface, title: title.trim() || surface.target?.name || "Device" }
: surface,
),
})),
),
openBrowser: (ref, tabId) =>
set((state) =>
userAction(state, scopedThreadKey(ref), (current) => {
+14 -3
View File
@@ -1,3 +1,4 @@
import { useMemo } from "react";
import { useAtomValue } from "@effect/atom-react";
import { createDeviceEnvironmentAtoms } from "@t3tools/client-runtime/state/device";
import {
@@ -18,7 +19,8 @@ export const deviceEnvironment = createDeviceEnvironmentAtoms(connectionAtomRunt
const EMPTY_DEVICE_STATE: DeviceServiceState = {
hosts: [],
hostStatus: "idle",
hostStatus: "disabled",
hostStatuses: {},
devices: [],
sessions: [],
onboardingCompleted: false,
@@ -54,11 +56,20 @@ const deviceHubAccessAtom = Atom.family((environmentId: EnvironmentId) =>
.pipe(Atom.setIdleTTL(60_000), Atom.withLabel(`device-hub-access:${environmentId}`)),
);
export function useDeviceHubAccess(environmentId: EnvironmentId | null): DeviceHubAccess | null {
export function useDeviceHubAccess(
environmentId: EnvironmentId | null,
hostId = "local",
): DeviceHubAccess | null {
const result = useAtomValue(
environmentId === null ? EMPTY_ACCESS_ATOM : deviceHubAccessAtom(environmentId),
);
return AsyncResult.isSuccess(result) ? result.value : null;
return useMemo(
() =>
AsyncResult.isSuccess(result)
? { ...result.value, query: { ...result.value.query, hostId } }
: null,
[result, hostId],
);
}
const EMPTY_ACCESS_ATOM = Atom.make(AsyncResult.initial<DeviceHubAccess, never>()).pipe(
+8
View File
@@ -95,6 +95,13 @@ export const DeviceServiceState = Schema.Struct({
hosts: Schema.Array(DeviceHostSummary),
hostStatus: DeviceHostStatus,
hostStatusDetail: Schema.optional(Schema.String),
hostStatuses: Schema.Record(
DeviceHostId,
Schema.Struct({
status: DeviceHostStatus,
detail: Schema.optional(Schema.String),
}),
),
devices: Schema.Array(DeviceSummary),
sessions: Schema.Array(DeviceSession),
bootingDevices: Schema.optional(
@@ -129,6 +136,7 @@ export const DeviceOpenInput = Schema.Struct({
export type DeviceOpenInput = typeof DeviceOpenInput.Type;
export const DeviceCloseInput = Schema.Struct({
hostId: Schema.optional(DeviceHostId),
threadId: ThreadId,
/** Omit to close every device session for the thread. */
deviceId: Schema.optional(DeviceId),