feat(web): split provider updates per environment when WSL is present
The launch popover now renders one row per local environment (e.g. Windows
and WSL), each with its own "update all" trigger that targets only that
environment's backend, instead of a single button that fanned out to every
environment at once.
- Defer the popover until every local backend leaves "connecting" (30s
safety cap) so it reflects every environment, rather than appearing from
the primary alone while WSL is still booting; rows pick up WSL reactively
if it connects later.
- Label rows by platform ("Windows" / "WSL" / "macOS" / "Linux"), detecting
WSL by its backend instance id and otherwise the reported OS, falling back
to the environment's own label.
- Resolve each row's result from both the dispatch payload and live server
state, so it lands correctly whether a secondary backend's config fails to
re-sync or the dispatch RPC is lost to a reconnect; a 20s backstop reverts
the spinner if the request never reaches the backend.
- Gate the entire split behind WSL presence: without a WSL backend the
popover keeps the original single-prompt flow, so non-WSL users see no
change.
This commit is contained in:
1 parent
c275e239f8
commit
07324844df
7 files changed
+1128
-270
No files matched your search
@@ -0,0 +1,281 @@
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";
|
||||
import { PROVIDER_DISPLAY_NAMES, type EnvironmentId } from "@t3tools/contracts";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { updateProvidersInEnvironment } from "../environmentApi";
|
||||
import { useLocalEnvironmentUpdateGroups } from "./ProviderUpdateLaunchNotification.environments";
|
||||
import {
|
||||
collectProviderUpdateOutcomeSnapshots,
|
||||
firstRejectedProviderUpdateMessage,
|
||||
getProviderUpdateProgressToastView,
|
||||
getProviderUpdateSidebarPillView,
|
||||
type LocalEnvironmentUpdateGroup,
|
||||
type ProviderUpdateSidebarPillView,
|
||||
type ProviderUpdateToastView,
|
||||
} from "./ProviderUpdateLaunchNotification.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import { Spinner } from "./ui/spinner";
|
||||
|
||||
// If neither the dispatch result nor server state ever reports the update (e.g.
|
||||
// the request never reached the backend), stop the spinner after this long so
|
||||
// the row reverts to its Update button instead of spinning forever.
|
||||
const PENDING_EXPIRY_MS = 20_000;
|
||||
|
||||
type RowStatusKind = "idle" | "loading" | "success" | "failed" | "unchanged";
|
||||
|
||||
interface RowStatus {
|
||||
readonly kind: RowStatusKind;
|
||||
readonly text: string;
|
||||
}
|
||||
|
||||
function providerNamesFor(group: LocalEnvironmentUpdateGroup): string {
|
||||
return group.candidates
|
||||
.map((candidate) => PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver)
|
||||
.join(", ");
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a row's display from every available signal, in priority order:
|
||||
* a transport rejection, then the dispatch's own result payload (reliable even
|
||||
* when a secondary backend's config does not re-sync), then live server state
|
||||
* (reliable even when the dispatch RPC is lost to a reconnect), then the
|
||||
* optimistic pending spinner, then the idle "ready to update" state.
|
||||
*/
|
||||
function resolveRowStatus(input: {
|
||||
readonly group: LocalEnvironmentUpdateGroup;
|
||||
readonly error: string | undefined;
|
||||
readonly result: ProviderUpdateToastView | undefined;
|
||||
readonly pill: ProviderUpdateSidebarPillView | null;
|
||||
readonly isPending: boolean;
|
||||
}): RowStatus {
|
||||
if (input.error) {
|
||||
return { kind: "failed", text: input.error };
|
||||
}
|
||||
if (input.result) {
|
||||
switch (input.result.phase) {
|
||||
case "succeeded":
|
||||
return { kind: "success", text: "Updated" };
|
||||
case "failed":
|
||||
return { kind: "failed", text: input.result.description };
|
||||
case "unchanged":
|
||||
return { kind: "unchanged", text: input.result.description };
|
||||
default:
|
||||
return { kind: "loading", text: "Updating…" };
|
||||
}
|
||||
}
|
||||
if (input.pill) {
|
||||
switch (input.pill.tone) {
|
||||
case "success":
|
||||
return { kind: "success", text: "Updated" };
|
||||
case "error":
|
||||
return { kind: "failed", text: input.pill.description };
|
||||
case "warning":
|
||||
return { kind: "unchanged", text: input.pill.description };
|
||||
default:
|
||||
return { kind: "loading", text: "Updating…" };
|
||||
}
|
||||
}
|
||||
if (input.isPending) {
|
||||
return { kind: "loading", text: "Updating…" };
|
||||
}
|
||||
return { kind: "idle", text: providerNamesFor(input.group) };
|
||||
}
|
||||
|
||||
function rowToneClass(kind: RowStatusKind): string {
|
||||
switch (kind) {
|
||||
case "failed":
|
||||
return "text-destructive";
|
||||
case "unchanged":
|
||||
return "text-warning";
|
||||
case "success":
|
||||
return "text-success";
|
||||
default:
|
||||
return "text-muted-foreground";
|
||||
}
|
||||
}
|
||||
|
||||
function EnvironmentUpdateRow({
|
||||
group,
|
||||
status,
|
||||
onUpdate,
|
||||
}: {
|
||||
readonly group: LocalEnvironmentUpdateGroup;
|
||||
readonly status: RowStatus;
|
||||
readonly onUpdate: () => void;
|
||||
}) {
|
||||
let trailing: ReactNode;
|
||||
switch (status.kind) {
|
||||
case "loading":
|
||||
trailing = <Spinner className="size-4 text-muted-foreground" />;
|
||||
break;
|
||||
case "success":
|
||||
trailing = <CheckIcon aria-hidden="true" className="size-4 text-success" />;
|
||||
break;
|
||||
case "failed":
|
||||
case "unchanged":
|
||||
trailing = (
|
||||
<Button size="xs" variant="outline" onClick={onUpdate}>
|
||||
Retry
|
||||
</Button>
|
||||
);
|
||||
break;
|
||||
default:
|
||||
trailing = (
|
||||
<Button size="xs" onClick={onUpdate}>
|
||||
Update
|
||||
</Button>
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-between gap-3 py-0.5">
|
||||
<div className="flex min-w-0 flex-col">
|
||||
<span className="truncate font-medium text-foreground">{group.label}</span>
|
||||
<span className={cn("truncate text-xs", rowToneClass(status.kind))}>{status.text}</span>
|
||||
</div>
|
||||
<div className="shrink-0">{trailing}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The launch popover's body when WSL is present: one row per local environment
|
||||
* (Windows + WSL), each with its own "update all" trigger that targets only
|
||||
* that environment's backend.
|
||||
*/
|
||||
export function ProviderUpdateEnvironmentRows() {
|
||||
const { groups } = useLocalEnvironmentUpdateGroups();
|
||||
const groupByEnvironment = useMemo(
|
||||
() => new Map(groups.map((group) => [group.environmentId, group] as const)),
|
||||
[groups],
|
||||
);
|
||||
|
||||
// Only surface results that land after this popover opened.
|
||||
const visibleAfterIsoRef = useRef<string>(new Date().toISOString());
|
||||
|
||||
const [pendingEnvironments, setPendingEnvironments] = useState<ReadonlySet<EnvironmentId>>(
|
||||
() => new Set(),
|
||||
);
|
||||
const [errorByEnvironment, setErrorByEnvironment] = useState<ReadonlyMap<EnvironmentId, string>>(
|
||||
() => new Map(),
|
||||
);
|
||||
const [resultByEnvironment, setResultByEnvironment] = useState<
|
||||
ReadonlyMap<EnvironmentId, ProviderUpdateToastView>
|
||||
>(() => new Map());
|
||||
|
||||
const clearPending = useCallback((environmentId: EnvironmentId) => {
|
||||
setPendingEnvironments((previous) => {
|
||||
if (!previous.has(environmentId)) {
|
||||
return previous;
|
||||
}
|
||||
const next = new Set(previous);
|
||||
next.delete(environmentId);
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleUpdate = useCallback(
|
||||
async (environmentId: EnvironmentId) => {
|
||||
const group = groupByEnvironment.get(environmentId);
|
||||
if (!group || group.candidates.length === 0) {
|
||||
return;
|
||||
}
|
||||
const providerCount = group.candidates.length;
|
||||
const targets = group.candidates.map((candidate) => ({
|
||||
driver: candidate.driver,
|
||||
instanceId: candidate.instanceId,
|
||||
}));
|
||||
|
||||
setPendingEnvironments((previous) => new Set(previous).add(environmentId));
|
||||
setErrorByEnvironment((previous) => {
|
||||
if (!previous.has(environmentId)) {
|
||||
return previous;
|
||||
}
|
||||
const next = new Map(previous);
|
||||
next.delete(environmentId);
|
||||
return next;
|
||||
});
|
||||
setResultByEnvironment((previous) => {
|
||||
if (!previous.has(environmentId)) {
|
||||
return previous;
|
||||
}
|
||||
const next = new Map(previous);
|
||||
next.delete(environmentId);
|
||||
return next;
|
||||
});
|
||||
|
||||
const expiry = setTimeout(() => clearPending(environmentId), PENDING_EXPIRY_MS);
|
||||
try {
|
||||
const results = await Promise.allSettled(
|
||||
updateProvidersInEnvironment(environmentId, targets),
|
||||
);
|
||||
if (results.length === 0) {
|
||||
setErrorByEnvironment((previous) =>
|
||||
new Map(previous).set(
|
||||
environmentId,
|
||||
"This environment isn’t connected — try again once it reconnects.",
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const rejectedMessage = firstRejectedProviderUpdateMessage(results);
|
||||
if (rejectedMessage) {
|
||||
setErrorByEnvironment((previous) =>
|
||||
new Map(previous).set(environmentId, rejectedMessage),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: collectProviderUpdateOutcomeSnapshots(results),
|
||||
providerCount,
|
||||
});
|
||||
setResultByEnvironment((previous) => new Map(previous).set(environmentId, view));
|
||||
} catch (error) {
|
||||
setErrorByEnvironment((previous) =>
|
||||
new Map(previous).set(
|
||||
environmentId,
|
||||
error instanceof Error ? error.message : "Provider update failed.",
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
clearTimeout(expiry);
|
||||
clearPending(environmentId);
|
||||
}
|
||||
},
|
||||
[clearPending, groupByEnvironment],
|
||||
);
|
||||
|
||||
const rows = groups
|
||||
.map((group) => ({
|
||||
group,
|
||||
status: resolveRowStatus({
|
||||
group,
|
||||
error: errorByEnvironment.get(group.environmentId),
|
||||
result: resultByEnvironment.get(group.environmentId),
|
||||
pill: getProviderUpdateSidebarPillView(group.providers, {
|
||||
visibleAfterIso: visibleAfterIsoRef.current,
|
||||
}),
|
||||
isPending: pendingEnvironments.has(group.environmentId),
|
||||
}),
|
||||
}))
|
||||
.filter(({ group, status }) => group.candidates.length > 0 || status.kind !== "idle");
|
||||
|
||||
if (rows.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-0.5 flex flex-col gap-1">
|
||||
{rows.map(({ group, status }) => (
|
||||
<EnvironmentUpdateRow
|
||||
key={group.environmentId}
|
||||
group={group}
|
||||
status={status}
|
||||
onUpdate={() => handleUpdate(group.environmentId)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { getPrimaryKnownEnvironment } from "../environments/primary";
|
||||
import {
|
||||
useSavedEnvironmentRegistryStore,
|
||||
useSavedEnvironmentRuntimeStore,
|
||||
} from "../environments/runtime";
|
||||
import { useServerConfig } from "../rpc/serverState";
|
||||
import {
|
||||
buildLocalEnvironmentUpdateGroups,
|
||||
deriveEnvironmentDisplayLabel,
|
||||
parseWslDistroFromInstanceId,
|
||||
type EnvironmentUpdateConnectionState,
|
||||
type LocalEnvironmentProvidersInput,
|
||||
type LocalEnvironmentUpdateGroup,
|
||||
} from "./ProviderUpdateLaunchNotification.logic";
|
||||
|
||||
function normalizeConnectionState(state: string | undefined): EnvironmentUpdateConnectionState {
|
||||
switch (state) {
|
||||
case "connected":
|
||||
return "ready";
|
||||
case "connecting":
|
||||
return "connecting";
|
||||
case "error":
|
||||
return "error";
|
||||
case "disconnected":
|
||||
return "disconnected";
|
||||
default:
|
||||
// A desktopLocal record exists but its runtime has not been initialized
|
||||
// yet — treat it as still settling so the popover waits for it.
|
||||
return "connecting";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reactively enumerate the enabled local environments (the primary plus any
|
||||
* desktopLocal secondary such as WSL) with each one's outdated one-click
|
||||
* candidates and a flag for whether any is still connecting. Drives the launch
|
||||
* popover's gating and its per-environment update triggers.
|
||||
*/
|
||||
export function useLocalEnvironmentUpdateGroups(): {
|
||||
readonly groups: LocalEnvironmentUpdateGroup[];
|
||||
readonly isAnySettling: boolean;
|
||||
} {
|
||||
const primaryConfig = useServerConfig();
|
||||
const registryById = useSavedEnvironmentRegistryStore((store) => store.byId);
|
||||
const runtimeById = useSavedEnvironmentRuntimeStore((store) => store.byId);
|
||||
|
||||
return useMemo(() => {
|
||||
const environments: LocalEnvironmentProvidersInput[] = [];
|
||||
|
||||
const primary = getPrimaryKnownEnvironment();
|
||||
const primaryEnvironmentId = primary?.environmentId;
|
||||
if (primary && primaryEnvironmentId) {
|
||||
environments.push({
|
||||
environmentId: primaryEnvironmentId,
|
||||
// Label by platform so the row reads "Windows"/"WSL", not the account name.
|
||||
label: deriveEnvironmentDisplayLabel({
|
||||
isWsl: false,
|
||||
wslDistro: null,
|
||||
platformOs: primaryConfig?.environment?.platform?.os,
|
||||
fallbackLabel: primary.label,
|
||||
}),
|
||||
isPrimary: true,
|
||||
// The primary is the backend serving this renderer, so it is ready
|
||||
// whenever its providers are available.
|
||||
connectionState: "ready",
|
||||
providers: primaryConfig?.providers ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
for (const record of Object.values(registryById)) {
|
||||
// Local secondaries only (the WSL backend); skip SSH / relay / remote and
|
||||
// never the primary twice.
|
||||
if (!record.desktopLocal || record.environmentId === primaryEnvironmentId) {
|
||||
continue;
|
||||
}
|
||||
const runtime = runtimeById[record.environmentId];
|
||||
const instanceId = record.desktopLocal.instanceId;
|
||||
environments.push({
|
||||
environmentId: record.environmentId,
|
||||
label: deriveEnvironmentDisplayLabel({
|
||||
isWsl: instanceId.startsWith("wsl:"),
|
||||
wslDistro: parseWslDistroFromInstanceId(instanceId),
|
||||
platformOs: runtime?.descriptor?.platform?.os,
|
||||
fallbackLabel: record.label,
|
||||
}),
|
||||
isPrimary: false,
|
||||
connectionState: normalizeConnectionState(runtime?.connectionState),
|
||||
providers: runtime?.serverConfig?.providers ?? [],
|
||||
});
|
||||
}
|
||||
|
||||
return buildLocalEnvironmentUpdateGroups(environments);
|
||||
}, [primaryConfig, registryById, runtimeById]);
|
||||
}
|
||||
@@ -1,13 +1,24 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";
|
||||
import {
|
||||
type EnvironmentId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import type { LocalProviderUpdateOutcome } from "../environmentApi";
|
||||
import {
|
||||
buildLocalEnvironmentUpdateGroups,
|
||||
canOneClickUpdateProviderCandidate,
|
||||
collectProviderUpdateCandidates,
|
||||
collectProviderUpdateOutcomeSnapshots,
|
||||
deriveEnvironmentDisplayLabel,
|
||||
environmentGroupsWithUpdates,
|
||||
firstRejectedProviderUpdateMessage,
|
||||
firstUnsuccessfulSecondaryProviderOutcome,
|
||||
localEnvironmentUpdateNotificationKey,
|
||||
parseWslDistroFromInstanceId,
|
||||
type LocalEnvironmentProvidersInput,
|
||||
getProviderUpdateInitialToastView,
|
||||
getProviderUpdateProgressToastView,
|
||||
getProviderUpdateRejectedToastView,
|
||||
@@ -776,4 +787,147 @@ describe("provider update launch notification logic", () => {
|
||||
expect(firstRejectedProviderUpdateMessage(results)).toBe("WebSocket closed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("per-environment update grouping", () => {
|
||||
const environment = (
|
||||
input: {
|
||||
readonly environmentId: string;
|
||||
readonly providers: ReadonlyArray<ServerProvider>;
|
||||
} & Partial<Omit<LocalEnvironmentProvidersInput, "environmentId" | "providers">>,
|
||||
): LocalEnvironmentProvidersInput => ({
|
||||
environmentId: input.environmentId as EnvironmentId,
|
||||
label: input.label ?? input.environmentId,
|
||||
isPrimary: input.isPrimary ?? false,
|
||||
connectionState: input.connectionState ?? "ready",
|
||||
providers: input.providers,
|
||||
});
|
||||
|
||||
it("groups each environment's outdated one-click candidates", () => {
|
||||
const result = buildLocalEnvironmentUpdateGroups([
|
||||
environment({
|
||||
environmentId: "env-windows",
|
||||
label: "Windows",
|
||||
isPrimary: true,
|
||||
providers: [provider({ driver: driver("codex"), latestVersion: "1.1.0" })],
|
||||
}),
|
||||
environment({
|
||||
environmentId: "env-wsl",
|
||||
label: "WSL",
|
||||
providers: [provider({ driver: driver("codex"), latestVersion: "1.1.0" })],
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(result.isAnySettling).toBe(false);
|
||||
expect(result.groups.map((group) => group.label)).toEqual(["Windows", "WSL"]);
|
||||
expect(result.groups.every((group) => group.candidates.length === 1)).toBe(true);
|
||||
});
|
||||
|
||||
it("flags settling while a secondary backend is still connecting", () => {
|
||||
const result = buildLocalEnvironmentUpdateGroups([
|
||||
environment({
|
||||
environmentId: "env-windows",
|
||||
isPrimary: true,
|
||||
providers: [provider({ driver: driver("codex") })],
|
||||
}),
|
||||
environment({ environmentId: "env-wsl", connectionState: "connecting", providers: [] }),
|
||||
]);
|
||||
|
||||
expect(result.isAnySettling).toBe(true);
|
||||
expect(
|
||||
result.groups.find((group) => group.environmentId === ("env-wsl" as EnvironmentId))
|
||||
?.isSettling,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps only environments that have a one-click update on offer", () => {
|
||||
const { groups } = buildLocalEnvironmentUpdateGroups([
|
||||
environment({
|
||||
environmentId: "env-windows",
|
||||
isPrimary: true,
|
||||
providers: [provider({ driver: driver("codex") })],
|
||||
}),
|
||||
environment({
|
||||
environmentId: "env-wsl",
|
||||
providers: [
|
||||
provider({ driver: driver("codex"), advisoryStatus: "current", latestVersion: null }),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(environmentGroupsWithUpdates(groups).map((group) => group.environmentId)).toEqual([
|
||||
"env-windows",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keys the notification by environment, driver and latest version", () => {
|
||||
const noUpdates = buildLocalEnvironmentUpdateGroups([
|
||||
environment({
|
||||
environmentId: "env-windows",
|
||||
isPrimary: true,
|
||||
providers: [
|
||||
provider({ driver: driver("codex"), advisoryStatus: "current", latestVersion: null }),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
expect(localEnvironmentUpdateNotificationKey(noUpdates.groups)).toBeNull();
|
||||
|
||||
const both = buildLocalEnvironmentUpdateGroups([
|
||||
environment({
|
||||
environmentId: "env-windows",
|
||||
isPrimary: true,
|
||||
providers: [provider({ driver: driver("codex"), latestVersion: "1.1.0" })],
|
||||
}),
|
||||
environment({
|
||||
environmentId: "env-wsl",
|
||||
providers: [provider({ driver: driver("codex"), latestVersion: "1.1.0" })],
|
||||
}),
|
||||
]);
|
||||
const key = localEnvironmentUpdateNotificationKey(both.groups);
|
||||
expect(key).toContain("env-windows=codex:1.1.0");
|
||||
expect(key).toContain("env-wsl=codex:1.1.0");
|
||||
});
|
||||
|
||||
it("labels environments by platform so they are distinguishable", () => {
|
||||
expect(
|
||||
deriveEnvironmentDisplayLabel({
|
||||
isWsl: false,
|
||||
wslDistro: null,
|
||||
platformOs: "windows",
|
||||
fallbackLabel: "Jgratton24",
|
||||
}),
|
||||
).toBe("Windows");
|
||||
expect(
|
||||
deriveEnvironmentDisplayLabel({
|
||||
isWsl: true,
|
||||
wslDistro: null,
|
||||
platformOs: "linux",
|
||||
fallbackLabel: "Jgratton24",
|
||||
}),
|
||||
).toBe("WSL");
|
||||
expect(
|
||||
deriveEnvironmentDisplayLabel({
|
||||
isWsl: true,
|
||||
wslDistro: "ubuntu",
|
||||
platformOs: "linux",
|
||||
fallbackLabel: "Jgratton24",
|
||||
}),
|
||||
).toBe("WSL · ubuntu");
|
||||
expect(
|
||||
deriveEnvironmentDisplayLabel({
|
||||
isWsl: false,
|
||||
wslDistro: null,
|
||||
platformOs: undefined,
|
||||
fallbackLabel: "My Device",
|
||||
}),
|
||||
).toBe("My Device");
|
||||
});
|
||||
|
||||
it("parses the WSL distro from the backend instance id", () => {
|
||||
expect(parseWslDistroFromInstanceId("wsl:ubuntu")).toBe("ubuntu");
|
||||
expect(parseWslDistroFromInstanceId("wsl:default")).toBeNull();
|
||||
expect(parseWslDistroFromInstanceId("wsl:")).toBeNull();
|
||||
expect(parseWslDistroFromInstanceId("ssh:host")).toBeNull();
|
||||
expect(parseWslDistroFromInstanceId(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
import {
|
||||
defaultInstanceIdForDriver,
|
||||
PROVIDER_DISPLAY_NAMES,
|
||||
type EnvironmentId,
|
||||
type ExecutionEnvironmentPlatformOs,
|
||||
type ProviderDriverKind,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -568,3 +570,124 @@ function getFailedProviderUpdateDescription(providers: ReadonlyArray<ServerProvi
|
||||
}
|
||||
return `${formatProviderList(providers)} failed to update. Check provider settings for details.`;
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// Per-environment update grouping
|
||||
//
|
||||
// The launch popover splits its single "update all" trigger into one trigger
|
||||
// per local environment (Windows + WSL). Each environment owns its provider
|
||||
// instances, so candidates and progress are computed from that environment's
|
||||
// own provider list; the dispatch targets that environment's connection.
|
||||
// ===========================================================================
|
||||
|
||||
const WSL_INSTANCE_ID_PREFIX = "wsl:";
|
||||
|
||||
/** The distro name from a WSL backend instance id ("wsl:ubuntu" -> "ubuntu"), or null for the default. */
|
||||
export function parseWslDistroFromInstanceId(instanceId: string | undefined): string | null {
|
||||
if (!instanceId || !instanceId.startsWith(WSL_INSTANCE_ID_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
const distro = instanceId.slice(WSL_INSTANCE_ID_PREFIX.length).trim();
|
||||
return distro.length === 0 || distro === "default" ? null : distro;
|
||||
}
|
||||
|
||||
/**
|
||||
* A human label that distinguishes local environments by platform (so the
|
||||
* popover shows "Windows" / "WSL" rather than the account name twice). WSL is
|
||||
* identified by its backend instance id; everything else falls back to the
|
||||
* reported OS, then the environment's own label.
|
||||
*/
|
||||
export function deriveEnvironmentDisplayLabel(input: {
|
||||
readonly isWsl: boolean;
|
||||
readonly wslDistro: string | null;
|
||||
readonly platformOs: ExecutionEnvironmentPlatformOs | undefined;
|
||||
readonly fallbackLabel: string;
|
||||
}): string {
|
||||
if (input.isWsl) {
|
||||
return input.wslDistro ? `WSL · ${input.wslDistro}` : "WSL";
|
||||
}
|
||||
switch (input.platformOs) {
|
||||
case "windows":
|
||||
return "Windows";
|
||||
case "darwin":
|
||||
return "macOS";
|
||||
case "linux":
|
||||
return "Linux";
|
||||
default:
|
||||
return input.fallbackLabel;
|
||||
}
|
||||
}
|
||||
|
||||
/** Connection state of a local environment, normalized across primary/secondary sources. */
|
||||
export type EnvironmentUpdateConnectionState = "connecting" | "ready" | "disconnected" | "error";
|
||||
|
||||
export interface LocalEnvironmentProvidersInput {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
readonly isPrimary: boolean;
|
||||
readonly connectionState: EnvironmentUpdateConnectionState;
|
||||
readonly providers: ReadonlyArray<ServerProvider>;
|
||||
}
|
||||
|
||||
export interface LocalEnvironmentUpdateGroup {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly label: string;
|
||||
readonly isPrimary: boolean;
|
||||
/** True while this environment's backend is still connecting (e.g. WSL booting). */
|
||||
readonly isSettling: boolean;
|
||||
/** Outdated, one-click-updatable providers in this environment. */
|
||||
readonly candidates: ProviderUpdateCandidate[];
|
||||
/** Full provider list for this environment, used to derive live update progress. */
|
||||
readonly providers: ReadonlyArray<ServerProvider>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build one update group per local environment, pairing each environment's
|
||||
* outdated one-click candidates with its own provider list, and report whether
|
||||
* any environment is still settling (so the caller can defer the popover).
|
||||
*/
|
||||
export function buildLocalEnvironmentUpdateGroups(
|
||||
environments: ReadonlyArray<LocalEnvironmentProvidersInput>,
|
||||
): { groups: LocalEnvironmentUpdateGroup[]; isAnySettling: boolean } {
|
||||
const groups = environments.map((environment) => ({
|
||||
environmentId: environment.environmentId,
|
||||
label: environment.label,
|
||||
isPrimary: environment.isPrimary,
|
||||
isSettling: environment.connectionState === "connecting",
|
||||
candidates: collectProviderUpdateCandidates(environment.providers).filter((candidate) =>
|
||||
canOneClickUpdateProviderCandidate(candidate, environment.providers),
|
||||
),
|
||||
providers: environment.providers,
|
||||
}));
|
||||
const isAnySettling = environments.some(
|
||||
(environment) => environment.connectionState === "connecting",
|
||||
);
|
||||
return { groups, isAnySettling };
|
||||
}
|
||||
|
||||
/** Groups that actually have a one-click update available, in display order (primary first). */
|
||||
export function environmentGroupsWithUpdates(
|
||||
groups: ReadonlyArray<LocalEnvironmentUpdateGroup>,
|
||||
): LocalEnvironmentUpdateGroup[] {
|
||||
return groups.filter((group) => group.candidates.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable key over the set of (environment, driver, latest version) updates on
|
||||
* offer, so the popover is shown once per distinct set and re-shown when it
|
||||
* changes.
|
||||
*/
|
||||
export function localEnvironmentUpdateNotificationKey(
|
||||
groups: ReadonlyArray<LocalEnvironmentUpdateGroup>,
|
||||
): string | null {
|
||||
const parts = environmentGroupsWithUpdates(groups)
|
||||
.map((group) => {
|
||||
const providerParts = group.candidates
|
||||
.map((candidate) => `${candidate.driver}:${candidate.versionAdvisory.latestVersion}`)
|
||||
.toSorted()
|
||||
.join(",");
|
||||
return `${group.environmentId}=${providerParts}`;
|
||||
})
|
||||
.toSorted();
|
||||
return parts.length > 0 ? parts.join("|") : null;
|
||||
}
|
||||
@@ -1,309 +1,153 @@
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { DownloadIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { updateProviderAcrossLocalEnvironments } from "../environmentApi";
|
||||
import { useSavedEnvironmentRegistryStore } from "../environments/runtime";
|
||||
import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal";
|
||||
import { useServerProviders } from "../rpc/serverState";
|
||||
import { PROVIDER_ICON_BY_PROVIDER } from "./chat/providerIconUtils";
|
||||
import { ProviderUpdateEnvironmentRows } from "./ProviderUpdateEnvironmentRows";
|
||||
import { useLocalEnvironmentUpdateGroups } from "./ProviderUpdateLaunchNotification.environments";
|
||||
import {
|
||||
canOneClickUpdateProviderCandidate,
|
||||
collectProviderUpdateCandidates,
|
||||
collectProviderUpdateOutcomeSnapshots,
|
||||
firstRejectedProviderUpdateMessage,
|
||||
environmentGroupsWithUpdates,
|
||||
getProviderUpdateInitialToastView,
|
||||
getProviderUpdateProgressToastView,
|
||||
getProviderUpdateRejectedToastView,
|
||||
getProviderUpdateRunningToastView,
|
||||
providerUpdateNotificationKey,
|
||||
type ProviderUpdateToastView,
|
||||
localEnvironmentUpdateNotificationKey,
|
||||
} from "./ProviderUpdateLaunchNotification.logic";
|
||||
import { ProviderUpdatePrimaryNotification } from "./ProviderUpdatePrimaryNotification";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
|
||||
/**
|
||||
* The provider update popover. With a WSL backend present it splits the update
|
||||
* trigger per environment; without one (the common case) it falls back to the
|
||||
* single-prompt flow so non-WSL users see no change.
|
||||
*/
|
||||
export function ProviderUpdateLaunchNotification() {
|
||||
const hasWslEnvironment = useSavedEnvironmentRegistryStore((store) =>
|
||||
Object.values(store.byId).some(
|
||||
(record) => record.desktopLocal?.instanceId?.startsWith("wsl:") === true,
|
||||
),
|
||||
);
|
||||
|
||||
return hasWslEnvironment ? (
|
||||
<ProviderUpdateEnvironmentsNotification />
|
||||
) : (
|
||||
<ProviderUpdatePrimaryNotification />
|
||||
);
|
||||
}
|
||||
|
||||
const seenProviderUpdateNotificationKeys = new Set<string>();
|
||||
type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
type ActiveProviderUpdateToast =
|
||||
| { readonly kind: "prompt"; readonly key: string; readonly toastId: ProviderUpdateToastId }
|
||||
| {
|
||||
readonly kind: "update";
|
||||
readonly key: string;
|
||||
readonly toastId: ProviderUpdateToastId;
|
||||
readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;
|
||||
readonly providerCount: number;
|
||||
// True until every dispatched backend update settles. While true the
|
||||
// primary-only serverState effect must not finalize the toast, since it
|
||||
// cannot observe a secondary (e.g. WSL) backend's outcome.
|
||||
readonly awaitingSettlement: boolean;
|
||||
};
|
||||
// While a local backend (e.g. WSL) is still connecting, defer the popover so it
|
||||
// reflects every environment. Cap the wait so a stuck or failed backend can't
|
||||
// suppress the primary's updates indefinitely.
|
||||
const SETTLING_GRACE_MS = 30_000;
|
||||
|
||||
function ProviderUpdateToastIcon({ provider }: { provider: ProviderDriverKind }) {
|
||||
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[provider];
|
||||
|
||||
if (!ProviderIcon) {
|
||||
return (
|
||||
<span className="relative inline-flex size-4 shrink-0 items-center justify-center">
|
||||
<DownloadIcon aria-hidden="true" className="size-4 text-success" strokeWidth={2.5} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="relative inline-flex size-4 shrink-0 items-center justify-center">
|
||||
<ProviderIcon aria-hidden="true" className="size-4" />
|
||||
<span className="absolute -right-1 -bottom-1 inline-flex size-3 items-center justify-center rounded-full bg-popover">
|
||||
<DownloadIcon aria-hidden="true" className="size-2.5 text-success" strokeWidth={2.5} />
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function updateProviderUpdateToast(input: {
|
||||
readonly toastId: ProviderUpdateToastId;
|
||||
readonly view: ProviderUpdateToastView;
|
||||
readonly openSettings: () => void;
|
||||
}) {
|
||||
if (input.view.type === "loading" || input.view.type === "success") {
|
||||
toastManager.update(input.toastId, {
|
||||
type: input.view.type,
|
||||
title: input.view.title,
|
||||
description: input.view.description,
|
||||
timeout: 0,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
...(input.view.dismissAfterVisibleMs !== undefined
|
||||
? { dismissAfterVisibleMs: input.view.dismissAfterVisibleMs }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.update(
|
||||
input.toastId,
|
||||
stackedThreadToast({
|
||||
type: input.view.type,
|
||||
title: input.view.title,
|
||||
description: input.view.description,
|
||||
timeout: 0,
|
||||
actionProps: {
|
||||
children: "Settings",
|
||||
onClick: input.openSettings,
|
||||
},
|
||||
actionVariant: "outline",
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function isTerminalProviderUpdateToastView(view: ProviderUpdateToastView) {
|
||||
return view.phase === "failed" || view.phase === "unchanged" || view.phase === "succeeded";
|
||||
}
|
||||
|
||||
export function ProviderUpdateLaunchNotification() {
|
||||
function ProviderUpdateEnvironmentsNotification() {
|
||||
const navigate = useNavigate();
|
||||
const providers = useServerProviders();
|
||||
const activeToastRef = useRef<ActiveProviderUpdateToast | null>(null);
|
||||
const { groups, isAnySettling } = useLocalEnvironmentUpdateGroups();
|
||||
const { dismissedNotificationKeys, dismissNotificationKey } =
|
||||
useDismissedProviderUpdateNotificationKeys();
|
||||
|
||||
const updateProviders = useMemo(() => collectProviderUpdateCandidates(providers), [providers]);
|
||||
const notificationKey = useMemo(
|
||||
() => providerUpdateNotificationKey(updateProviders),
|
||||
[updateProviders],
|
||||
);
|
||||
const oneClickProviders = useMemo(
|
||||
() =>
|
||||
updateProviders.filter((provider) => canOneClickUpdateProviderCandidate(provider, providers)),
|
||||
[providers, updateProviders],
|
||||
);
|
||||
const activeToastRef = useRef<ProviderUpdateToastId | null>(null);
|
||||
const notificationKeyRef = useRef<string | null>(null);
|
||||
|
||||
const openProviderSettings = useCallback(
|
||||
(toastId?: ProviderUpdateToastId) => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (toastId !== undefined) {
|
||||
toastManager.close(toastId);
|
||||
} else if (activeToast) {
|
||||
toastManager.close(activeToast.toastId);
|
||||
}
|
||||
if (activeToast && (toastId === undefined || activeToast.toastId === toastId)) {
|
||||
// Close our prompt if this flow unmounts (e.g. the WSL backend is disabled
|
||||
// and we fall back to the single-prompt flow).
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (activeToastRef.current !== null) {
|
||||
toastManager.close(activeToastRef.current);
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
void navigate({ to: "/settings/providers" });
|
||||
},
|
||||
[navigate],
|
||||
};
|
||||
}, []);
|
||||
|
||||
const updateGroups = useMemo(() => environmentGroupsWithUpdates(groups), [groups]);
|
||||
const notificationKey = useMemo(() => localEnvironmentUpdateNotificationKey(groups), [groups]);
|
||||
useEffect(() => {
|
||||
notificationKeyRef.current = notificationKey;
|
||||
}, [notificationKey]);
|
||||
|
||||
// Title summarizes the distinct providers on offer across all environments;
|
||||
// the per-environment detail lives in the popover body.
|
||||
const candidateUnion = useMemo(
|
||||
() => collectProviderUpdateCandidates(updateGroups.flatMap((group) => group.candidates)),
|
||||
[updateGroups],
|
||||
);
|
||||
|
||||
// Defer while any local backend is still connecting, up to the grace period.
|
||||
const [settleGraceElapsed, setSettleGraceElapsed] = useState(false);
|
||||
useEffect(() => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (activeToast?.kind !== "update") {
|
||||
if (!isAnySettling) {
|
||||
setSettleGraceElapsed(false);
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => setSettleGraceElapsed(true), SETTLING_GRACE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [isAnySettling]);
|
||||
const isGated = isAnySettling && !settleGraceElapsed;
|
||||
|
||||
// The dispatched updates have not all settled yet. This effect only sees the
|
||||
// primary backend's serverState, so it cannot tell whether a secondary (e.g.
|
||||
// WSL) backend succeeded — leave the running toast in place and let the
|
||||
// settled-promise handler report the aggregate outcome.
|
||||
if (activeToast.awaitingSettlement) {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeProviders = providers.filter((provider) =>
|
||||
activeToast.providerInstanceIds.has(provider.instanceId),
|
||||
);
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: activeProviders,
|
||||
providerCount: activeToast.providerCount,
|
||||
});
|
||||
updateProviderUpdateToast({
|
||||
toastId: activeToast.toastId,
|
||||
view,
|
||||
openSettings: () => openProviderSettings(activeToast.toastId),
|
||||
});
|
||||
|
||||
if (isTerminalProviderUpdateToastView(view)) {
|
||||
const openProviderSettings = useCallback(() => {
|
||||
const toastId = activeToastRef.current;
|
||||
if (toastId !== null) {
|
||||
toastManager.close(toastId);
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
}, [providers, openProviderSettings]);
|
||||
void navigate({ to: "/settings/providers" });
|
||||
}, [navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
|
||||
toastManager.close(activeToast.toastId);
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
|
||||
if (
|
||||
!notificationKey ||
|
||||
isGated ||
|
||||
dismissedNotificationKeys.has(notificationKey) ||
|
||||
seenProviderUpdateNotificationKeys.has(notificationKey) ||
|
||||
activeToastRef.current
|
||||
activeToastRef.current !== null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
seenProviderUpdateNotificationKeys.add(notificationKey);
|
||||
|
||||
const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
|
||||
|
||||
let toastId!: ProviderUpdateToastId;
|
||||
let updateStarted = false;
|
||||
const openSettings = () => openProviderSettings(toastId);
|
||||
const dismissPrompt = () => {
|
||||
dismissNotificationKey(notificationKey);
|
||||
};
|
||||
|
||||
const runUpdates = () => {
|
||||
if (updateStarted || oneClickProviders.length === 0) {
|
||||
return;
|
||||
// Dismiss whatever set is still on offer at close time, so the popover
|
||||
// does not re-pop for updates the user just declined.
|
||||
const liveKey = notificationKeyRef.current;
|
||||
if (liveKey) {
|
||||
dismissNotificationKey(liveKey);
|
||||
}
|
||||
updateStarted = true;
|
||||
|
||||
const providerCount = oneClickProviders.length;
|
||||
const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
|
||||
activeToastRef.current = {
|
||||
kind: "update",
|
||||
key: notificationKey,
|
||||
toastId,
|
||||
providerInstanceIds,
|
||||
providerCount,
|
||||
awaitingSettlement: true,
|
||||
};
|
||||
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view: getProviderUpdateRunningToastView(providerCount),
|
||||
openSettings,
|
||||
});
|
||||
|
||||
void Promise.allSettled(
|
||||
oneClickProviders.flatMap((provider) =>
|
||||
updateProviderAcrossLocalEnvironments(provider.driver, provider.instanceId),
|
||||
),
|
||||
).then((results) => {
|
||||
const activeUpdateToast = activeToastRef.current;
|
||||
if (activeUpdateToast?.kind !== "update" || activeUpdateToast.toastId !== toastId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Every backend has settled — release the live serverState effect.
|
||||
activeToastRef.current = { ...activeUpdateToast, awaitingSettlement: false };
|
||||
|
||||
const rejectedMessage = firstRejectedProviderUpdateMessage(results);
|
||||
if (rejectedMessage) {
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view: getProviderUpdateRejectedToastView(providerCount, rejectedMessage),
|
||||
openSettings,
|
||||
});
|
||||
activeToastRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedProviderSnapshots = collectProviderUpdateOutcomeSnapshots(results);
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: updatedProviderSnapshots,
|
||||
providerCount,
|
||||
});
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view,
|
||||
openSettings,
|
||||
});
|
||||
|
||||
if (isTerminalProviderUpdateToastView(view)) {
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
});
|
||||
activeToastRef.current = null;
|
||||
};
|
||||
|
||||
toastId = toastManager.add(
|
||||
const toastId = toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: initialView.type,
|
||||
title: initialView.title,
|
||||
description: initialView.description,
|
||||
type: "warning",
|
||||
title: getProviderUpdateInitialToastView({
|
||||
updateProviders: candidateUnion,
|
||||
oneClickProviders: candidateUnion,
|
||||
}).title,
|
||||
description: <ProviderUpdateEnvironmentRows />,
|
||||
timeout: 0,
|
||||
actionProps:
|
||||
oneClickProviders.length > 0
|
||||
? {
|
||||
children: "Update",
|
||||
onClick: runUpdates,
|
||||
}
|
||||
: {
|
||||
children: "Settings",
|
||||
onClick: openSettings,
|
||||
},
|
||||
actionVariant: oneClickProviders.length > 0 ? "default" : "outline",
|
||||
actionProps: {
|
||||
children: "Settings",
|
||||
onClick: openProviderSettings,
|
||||
},
|
||||
actionVariant: "outline",
|
||||
data: {
|
||||
leadingIcon:
|
||||
updateProviders.length === 1 ? (
|
||||
<ProviderUpdateToastIcon provider={updateProviders[0]!.driver} />
|
||||
) : undefined,
|
||||
hideCopyButton: true,
|
||||
leadingIcon: <DownloadIcon aria-hidden="true" className="size-4 text-success" />,
|
||||
onClose: dismissPrompt,
|
||||
...(oneClickProviders.length > 0
|
||||
? {
|
||||
secondaryActionProps: {
|
||||
children: "Settings",
|
||||
onClick: openSettings,
|
||||
},
|
||||
secondaryActionVariant: "outline" as const,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };
|
||||
activeToastRef.current = toastId;
|
||||
}, [
|
||||
dismissNotificationKey,
|
||||
dismissedNotificationKeys,
|
||||
notificationKey,
|
||||
oneClickProviders,
|
||||
isGated,
|
||||
candidateUnion,
|
||||
dismissedNotificationKeys,
|
||||
dismissNotificationKey,
|
||||
openProviderSettings,
|
||||
updateProviders,
|
||||
]);
|
||||
|
||||
return null;
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
import { DownloadIcon } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { type ProviderDriverKind, type ProviderInstanceId } from "@t3tools/contracts";
|
||||
|
||||
import { updateProviderAcrossLocalEnvironments } from "../environmentApi";
|
||||
import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal";
|
||||
import { useServerProviders } from "../rpc/serverState";
|
||||
import { PROVIDER_ICON_BY_PROVIDER } from "./chat/providerIconUtils";
|
||||
import {
|
||||
canOneClickUpdateProviderCandidate,
|
||||
collectProviderUpdateCandidates,
|
||||
collectProviderUpdateOutcomeSnapshots,
|
||||
firstRejectedProviderUpdateMessage,
|
||||
getProviderUpdateInitialToastView,
|
||||
getProviderUpdateProgressToastView,
|
||||
getProviderUpdateRejectedToastView,
|
||||
getProviderUpdateRunningToastView,
|
||||
providerUpdateNotificationKey,
|
||||
type ProviderUpdateToastView,
|
||||
} from "./ProviderUpdateLaunchNotification.logic";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
|
||||
const seenProviderUpdateNotificationKeys = new Set<string>();
|
||||
type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
type ActiveProviderUpdateToast =
|
||||
| { readonly kind: "prompt"; readonly key: string; readonly toastId: ProviderUpdateToastId }
|
||||
| {
|
||||
readonly kind: "update";
|
||||
readonly key: string;
|
||||
readonly toastId: ProviderUpdateToastId;
|
||||
readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;
|
||||
readonly providerCount: number;
|
||||
// True until every dispatched backend update settles. While true the
|
||||
// primary-only serverState effect must not finalize the toast, since it
|
||||
// cannot observe a secondary (e.g. WSL) backend's outcome.
|
||||
readonly awaitingSettlement: boolean;
|
||||
};
|
||||
|
||||
function ProviderUpdateToastIcon({ provider }: { provider: ProviderDriverKind }) {
|
||||
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[provider];
|
||||
|
||||
if (!ProviderIcon) {
|
||||
return (
|
||||
<span className="relative inline-flex size-4 shrink-0 items-center justify-center">
|
||||
<DownloadIcon aria-hidden="true" className="size-4 text-success" strokeWidth={2.5} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="relative inline-flex size-4 shrink-0 items-center justify-center">
|
||||
<ProviderIcon aria-hidden="true" className="size-4" />
|
||||
<span className="absolute -right-1 -bottom-1 inline-flex size-3 items-center justify-center rounded-full bg-popover">
|
||||
<DownloadIcon aria-hidden="true" className="size-2.5 text-success" strokeWidth={2.5} />
|
||||
</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function updateProviderUpdateToast(input: {
|
||||
readonly toastId: ProviderUpdateToastId;
|
||||
readonly view: ProviderUpdateToastView;
|
||||
readonly openSettings: () => void;
|
||||
}) {
|
||||
if (input.view.type === "loading" || input.view.type === "success") {
|
||||
toastManager.update(input.toastId, {
|
||||
type: input.view.type,
|
||||
title: input.view.title,
|
||||
description: input.view.description,
|
||||
timeout: 0,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
...(input.view.dismissAfterVisibleMs !== undefined
|
||||
? { dismissAfterVisibleMs: input.view.dismissAfterVisibleMs }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
toastManager.update(
|
||||
input.toastId,
|
||||
stackedThreadToast({
|
||||
type: input.view.type,
|
||||
title: input.view.title,
|
||||
description: input.view.description,
|
||||
timeout: 0,
|
||||
actionProps: {
|
||||
children: "Settings",
|
||||
onClick: input.openSettings,
|
||||
},
|
||||
actionVariant: "outline",
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function isTerminalProviderUpdateToastView(view: ProviderUpdateToastView) {
|
||||
return view.phase === "failed" || view.phase === "unchanged" || view.phase === "succeeded";
|
||||
}
|
||||
|
||||
/**
|
||||
* The single-prompt provider update notification used when there is only one
|
||||
* local environment (no WSL backend). Non-WSL users see exactly this flow — the
|
||||
* per-environment split is gated behind WSL presence.
|
||||
*/
|
||||
export function ProviderUpdatePrimaryNotification() {
|
||||
const navigate = useNavigate();
|
||||
const providers = useServerProviders();
|
||||
const activeToastRef = useRef<ActiveProviderUpdateToast | null>(null);
|
||||
const { dismissedNotificationKeys, dismissNotificationKey } =
|
||||
useDismissedProviderUpdateNotificationKeys();
|
||||
|
||||
// If this flow unmounts (e.g. a WSL backend appears and we switch to the
|
||||
// per-environment popover), close any prompt it owns so it does not linger.
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (activeToast) {
|
||||
toastManager.close(activeToast.toastId);
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const updateProviders = useMemo(() => collectProviderUpdateCandidates(providers), [providers]);
|
||||
const notificationKey = useMemo(
|
||||
() => providerUpdateNotificationKey(updateProviders),
|
||||
[updateProviders],
|
||||
);
|
||||
const oneClickProviders = useMemo(
|
||||
() =>
|
||||
updateProviders.filter((provider) => canOneClickUpdateProviderCandidate(provider, providers)),
|
||||
[providers, updateProviders],
|
||||
);
|
||||
|
||||
const openProviderSettings = useCallback(
|
||||
(toastId?: ProviderUpdateToastId) => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (toastId !== undefined) {
|
||||
toastManager.close(toastId);
|
||||
} else if (activeToast) {
|
||||
toastManager.close(activeToast.toastId);
|
||||
}
|
||||
if (activeToast && (toastId === undefined || activeToast.toastId === toastId)) {
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
void navigate({ to: "/settings/providers" });
|
||||
},
|
||||
[navigate],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (activeToast?.kind !== "update") {
|
||||
return;
|
||||
}
|
||||
|
||||
// The dispatched updates have not all settled yet. This effect only sees the
|
||||
// primary backend's serverState, so it cannot tell whether a secondary (e.g.
|
||||
// WSL) backend succeeded — leave the running toast in place and let the
|
||||
// settled-promise handler report the aggregate outcome.
|
||||
if (activeToast.awaitingSettlement) {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeProviders = providers.filter((provider) =>
|
||||
activeToast.providerInstanceIds.has(provider.instanceId),
|
||||
);
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: activeProviders,
|
||||
providerCount: activeToast.providerCount,
|
||||
});
|
||||
updateProviderUpdateToast({
|
||||
toastId: activeToast.toastId,
|
||||
view,
|
||||
openSettings: () => openProviderSettings(activeToast.toastId),
|
||||
});
|
||||
|
||||
if (isTerminalProviderUpdateToastView(view)) {
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
}, [providers, openProviderSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
const activeToast = activeToastRef.current;
|
||||
if (activeToast?.kind === "prompt" && activeToast.key !== notificationKey) {
|
||||
toastManager.close(activeToast.toastId);
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
|
||||
if (
|
||||
!notificationKey ||
|
||||
dismissedNotificationKeys.has(notificationKey) ||
|
||||
seenProviderUpdateNotificationKeys.has(notificationKey) ||
|
||||
activeToastRef.current
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
seenProviderUpdateNotificationKeys.add(notificationKey);
|
||||
|
||||
const initialView = getProviderUpdateInitialToastView({ updateProviders, oneClickProviders });
|
||||
|
||||
let toastId!: ProviderUpdateToastId;
|
||||
let updateStarted = false;
|
||||
const openSettings = () => openProviderSettings(toastId);
|
||||
const dismissPrompt = () => {
|
||||
dismissNotificationKey(notificationKey);
|
||||
};
|
||||
|
||||
const runUpdates = () => {
|
||||
if (updateStarted || oneClickProviders.length === 0) {
|
||||
return;
|
||||
}
|
||||
updateStarted = true;
|
||||
|
||||
const providerCount = oneClickProviders.length;
|
||||
const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));
|
||||
activeToastRef.current = {
|
||||
kind: "update",
|
||||
key: notificationKey,
|
||||
toastId,
|
||||
providerInstanceIds,
|
||||
providerCount,
|
||||
awaitingSettlement: true,
|
||||
};
|
||||
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view: getProviderUpdateRunningToastView(providerCount),
|
||||
openSettings,
|
||||
});
|
||||
|
||||
void Promise.allSettled(
|
||||
oneClickProviders.flatMap((provider) =>
|
||||
updateProviderAcrossLocalEnvironments(provider.driver, provider.instanceId),
|
||||
),
|
||||
).then((results) => {
|
||||
const activeUpdateToast = activeToastRef.current;
|
||||
if (activeUpdateToast?.kind !== "update" || activeUpdateToast.toastId !== toastId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Every backend has settled — release the live serverState effect.
|
||||
activeToastRef.current = { ...activeUpdateToast, awaitingSettlement: false };
|
||||
|
||||
const rejectedMessage = firstRejectedProviderUpdateMessage(results);
|
||||
if (rejectedMessage) {
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view: getProviderUpdateRejectedToastView(providerCount, rejectedMessage),
|
||||
openSettings,
|
||||
});
|
||||
activeToastRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const updatedProviderSnapshots = collectProviderUpdateOutcomeSnapshots(results);
|
||||
const view = getProviderUpdateProgressToastView({
|
||||
providers: updatedProviderSnapshots,
|
||||
providerCount,
|
||||
});
|
||||
updateProviderUpdateToast({
|
||||
toastId,
|
||||
view,
|
||||
openSettings,
|
||||
});
|
||||
|
||||
if (isTerminalProviderUpdateToastView(view)) {
|
||||
activeToastRef.current = null;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
toastId = toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: initialView.type,
|
||||
title: initialView.title,
|
||||
description: initialView.description,
|
||||
timeout: 0,
|
||||
actionProps:
|
||||
oneClickProviders.length > 0
|
||||
? {
|
||||
children: "Update",
|
||||
onClick: runUpdates,
|
||||
}
|
||||
: {
|
||||
children: "Settings",
|
||||
onClick: openSettings,
|
||||
},
|
||||
actionVariant: oneClickProviders.length > 0 ? "default" : "outline",
|
||||
data: {
|
||||
leadingIcon:
|
||||
updateProviders.length === 1 ? (
|
||||
<ProviderUpdateToastIcon provider={updateProviders[0]!.driver} />
|
||||
) : undefined,
|
||||
hideCopyButton: true,
|
||||
onClose: dismissPrompt,
|
||||
...(oneClickProviders.length > 0
|
||||
? {
|
||||
secondaryActionProps: {
|
||||
children: "Settings",
|
||||
onClick: openSettings,
|
||||
},
|
||||
secondaryActionVariant: "outline" as const,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
}),
|
||||
);
|
||||
activeToastRef.current = { kind: "prompt", key: notificationKey, toastId };
|
||||
}, [
|
||||
dismissNotificationKey,
|
||||
dismissedNotificationKeys,
|
||||
notificationKey,
|
||||
oneClickProviders,
|
||||
openProviderSettings,
|
||||
updateProviders,
|
||||
]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -114,6 +114,36 @@ export interface LocalProviderUpdateOutcome {
|
||||
readonly provider: ServerProvider | null;
|
||||
}
|
||||
|
||||
function dispatchProviderUpdate(
|
||||
connection: EnvironmentConnection,
|
||||
isPrimary: boolean,
|
||||
driver: ProviderDriverKind,
|
||||
instanceId: ProviderInstanceId,
|
||||
): Promise<LocalProviderUpdateOutcome> {
|
||||
return connection.client.server
|
||||
.updateProvider({ provider: driver, instanceId })
|
||||
.then((payload) => ({
|
||||
environmentId: connection.environmentId,
|
||||
isPrimary,
|
||||
driver,
|
||||
instanceId,
|
||||
provider:
|
||||
payload.providers.find(
|
||||
(candidate) => candidate.driver === driver && candidate.instanceId === instanceId,
|
||||
) ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
/** The live connection for a local environment, whether it is the primary or a saved secondary. */
|
||||
function readLocalEnvironmentConnection(
|
||||
environmentId: EnvironmentId,
|
||||
): EnvironmentConnection | null {
|
||||
const primary = getPrimaryEnvironmentConnection();
|
||||
return primary.environmentId === environmentId
|
||||
? primary
|
||||
: readEnvironmentConnection(environmentId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch a provider update to every connected local backend that has the
|
||||
* provider configured — the primary plus any local secondary (e.g. WSL) — and
|
||||
@@ -128,25 +158,8 @@ export function updateProviderAcrossLocalEnvironments(
|
||||
primaryInstanceId: ProviderInstanceId,
|
||||
): ReadonlyArray<Promise<LocalProviderUpdateOutcome>> {
|
||||
const primary = getPrimaryEnvironmentConnection();
|
||||
|
||||
const dispatch = (
|
||||
connection: EnvironmentConnection,
|
||||
instanceId: ProviderInstanceId,
|
||||
isPrimary: boolean,
|
||||
): Promise<LocalProviderUpdateOutcome> =>
|
||||
connection.client.server.updateProvider({ provider: driver, instanceId }).then((payload) => ({
|
||||
environmentId: connection.environmentId,
|
||||
isPrimary,
|
||||
driver,
|
||||
instanceId,
|
||||
provider:
|
||||
payload.providers.find(
|
||||
(candidate) => candidate.driver === driver && candidate.instanceId === instanceId,
|
||||
) ?? null,
|
||||
}));
|
||||
|
||||
const dispatches: Array<Promise<LocalProviderUpdateOutcome>> = [
|
||||
dispatch(primary, primaryInstanceId, true),
|
||||
dispatchProviderUpdate(primary, true, driver, primaryInstanceId),
|
||||
];
|
||||
|
||||
for (const record of listSavedEnvironmentRecords()) {
|
||||
@@ -164,12 +177,32 @@ export function updateProviderAcrossLocalEnvironments(
|
||||
if (!match) {
|
||||
continue; // provider not configured in this environment
|
||||
}
|
||||
dispatches.push(dispatch(connection, match.instanceId, false));
|
||||
dispatches.push(dispatchProviderUpdate(connection, false, driver, match.instanceId));
|
||||
}
|
||||
|
||||
return dispatches;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispatch updates to a single local environment — the per-environment trigger
|
||||
* behind the launch popover's split "update all" buttons. Each target carries
|
||||
* the instance id resolved from that environment's own server config. Returns
|
||||
* one in-flight outcome per target (empty if the environment is not connected).
|
||||
*/
|
||||
export function updateProvidersInEnvironment(
|
||||
environmentId: EnvironmentId,
|
||||
targets: ReadonlyArray<{ readonly driver: ProviderDriverKind; readonly instanceId: ProviderInstanceId }>,
|
||||
): ReadonlyArray<Promise<LocalProviderUpdateOutcome>> {
|
||||
const connection = readLocalEnvironmentConnection(environmentId);
|
||||
if (!connection) {
|
||||
return [];
|
||||
}
|
||||
const isPrimary = connection.environmentId === getPrimaryEnvironmentConnection().environmentId;
|
||||
return targets.map((target) =>
|
||||
dispatchProviderUpdate(connection, isPrimary, target.driver, target.instanceId),
|
||||
);
|
||||
}
|
||||
|
||||
export function __setEnvironmentApiOverrideForTests(
|
||||
environmentId: EnvironmentId,
|
||||
api: EnvironmentApi,
|
||||
|
||||
Reference in new issue
Block a user