Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 7 additions & 9 deletions apps/mobile/src/state/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ function applyEvent(current: ThreadPreviewTabs, event: PreviewEvent): ThreadPrev
return { ...current, serverEpoch: event.serverEpoch, revision: event.revision, sessions };
}

const PREVIEW_TABS_IDLE_TTL_MS = 5 * 60_000;

const threadPreviewTabsAtom = Atom.family((threadKey: string) => {
const ref = parseScopedThreadKey(threadKey);
if (ref === null) return emptyTabsAtom;
Expand All @@ -74,7 +76,6 @@ const threadPreviewTabsAtom = Atom.family((threadKey: string) => {
});
const eventsAtom = previewEnvironment.events({ environmentId: ref.environmentId, input: {} });
return Atom.make((get) => {
let disposed = false;
let state = EMPTY_TABS;
// Lists can land after events they predate; replay newer events on each list.
let list: PreviewListResult | null = null;
Expand All @@ -92,9 +93,6 @@ const threadPreviewTabsAtom = Atom.family((threadKey: string) => {
);
return events.reduce<ThreadPreviewTabs>(applyEvent, { ...result, listed: true });
};
get.addFinalizer(() => {
disposed = true;
});
get.subscribe(listAtom, (result) => {
if (!AsyncResult.isSuccess(result)) return;
const next = applyList(result.value);
Expand All @@ -116,11 +114,11 @@ const threadPreviewTabsAtom = Atom.family((threadKey: string) => {
get.mount(eventsAtom);
const cached = get.once(listAtom);
if (AsyncResult.isSuccess(cached)) state = applyList(cached.value) ?? state;
queueMicrotask(() => {
if (!disposed) get.refresh(listAtom);
});
return state;
}).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`mobile-preview-tabs:${threadKey}`));
}).pipe(
Atom.setIdleTTL(PREVIEW_TABS_IDLE_TTL_MS),
Atom.withLabel(`mobile-preview-tabs:${threadKey}`),
);
});

interface ServerBrowserTabs {
Expand All @@ -142,7 +140,7 @@ const serverBrowserTabsAtom = Atom.family((threadKey: string) =>
tabs: tabs.sessions.filter((session) => session.runtime === "server"),
loaded: tabs.listed,
};
}).pipe(Atom.withEquality(sameServerBrowserTabs), Atom.setIdleTTL(1_000)),
}).pipe(Atom.withEquality(sameServerBrowserTabs), Atom.setIdleTTL(PREVIEW_TABS_IDLE_TTL_MS)),
);
const emptyServerBrowserTabsAtom = Atom.make<ServerBrowserTabs>({ tabs: [], loaded: false });
const serverBrowserTabCountAtom = Atom.family((threadKey: string) =>
Expand Down
13 changes: 2 additions & 11 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,6 @@ import {
threadHandoffSendBlockReason,
useThreadHandoffBannerItem,
} from "./chat/ThreadHandoffBanner";
import { useDeviceState } from "~/state/device";
import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar";
import { ComposerContextPermissions } from "./ComposerContextPermissions";
import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";
Expand Down Expand Up @@ -2282,9 +2281,6 @@ export default function ChatView(props: ChatViewProps) {
const linkedItemsSurfaceAvailable =
pullRequestsSurfaceAvailable ||
(isServerThread && (activeThreadShell?.issues?.length ?? 0) > 0);
const { state: deviceState, loaded: deviceStateLoaded } = useDeviceState(
activeThreadRef?.environmentId ?? null,
);
// The thread's own change request, placed against the project it belongs to. Without a
// project there is nothing to resolve it against, so the caller falls back to the browser.
const activeProjectRepository = sourceControlClients.repositorySelector(
Expand Down Expand Up @@ -2710,8 +2706,7 @@ export default function ChatView(props: ChatViewProps) {
activeProject,
activeRightPanelSurface,
activePreviewState,
deviceState,
deviceStateLoaded,
serverSettings: serverConfig?.settings ?? null,
pullRequestPanelTarget,
threadPanelPresentation,
isServerThread,
Expand Down Expand Up @@ -3719,11 +3714,7 @@ export default function ChatView(props: ChatViewProps) {
className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background"
>
{embedded ? null : (
<DeviceSetupDialogHost
threadKey={activeThreadKey}
threadRef={activeThreadRef}
state={deviceState}
/>
<DeviceSetupDialogHost threadKey={activeThreadKey} threadRef={activeThreadRef} />
)}
{rightPanelControlsAtRoot && !embedded ? panelLayoutControls : null}
<div
Expand Down
28 changes: 16 additions & 12 deletions apps/web/src/components/chat/ChatOverlayHosts.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type {
DeviceServiceState,
EnvironmentId,
MessageId,
OrchestrationV2ThreadProjection,
Expand Down Expand Up @@ -28,6 +27,7 @@ import { Button } from "../ui/button";
import { Dialog } from "../ui/dialog";
import { WizardPopup } from "../ui/wizard";
import { findRevertCheckpoint } from "../../session-logic";
import { useDeviceState } from "../../state/device";
import { filesystemEnvironment } from "../../state/filesystem";
import { useEnvironmentQuery } from "../../state/query";
import { registerThreadOverlay } from "./threadOverlayRetention";
Expand Down Expand Up @@ -108,10 +108,23 @@ export function openDeviceSetupDialog(threadKey: string): void {
appAtomRegistry.set(deviceSetupDialogAtom, { threadKey, value: true });
}

function DeviceSetupDialogContent(props: { readonly threadRef: ScopedThreadRef }) {
const { state } = useDeviceState(props.threadRef.environmentId);
return (
<DeviceSetup
environmentId={props.threadRef.environmentId}
state={state}
onComplete={() => {
useRightPanelStore.getState().open(props.threadRef, "device");
closeThreadOverlay(deviceSetupDialogAtom);
}}
/>
);
}

export function DeviceSetupDialogHost(props: {
readonly threadKey: string | null;
readonly threadRef: ScopedThreadRef | null;
readonly state: DeviceServiceState;
}) {
const open = useThreadOverlay(deviceSetupDialogAtom, props.threadKey) !== null;
const { threadRef } = props;
Expand All @@ -123,16 +136,7 @@ export function DeviceSetupDialogHost(props: {
}}
>
<WizardPopup>
{threadRef ? (
<DeviceSetup
environmentId={threadRef.environmentId}
state={props.state}
onComplete={() => {
useRightPanelStore.getState().open(threadRef, "device");
closeThreadOverlay(deviceSetupDialogAtom);
}}
/>
) : null}
{open && threadRef ? <DeviceSetupDialogContent threadRef={threadRef} /> : null}
</WizardPopup>
</Dialog>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { EnvironmentId, type HostResourcesSnapshot } from "@t3tools/contracts";
import { describe, expect, it, vi } from "vite-plus/test";

import { render } from "../../../test/render";
import { act, render } from "../../../test/render";
import { HiddenThreadContext } from "./backgroundThread";
import { ThreadDetailsMachineLoad } from "./ThreadDetailsMachineLoad";

const environmentId = EnvironmentId.make("studio");
const state = vi.hoisted(() => ({
phase: "connected",
sample: null as unknown,
resourcesReads: 0,
presentationsAtom: Symbol("presentationsAtom"),
resourcesAtom: Symbol("resourcesAtom"),
}));
Expand Down Expand Up @@ -41,6 +43,7 @@ vi.mock("@effect/atom-react", async (importOriginal) => {
...actual,
useAtomValue: (atom: unknown, select?: (value: unknown) => unknown) => {
if (atom === state.resourcesAtom) {
state.resourcesReads += 1;
return state.sample === null
? { _tag: "Initial", waiting: true }
: { _tag: "Success", value: state.sample, waiting: false };
Expand All @@ -49,7 +52,7 @@ vi.mock("@effect/atom-react", async (importOriginal) => {
const presentations = new Map([[environmentId, { connection: { phase: state.phase } }]]);
return select ? select(presentations) : presentations;
}
return (actual.useAtomValue as (...args: ReadonlyArray<unknown>) => unknown)(atom, select);
return { _tag: "Initial", waiting: false };
},
};
});
Expand Down Expand Up @@ -84,4 +87,66 @@ describe("ThreadDetailsMachineLoad", () => {
await screen.rerender(<ThreadDetailsMachineLoad environmentId={environmentId} />);
expect(screen.container.textContent).toContain("17%");
});

it("stops reading liveHostResources while the thread is hidden and resumes when visible", async () => {
state.phase = "connected";
state.sample = sample(0.42);
state.resourcesReads = 0;
await using screen = await render(
<HiddenThreadContext value={true}>
<ThreadDetailsMachineLoad environmentId={environmentId} />
</HiddenThreadContext>,
);
expect(screen.container.textContent).toBe("");
expect(state.resourcesReads).toBe(0);

await screen.rerender(
<HiddenThreadContext value={false}>
<ThreadDetailsMachineLoad environmentId={environmentId} />
</HiddenThreadContext>,
);
expect(screen.container.textContent).toContain("42%");
const readsWhileVisible = state.resourcesReads;
expect(readsWhileVisible).toBeGreaterThan(0);

await screen.rerender(
<HiddenThreadContext value={true}>
<ThreadDetailsMachineLoad environmentId={environmentId} />
</HiddenThreadContext>,
);
expect(screen.container.textContent).toBe("");
expect(state.resourcesReads).toBe(readsWhileVisible);
});

it("stops reading liveHostResources when the document is hidden and resumes on visibilitychange", async () => {
state.phase = "connected";
state.sample = sample(0.35);
state.resourcesReads = 0;
let visibilityState: DocumentVisibilityState = "visible";
const spy = vi
.spyOn(document, "visibilityState", "get")
.mockImplementation(() => visibilityState);
try {
await using screen = await render(<ThreadDetailsMachineLoad environmentId={environmentId} />);
expect(screen.container.textContent).toContain("35%");
const readsWhileVisible = state.resourcesReads;
expect(readsWhileVisible).toBeGreaterThan(0);

visibilityState = "hidden";
await act(() => {
document.dispatchEvent(new Event("visibilitychange"));
});
expect(screen.container.textContent).toBe("");
expect(state.resourcesReads).toBe(readsWhileVisible);

visibilityState = "visible";
await act(() => {
document.dispatchEvent(new Event("visibilitychange"));
});
expect(screen.container.textContent).toContain("35%");
expect(state.resourcesReads).toBeGreaterThan(readsWhileVisible);
} finally {
spy.mockRestore();
}
});
});
34 changes: 32 additions & 2 deletions apps/web/src/components/chat/ThreadDetailsMachineLoad.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,37 @@ import { useAtomValue } from "@effect/atom-react";
import {
type EnvironmentId,
type HostPressureLevel,
type HostResourcesSnapshot,
worstHostPressureLevel,
} from "@t3tools/contracts";
import { AsyncResult, Atom } from "effect/reactivity";
import { useGT, plural, part } from "gt-react";
import { useState } from "react";
import { use, useState, useSyncExternalStore } from "react";

import { formatBytes } from "../../lib/formatBytes";
import { useServerConfigs } from "../../state/entities";
import { environmentPresentations } from "../../state/presentation";
import { serverEnvironment } from "../../state/server";
import { HiddenThreadContext } from "./backgroundThread";
import { ThreadDetailsSection } from "./ThreadDetailsSection";
import { UsageRow, type UsageTone } from "./ThreadDetailsUsage";

const IDLE_HOST_RESOURCES_ATOM = Atom.make(
AsyncResult.initial<HostResourcesSnapshot, never>(),
).pipe(Atom.withLabel("thread-details:machine-load:idle"));

function subscribeDocumentVisibility(onStoreChange: () => void): () => void {
if (typeof document === "undefined") return () => {};
document.addEventListener("visibilitychange", onStoreChange);
return () => document.removeEventListener("visibilitychange", onStoreChange);
}

function readDocumentVisible(): boolean {
return typeof document === "undefined" || document.visibilityState !== "hidden";
}

const readServerDocumentVisible = () => true;

const toneOf = (level: HostPressureLevel | undefined): UsageTone =>
level === "severe" ? "error" : level === "elevated" ? "warning" : null;

Expand All @@ -26,7 +45,18 @@ export function ThreadDetailsMachineLoad({
readonly environmentId: EnvironmentId;
}) {
const gt = useGT();
const result = useAtomValue(serverEnvironment.liveHostResources({ environmentId, input: {} }));
const hiddenThread = use(HiddenThreadContext);
const documentVisible = useSyncExternalStore(
subscribeDocumentVisibility,
readDocumentVisible,
readServerDocumentVisible,
);
const pollingActive = !hiddenThread && documentVisible;
const result = useAtomValue(
pollingActive
? serverEnvironment.liveHostResources({ environmentId, input: {} })
: IDLE_HOST_RESOURCES_ATOM,
);
const pressure = useServerConfigs().get(environmentId)?.hostPressure;
const connected = useAtomValue(
environmentPresentations.presentationsAtom,
Expand Down
29 changes: 21 additions & 8 deletions apps/web/src/components/chat/useRightPanelActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ import type { ThreadPreviewState } from "../../previewStateStore";
import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
import { useStableCallback } from "../../hooks/useStableCallback";
import { type ScopedThreadRef, type PreviewSessionSnapshot } from "@t3tools/contracts";
import {
type DeviceServiceState,
type ScopedThreadRef,
type PreviewSessionSnapshot,
type ServerSettings,
} from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { sideThreadComposer, sideThreadKindOf } from "@t3tools/client-runtime/side-thread";
import { readThreadShell } from "../../state/entities";
Expand Down Expand Up @@ -37,7 +42,7 @@ import {
} from "../preview/agentOpenedPreviews";
import { getClientSettings } from "../../hooks/useSettings";
import type { threadPullRequestPanelTarget } from "../pullRequest/pullRequestDetail.logic";
import type { useDeviceState } from "../../state/device";
import { readLoadedDeviceState } from "../../state/device";
import { stackedThreadToast, toastManager } from "../ui/toast";
import { openDeviceSetupDialog } from "./ChatOverlayHosts";
import { previewEnvironment } from "../../state/preview";
Expand All @@ -48,8 +53,7 @@ interface RightPanelActionsInput {
readonly activeProject: EnvironmentProject | null;
readonly activeRightPanelSurface: RightPanelSurface | null;
readonly activePreviewState: ThreadPreviewState;
readonly deviceState: ReturnType<typeof useDeviceState>["state"];
readonly deviceStateLoaded: boolean;
readonly serverSettings: ServerSettings | null;
readonly pullRequestPanelTarget: ReturnType<typeof threadPullRequestPanelTarget> | null;
readonly threadPanelPresentation: ThreadPanelPresentation;
readonly isServerThread: boolean;
Expand All @@ -71,6 +75,15 @@ interface RightPanelActionsInput {
readonly onDiffPanelOpen: (() => void) | undefined;
}

export function needsDeviceSetup(
loadedState: Pick<DeviceServiceState, "onboardingCompleted" | "hostStatus"> | null,
serverSettings: Pick<ServerSettings, "enableDeviceSupport" | "deviceOnboardingCompleted"> | null,
): boolean {
return loadedState !== null
? !loadedState.onboardingCompleted || loadedState.hostStatus === "disabled"
: !serverSettings?.enableDeviceSupport || !serverSettings.deviceOnboardingCompleted;
}

/**
* Opening, closing, and arranging the right panel's surfaces: browser, diff, files, pull
* requests, device, and terminal tabs.
Expand All @@ -81,8 +94,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
activeProject,
activeRightPanelSurface,
activePreviewState,
deviceState,
deviceStateLoaded,
serverSettings,
pullRequestPanelTarget,
threadPanelPresentation,
isServerThread,
Expand Down Expand Up @@ -163,7 +175,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
const addPullRequestsSurfaceStable = useStableCallback(addPullRequestsSurface);
const addDeviceSurface = () => {
if (!activeThreadRef) return;
if (!deviceState.onboardingCompleted || deviceState.hostStatus === "disabled") {
if (needsDeviceSetup(readLoadedDeviceState(activeThreadRef.environmentId), serverSettings)) {
openDeviceSetupDialog(scopedThreadKey(activeThreadRef));
return;
}
Expand All @@ -182,7 +194,8 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
floatPanelSurfaceOnClose(activeThreadRef, source, {
autoShowFloatingPreview: getClientSettings().browserAutoShowFloatingPreview,
previewState: activePreviewState,
deviceState: deviceStateLoaded ? deviceState : null,
deviceState:
source.kind === "device" ? readLoadedDeviceState(activeThreadRef.environmentId) : null,
});
}
useRightPanelStore.getState().setMaximized(activeThreadRef, false);
Expand Down
8 changes: 0 additions & 8 deletions apps/web/src/components/desktop/RunningThreadKeepAlive.tsx

This file was deleted.

Loading
Loading