Skip to content
Merged
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
1 change: 1 addition & 0 deletions apps/mobile/src/state/peerLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { relayEnvironmentDiscovery } from "./relay";
import { useEnvironmentQuery } from "./query";
import { useAtomCommand } from "./use-atom-command";

// Web adds linked machines on its own (`linkedEnvironmentsToAutoAdd`); mobile does not yet.
export const peerLinkEnvironment = createPeerLinkEnvironmentAtoms(connectionAtomRuntime);

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { Skeleton } from "../ui/skeleton";
import { toastManager } from "../ui/toast";
import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
import { presentSavedCloudEnvironmentConnection } from "./cloudEnvironmentConnectionPresentation";
import { undismissLinkedEnvironment } from "../../state/linkedEnvironmentDismissals";

const EMPTY_DISCOVERY_REFRESH_INTERVAL_MS = 5_000;

Expand Down Expand Up @@ -111,7 +112,11 @@ export function CloudEnvironmentConnectRows({
label: environment.label,
}),
}),
);
).then((result) => {
// Adding it back is the way back from removing it, so it may be added on its own again.
if (result._tag === "Success") void undismissLinkedEnvironment(environment.environmentId);
return result;
});
const [connectingEnvironmentIds, setConnectingEnvironmentIds] = useState<
ReadonlySet<EnvironmentId>
>(new Set());
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/settings/AddEnvironmentDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import { desktopSshHostsStateAtom, filterDiscoveredSshHosts } from "~/state/desk
import { type EnvironmentPresentation, useRelayEnvironmentDiscovery } from "~/state/environments";
import { useAtomCommand } from "../../state/use-atom-command";
import { primaryServerKeybindingsAtom } from "~/state/server";
import { undismissLinkedEnvironment } from "~/state/linkedEnvironmentDismissals";
import {
resolveShortcutCommand,
shortcutLabelForCommand,
Expand Down Expand Up @@ -474,6 +475,7 @@ export function AddEnvironmentDialog({
}
return;
}
void undismissLinkedEnvironment(relayRouteOffer.environmentId);
handleOpenChange(false);
toastManager.add({
type: "success",
Expand Down
6 changes: 6 additions & 0 deletions apps/web/src/components/settings/ConnectionsSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ import {
peerLinkEnvironment,
usePeerLinkHosts,
} from "~/state/peerLinks";
import { dismissLinkedEnvironment } from "~/state/linkedEnvironmentDismissals";
import { LoadBalancingSettings } from "./LoadBalancingSettings";
import { PullRequestRoutingSettings } from "./PullRequestRoutingSettings";
import { Input } from "../ui/input";
Expand Down Expand Up @@ -691,10 +692,15 @@ function ConnectionsSettingsContent({
setSavedBackendError(null);
// Read before removing: the lists are this app's, and removal changes what it reports.
const linkingHosts = hostsLinking(peerLinkHosts, environmentId);
// A host linking it, loaded here or not, would add it straight back. Recorded first, so it
// never does.
const undoDismiss = dismissLinkedEnvironment(environmentId);
const result = await removeEnvironment(environmentId);
setRemovingSavedEnvironmentId(null);
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) return;
// Still in the app, so nothing should keep it from coming back.
void undoDismiss.then((undo) => undo());
const error = squashAtomCommandFailure(result);
const message = error instanceof Error ? error.message : "Failed to remove backend.";
setSavedBackendError(message);
Expand Down
81 changes: 35 additions & 46 deletions apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import {
ANOTHER_ADDRESS,
appPairingAddresses,
type KnownEnvironmentRow,
linkRequestFailureMessage,
} from "@t3tools/client-runtime/link-request";
Expand All @@ -25,9 +24,15 @@ import { useId, useRef, useState } from "react";
import { requestConfirmDialog } from "~/confirmDialog";
import { mintPairingCodeOn } from "~/state/peerPairingCode";
import { environmentCatalog } from "~/connection/catalog";
import { connectPairing as connectPairingAtom } from "~/connection/onboarding";
import { useKnownEnvironments } from "~/state/knownEnvironments";
import { forgetLinkOnConnect, peerLinkEnvironment, useLinkableMachines } from "~/state/peerLinks";
import { linkedEnvironmentsRefreshKey, useKnownEnvironments } from "~/state/knownEnvironments";
import { dismissLinkedEnvironment } from "~/state/linkedEnvironmentDismissals";
import {
addingLinkedEnvironmentsAtom,
addLinkedEnvironmentToApp,
forgetLinkOnConnect,
peerLinkEnvironment,
useLinkableMachines,
} from "~/state/peerLinks";
import { useEnvironmentScope, usePreparedConnection } from "~/state/session";
import { useAtomCommand } from "~/state/use-atom-command";
import { accessConfig } from "../auth/ConnectAgentSurface";
Expand Down Expand Up @@ -76,7 +81,7 @@ export function LinkedEnvironmentsSettings({
if (!known.isPending) known.refresh();
},
{
key: `linked-environments:${environmentId}`,
key: linkedEnvironmentsRefreshKey(environmentId),
intervalMs: null,
refreshOnShow: true,
},
Expand Down Expand Up @@ -176,11 +181,11 @@ function LinkedEnvironmentRow({
const health = peerLinkHealth(link, DateTime.makeUnsafe(nowMinute));
const unlink = useAtomCommand(peerLinkEnvironment.unlink, { label: "unlink environment" });
const canUnlink = useAtomValue(peerLinkEnvironment.unlink.permissionAtom(environmentId));
const addToApp = useAtomCommand(peerLinkEnvironment.addToApp, { reportFailure: false });
const canAddToApp = useAtomValue(peerLinkEnvironment.addToApp.permissionAtom(environmentId));
const connectPairing = useAtomCommand(connectPairingAtom, { reportFailure: false });
const removeFromApp = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
const [busy, setBusy] = useState(false);
// An add of this machine runs from any host's row or the automatic add; one at a time.
const adding = useAtomValue(addingLinkedEnvironmentsAtom).has(link.environmentId);
const forget = async () => {
const confirmed = await (requestConfirmDialog(
`Forget ${link.label}? Agents here stop working there. Revoke "T3 Code · …" in ${link.label}'s Sharing & access to end the session there too. An app added through this link stays under Authorized clients there until you revoke it.`,
Expand All @@ -203,55 +208,33 @@ function LinkedEnvironmentRow({
{ variant: "destructive" },
) ?? Promise.resolve(false));
if (!alsoRemove) return;
// Another host may still link it. Recorded first, so it is never added back on its own.
const undoDismiss = dismissLinkedEnvironment(link.environmentId);
const removed = await removeFromApp(link.environmentId);
if (removed._tag === "Success") forgetLinkOnConnect(link.environmentId);
else if (!isAtomCommandInterrupted(removed)) {
// Still in the app, so it is not removed, and nothing should keep it from coming back.
void undoDismiss.then((undo) => undo());
failureToast(`Could not remove ${row.label}`, String(squashAtomCommandFailure(removed)));
}
};
const connectAt = async (hosts: ReadonlyArray<string>, pairingCode: string) => {
// A host that does not answer as this machine never receives the code, so the next can.
let result: Awaited<ReturnType<typeof connectPairing>> | undefined;
for (const host of hosts) {
result = await connectPairing({
host,
pairingCode,
expectedEnvironmentId: link.environmentId,
});
if (result._tag === "Success" || isAtomCommandInterrupted(result)) return result;
}
return result;
};
const add = async () => {
if (row.appAddress === null) return;
setBusy(true);
const issued = await addToApp({ environmentId, input: { environmentId: link.environmentId } });
// Where the peer just answered first, then its other addresses this client reaches.
const hosts =
issued._tag === "Success" ? appPairingAddresses(issued.value.urls, row.onHostMachine) : [];
const added =
issued._tag === "Success" ? await connectAt(hosts, issued.value.credential) : issued;
setBusy(false);
if (added === undefined) {
failureToast(
`Could not add ${link.label} to this app`,
`${link.label} answers only at addresses this device cannot open.`,
);
return;
}
if (added._tag === "Failure") {
if (!isAtomCommandInterrupted(added)) {
failureToast(
`Could not add ${link.label} to this app`,
String(squashAtomCommandFailure(added)),
);
}
// Pairing clears a dismissal on success, so a later removal starts fresh.
const added = await addLinkedEnvironmentToApp(environmentId, {
environmentId: link.environmentId,
label: link.label,
onHostMachine: row.onHostMachine,
});
if (added._tag === "Interrupted") return;
if (added._tag === "Failed") {
failureToast(`Could not add ${link.label} to this app`, added.message);
return;
}
toastManager.add({
type: "success",
title: `Added ${link.label} to this app`,
...(issued._tag === "Success" && issued.value.access === "read-only"
...(added.access === "read-only"
? {
description:
"Read-only: the link allows no more. Link it with full access to act there.",
Expand Down Expand Up @@ -300,15 +283,21 @@ function LinkedEnvironmentRow({
{canUnlink || (canAddToApp && row.action === "add-to-app") ? (
<div className="flex w-full shrink-0 items-center gap-2 sm:w-auto sm:justify-end">
{canAddToApp && row.action === "add-to-app" ? (
<Button size="xs" variant="outline" disabled={busy} onClick={() => void add()}>
Add to this app
<Button
size="xs"
variant="outline"
disabled={busy || adding}
aria-busy={adding}
onClick={() => void add()}
>
{adding ? "Adding…" : "Add to this app"}
</Button>
) : null}
{canUnlink ? (
<Button
size="xs"
variant="destructive-outline"
disabled={busy}
disabled={busy || adding}
onClick={() => void forget()}
>
Forget
Expand Down
9 changes: 8 additions & 1 deletion apps/web/src/connection/onboarding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ import {
createAtomCommandScheduler,
createRuntimeCommand,
} from "@t3tools/client-runtime/state/runtime";
import type { DesktopSshEnvironmentTarget } from "@t3tools/contracts";
import type { DesktopSshEnvironmentTarget, EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";

import { undismissLinkedEnvironment } from "../state/linkedEnvironmentDismissals";
import { connectionAtomRuntime } from "./runtime";

// Adding a machine by any path is the way back from removing it, so it may be added on its own again.
const undismissAdded = (environmentId: EnvironmentId) =>
Effect.sync(() => void undismissLinkedEnvironment(environmentId));

const onboardingScheduler = createAtomCommandScheduler();

export const connectPairing = createRuntimeCommand(connectionAtomRuntime, {
Expand All @@ -20,6 +25,7 @@ export const connectPairing = createRuntimeCommand(connectionAtomRuntime, {
execute: (input: ConnectionOnboarding.PairingConnectionInput) =>
ConnectionOnboarding.ConnectionOnboarding.pipe(
Effect.flatMap((onboarding) => onboarding.registerPairing(input)),
Effect.tap(undismissAdded),
),
});

Expand All @@ -33,5 +39,6 @@ export const connectSshEnvironment = createRuntimeCommand(connectionAtomRuntime,
execute: (input: ConnectionOnboarding.SshConnectionInput) =>
ConnectionOnboarding.ConnectionOnboarding.pipe(
Effect.flatMap((onboarding) => onboarding.registerSsh(input)),
Effect.tap(undismissAdded),
),
});
30 changes: 5 additions & 25 deletions apps/web/src/connection/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import {
import { clearComposerDraftsEnvironment } from "../composerDraftStore";
import { isHostedStaticApp } from "../hostedPairing";
import { isLocalEnvironmentDisabled } from "../localEnvironment";
import { subscribeNetworkPathChanges } from "../lib/networkPathChanges";
import { randomUUID } from "../lib/utils";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState";
Expand Down Expand Up @@ -92,33 +93,12 @@ const layerConnectivity = Connectivity.layer({
),
});

interface NetworkInformationLike extends EventTarget {
readonly type?: string;
}

// change also fires for same-network bandwidth and latency estimates; count only type changes.
const networkPathChanges = Stream.callback<"network-changed">((queue) =>
Effect.acquireRelease(
Effect.sync(() => {
const connection =
typeof navigator === "undefined"
? undefined
: (navigator as Navigator & { readonly connection?: NetworkInformationLike }).connection;
if (connection?.type === undefined) return undefined;
let previous = connection.type;
const listener = () => {
const type = connection.type;
if (type === undefined || type === previous) return;
previous = type;
Queue.offerUnsafe(queue, "network-changed");
};
connection.addEventListener("change", listener);
return { connection, listener };
}),
(subscription) =>
Effect.sync(() =>
subscription?.connection.removeEventListener("change", subscription.listener),
),
Effect.sync(() =>
subscribeNetworkPathChanges(() => Queue.offerUnsafe(queue, "network-changed")),
),
(unsubscribe) => Effect.sync(unsubscribe),
).pipe(Effect.asVoid),
);

Expand Down
32 changes: 32 additions & 0 deletions apps/web/src/hooks/useLiveRefresh.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@ function Probe(props: {
readonly enabled?: boolean;
readonly intervalMs?: number | null;
readonly refreshOnShow?: boolean;
readonly refreshOnReconnect?: boolean;
}) {
useLiveRefresh(props.refresh, {
key: props.viewKey,
enabled: props.enabled ?? true,
...(props.intervalMs !== undefined ? { intervalMs: props.intervalMs } : {}),
...(props.refreshOnShow !== undefined ? { refreshOnShow: props.refreshOnShow } : {}),
...(props.refreshOnReconnect !== undefined
? { refreshOnReconnect: props.refreshOnReconnect }
: {}),
});
return null;
}
Expand Down Expand Up @@ -62,4 +66,32 @@ describe("useLiveRefresh", () => {
expect(periodic).toHaveBeenCalledTimes(5);
expect(untimed).not.toHaveBeenCalled();
});

it("with refreshOnReconnect, reads when the browser comes back online, outside the floor", async () => {
const reconnecting = vi.fn();
const plain = vi.fn();
using _timers = fakeTimers({ now: 1_000_000 });
await using _screen = await render(
<>
<Probe refresh={reconnecting} viewKey="reconnect" intervalMs={null} refreshOnReconnect />
<Probe refresh={plain} viewKey="no-reconnect" intervalMs={null} />
</>,
// A bare hook probe; nothing here navigates.
{ router: false },
);
// The first arrival only records the mount-time read.
await act(() => window.dispatchEvent(new Event("online")));
expect(reconnecting).not.toHaveBeenCalled();

// A burst inside the floor reads once.
await act(() => vi.advanceTimersByTime(LIVE_REFRESH_MIN_INTERVAL_MS));
await act(() => window.dispatchEvent(new Event("online")));
await act(() => window.dispatchEvent(new Event("online")));
expect(reconnecting).toHaveBeenCalledTimes(1);

await act(() => vi.advanceTimersByTime(LIVE_REFRESH_MIN_INTERVAL_MS));
await act(() => window.dispatchEvent(new Event("online")));
expect(reconnecting).toHaveBeenCalledTimes(2);
expect(plain).not.toHaveBeenCalled();
});
});
16 changes: 15 additions & 1 deletion apps/web/src/hooks/useLiveRefresh.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { useEffect, useEffectEvent, useId } from "react";

import { subscribeNetworkPathChanges } from "../lib/networkPathChanges";

export const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000;

const LIVE_REFRESH_INTERVAL_MS = 5 * 60_000;
Expand Down Expand Up @@ -83,13 +85,19 @@ export function useLiveRefresh(
* long stale when shown.
*/
readonly refreshOnShow?: boolean;
/**
* Also treat the browser coming back online, or the device changing networks, like a
* return to the window: for a read whose answer depends on what else is reachable.
*/
readonly refreshOnReconnect?: boolean;
} = {},
): void {
const {
enabled = true,
key,
intervalMs = LIVE_REFRESH_INTERVAL_MS,
refreshOnShow = false,
refreshOnReconnect = false,
} = options;
const runRefresh = useEffectEvent((viewId: string, now: number) => {
if (refresh === null) return;
Expand Down Expand Up @@ -146,11 +154,17 @@ export function useLiveRefresh(
syncTimer();
window.addEventListener("focus", onArrival);
document.addEventListener("visibilitychange", onVisibilityChange);
if (refreshOnReconnect) window.addEventListener("online", onArrival);
const stopWatchingNetwork = refreshOnReconnect
? subscribeNetworkPathChanges(onArrival)
: () => undefined;
return () => {
clearInterval(timer);
window.removeEventListener("focus", onArrival);
document.removeEventListener("visibilitychange", onVisibilityChange);
window.removeEventListener("online", onArrival);
stopWatchingNetwork();
stopWatchingInteraction();
};
}, [enabled, viewId, intervalMs, refreshOnShow]);
}, [enabled, viewId, intervalMs, refreshOnShow, refreshOnReconnect]);
}
Loading
Loading