Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
fix(web): stop prompting for provider updates
Leoaf2afbfda6d1
diff --git a/apps/web/src/components/ProviderUpdateEnvironmentRows.test.tsx b/apps/web/src/components/ProviderUpdateEnvironmentRows.test.tsxdeleted file mode 100644index b34f82a77..000000000--- a/apps/web/src/components/ProviderUpdateEnvironmentRows.test.tsx+++ /dev/null@@ -1,226 +0,0 @@-import type { Dispatch, ReactElement, SetStateAction } from "react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";-import {- type EnvironmentId,- ProviderDriverKind,- ProviderInstanceId,- type ServerProvider,-} from "@t3tools/contracts";-import { AsyncResult } from "effect/unstable/reactivity";--import type {- LocalEnvironmentUpdateGroup,- ProviderUpdateCandidate,- ProviderUpdateRowStatus,-} from "./ProviderUpdateLaunchNotification.logic";--const testState = vi.hoisted(() => ({- groups: [] as LocalEnvironmentUpdateGroup[],- updateProvider: vi.fn(),-}));--const hooks = vi.hoisted(() => {- let cursor = 0;- let slots: unknown[] = [];-- const nextIndex = () => cursor++;-- return {- beginRender() {- cursor = 0;- },- reset() {- cursor = 0;- slots = [];- },- useCallback<T>(callback: T): T {- nextIndex();- return callback;- },- useMemo<T>(factory: () => T): T {- nextIndex();- return factory();- },- useMemoCache(size: number): unknown[] {- const index = nextIndex();- if (!slots[index]) {- slots[index] = Array.from({ length: size }, () => Symbol.for("react.memo_cache_sentinel"));- }- return slots[index] as unknown[];- },- useRef<T>(initialValue: T): { current: T } {- const index = nextIndex();- if (!slots[index]) {- slots[index] = { current: initialValue };- }- return slots[index] as { current: T };- },- useState<T>(initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {- const index = nextIndex();- if (index >= slots.length) {- slots[index] =- typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;- }- const setValue: Dispatch<SetStateAction<T>> = (nextValue) => {- const previous = slots[index] as T;- slots[index] =- typeof nextValue === "function" ? (nextValue as (value: T) => T)(previous) : nextValue;- };- return [slots[index] as T, setValue];- },- };-});--vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- return {- ...actual,- useCallback: hooks.useCallback,- useMemo: hooks.useMemo,- useRef: hooks.useRef,- useState: hooks.useState,- };-});--vi.mock("react/compiler-runtime", () => ({- c: hooks.useMemoCache,-}));--vi.mock("~/state/server", () => ({- serverEnvironment: { updateProvider: Symbol("updateProvider") },-}));--vi.mock("~/state/use-atom-command", () => ({- useAtomCommand: () => testState.updateProvider,-}));--vi.mock("./ProviderUpdateLaunchNotification.environments", () => ({- useLocalEnvironmentUpdateGroups: () => ({- groups: testState.groups,- isAnySettling: false,- }),-}));--import { ProviderUpdateEnvironmentRows } from "./ProviderUpdateEnvironmentRows";--const environmentId = "env-wsl" as EnvironmentId;-const pendingExpiryMs = 6 * 60_000;--function provider(updateStatus?: "succeeded"): ServerProvider {- const result: ServerProvider = {- instanceId: ProviderInstanceId.make("codex-wsl"),- driver: ProviderDriverKind.make("codex"),- enabled: true,- installed: true,- version: updateStatus ? "1.1.0" : "1.0.0",- status: "ready",- auth: { status: "authenticated" },- checkedAt: "2026-06-26T12:00:00.000Z",- models: [],- slashCommands: [],- skills: [],- versionAdvisory: {- status: updateStatus ? "current" : "behind_latest",- currentVersion: updateStatus ? "1.1.0" : "1.0.0",- latestVersion: "1.1.0",- updateCommand: "npm install -g @openai/codex@latest",- canUpdate: true,- checkedAt: "2026-06-26T12:00:00.000Z",- message: updateStatus ? "Up to date." : "Update available.",- },- };-- return updateStatus- ? {- ...result,- updateState: {- status: updateStatus,- startedAt: "2026-06-26T12:00:00.000Z",- finishedAt: "2026-06-26T12:00:01.000Z",- message: "Provider updated.",- output: null,- },- }- : result;-}--function deferred<T>() {- let resolve!: (value: T) => void;- const promise = new Promise<T>((complete) => {- resolve = complete;- });- return { promise, resolve };-}--type RowElement = ReactElement<{- readonly status: ProviderUpdateRowStatus;- readonly onUpdate: () => void;-}>;--function renderRow(): RowElement {- hooks.beginRender();- const output = ProviderUpdateEnvironmentRows({}) as ReactElement<{- readonly children: RowElement | RowElement[];- }>;- const children = output.props.children;- return Array.isArray(children) ? children[0]! : children;-}--async function flushPromises(): Promise<void> {- await Promise.resolve();- await Promise.resolve();- await Promise.resolve();-}--describe("ProviderUpdateEnvironmentRows", () => {- beforeEach(() => {- vi.useFakeTimers();- hooks.reset();- testState.updateProvider.mockReset();- const candidate = provider() as ProviderUpdateCandidate;- testState.groups = [- {- environmentId,- label: "WSL",- isPrimary: false,- isSettling: false,- candidates: [candidate],- providers: [candidate],- },- ];- });-- afterEach(() => {- vi.useRealTimers();- });-- it("keeps a successor pending when an expired request resolves late, then shows its success", async () => {- const firstRequest =- deferred<ReturnType<typeof AsyncResult.success<{ providers: ServerProvider[] }>>>();- const successorRequest =- deferred<ReturnType<typeof AsyncResult.success<{ providers: ServerProvider[] }>>>();- testState.updateProvider- .mockReturnValueOnce(firstRequest.promise)- .mockReturnValueOnce(successorRequest.promise);-- renderRow().props.onUpdate();- expect(renderRow().props.status.kind).toBe("loading");-- await vi.advanceTimersByTimeAsync(pendingExpiryMs);- expect(renderRow().props.status.kind).toBe("failed");-- renderRow().props.onUpdate();- expect(testState.updateProvider).toHaveBeenCalledTimes(2);- expect(renderRow().props.status.kind).toBe("loading");-- firstRequest.resolve(AsyncResult.success({ providers: [provider("succeeded")] }));- await flushPromises();-- expect(renderRow().props.status.kind).toBe("loading");-- successorRequest.resolve(AsyncResult.success({ providers: [provider("succeeded")] }));- await flushPromises();-- expect(renderRow().props.status.kind).toBe("success");- });-});diff --git a/apps/web/src/components/ProviderUpdateEnvironmentRows.tsx b/apps/web/src/components/ProviderUpdateEnvironmentRows.tsxdeleted file mode 100644index 56aaa9e96..000000000--- a/apps/web/src/components/ProviderUpdateEnvironmentRows.tsx+++ /dev/null@@ -1,397 +0,0 @@-import { CheckIcon } from "lucide-react";-import { type ReactNode, useCallback, useMemo, useRef, useState } from "react";-import type { EnvironmentId, ServerProvider } from "@t3tools/contracts";-import {- isAtomCommandInterrupted,- squashAtomCommandFailure,- type AtomCommandResult,-} from "@t3tools/client-runtime/state/runtime";--import { cn } from "~/lib/utils";-import { serverEnvironment } from "~/state/server";-import { useAtomCommand } from "~/state/use-atom-command";-import { useLocalEnvironmentUpdateGroups } from "./ProviderUpdateLaunchNotification.environments";-import {- collectProviderUpdateOutcomeSnapshots,- firstRejectedProviderUpdateMessage,- getProviderUpdateProgressToastView,- getProviderUpdateSidebarPillView,- isTerminalProviderUpdatePhase,- resolveEnvironmentUpdateRowStatus,- type LocalEnvironmentUpdateGroup,- type LocalProviderUpdateOutcome,- type ProviderUpdateRowStatus,- type ProviderUpdateRowStatusKind,- type ProviderUpdateToastView,-} from "./ProviderUpdateLaunchNotification.logic";-import { Button } from "./ui/button";-import { Spinner } from "./ui/spinner";--type ProviderUpdateCommandResult = AtomCommandResult<- { readonly providers: ReadonlyArray<ServerProvider> },- unknown->;--/**- * Map one targeted instance's update command result into the settled-outcome- * shape the multi-backend reducers consume: a non-interrupted failure becomes a- * rejection carrying its message; a success carries the post-update snapshot of- * the targeted instance (null when the backend did not report it).- */-function toProviderUpdateOutcome(input: {- readonly environmentId: EnvironmentId;- readonly isPrimary: boolean;- readonly target: {- readonly driver: ServerProvider["driver"];- readonly instanceId: ServerProvider["instanceId"];- };- readonly result: ProviderUpdateCommandResult;-}): PromiseSettledResult<LocalProviderUpdateOutcome> {- if (input.result._tag === "Failure") {- if (isAtomCommandInterrupted(input.result)) {- // An interrupted dispatch (e.g. superseded) is neither a success nor a- // hard failure — surface it as a non-contributing, non-rejecting outcome.- return {- status: "fulfilled",- value: {- environmentId: input.environmentId,- isPrimary: input.isPrimary,- driver: input.target.driver,- instanceId: input.target.instanceId,- provider: null,- },- };- }- const error = squashAtomCommandFailure(input.result);- return {- status: "rejected",- reason: error instanceof Error ? error : new Error("Provider update failed."),- };- }-- const provider =- input.result.value.providers.find(- (candidate) => candidate.instanceId === input.target.instanceId,- ) ?? null;- return {- status: "fulfilled",- value: {- environmentId: input.environmentId,- isPrimary: input.isPrimary,- driver: input.target.driver,- instanceId: input.target.instanceId,- provider,- },- };-}--// Transport-hang safety net. The dispatch's `finally` clears the spinner and the-// in-flight guard on completion, so this only matters if a request never resolves-// at all (e.g. the socket drops mid-flight without surfacing an error). Keep it-// well beyond the server's own update timeout (5 min) so a legitimately slow-// update (npm installs routinely run tens of seconds) is never cut off and left-// showing a dead, unresponsive Update button.-const PENDING_EXPIRY_MS = 6 * 60_000;--function rowToneClass(kind: ProviderUpdateRowStatusKind): 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: ProviderUpdateRowStatus;- 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" variant="outline" 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({- onInteract,-}: {- /** Called the first time the user triggers an update, so the host can stop refreshing the prompt. */- readonly onInteract?: () => void;-}) {- const { groups } = useLocalEnvironmentUpdateGroups();- const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {- reportFailure: false,- });- 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());-- // Synchronous re-entry guard. setPendingEnvironments is an async state update,- // and PENDING_EXPIRY_MS can clear the spinner while a request is still in- // flight, so a rapid double-click (or a click after the expiry fires mid-- // request) would otherwise dispatch a second full round of updates. A ref- // updates synchronously, so we can bail before doing any work.- const inFlightEnvironmentsRef = useRef<Set<EnvironmentId>>(new Set());-- // Monotonic per-environment request version. Bumped on each dispatch and- // captured locally, so an attempt that was superseded -- e.g. one that already- // tripped the expiry safety net and was retried -- detects it is no longer- // current and skips every state write when it finally resolves, instead of- // clobbering the newer attempt's spinner/result/error or its in-flight guard.- const requestVersionRef = useRef<Map<EnvironmentId, number>>(new Map());-- 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;- }- if (inFlightEnvironmentsRef.current.has(environmentId)) {- return;- }- inFlightEnvironmentsRef.current.add(environmentId);- const requestVersion = (requestVersionRef.current.get(environmentId) ?? 0) + 1;- requestVersionRef.current.set(environmentId, requestVersion);- const isCurrentRequest = () =>- requestVersionRef.current.get(environmentId) === requestVersion;- onInteract?.();- 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(() => {- // A newer attempt may have superseded this one; if so, leave its state- // untouched.- if (!isCurrentRequest()) {- return;- }- // The request is presumed dead (see PENDING_EXPIRY_MS). Clear the- // spinner AND the in-flight guard together so the row never strands on a- // dead Update button, and surface feedback so the timeout is visible- // rather than silently reverting to idle.- inFlightEnvironmentsRef.current.delete(environmentId);- clearPending(environmentId);- setErrorByEnvironment((previous) =>- new Map(previous).set(environmentId, "Update timed out — try again."),- );- }, PENDING_EXPIRY_MS);- try {- // Dispatch each candidate's update to this environment's own backend and- // normalize every settled outcome into the multi-backend reducer shape.- const results = await Promise.all(- targets.map(async (target): Promise<PromiseSettledResult<LocalProviderUpdateOutcome>> => {- try {- const result = await updateProvider({- environmentId,- input: { provider: target.driver, instanceId: target.instanceId },- });- return toProviderUpdateOutcome({- environmentId,- isPrimary: group.isPrimary,- target,- result,- });- } catch (error) {- return {- status: "rejected",- reason: error instanceof Error ? error : new Error("Provider update failed."),- };- }- }),- );- if (!isCurrentRequest()) {- // A newer attempt superseded this one while it was in flight; leave- // the newer attempt's state intact.- return;- }- // The request resolved (not a transport hang), so clear any stale- // timeout error the expiry may have set -- otherwise a late success- // would be masked, since an error takes priority in the row status.- setErrorByEnvironment((previous) => {- if (!previous.has(environmentId)) {- return previous;- }- const next = new Map(previous);- next.delete(environmentId);- return next;- });- 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,- });- // Only persist a terminal outcome. A non-terminal ("running"/"initial")- // view means this dispatch could not confirm completion — e.g. a snapshot- // came back without its targeted instance (collectProviderUpdateOutcome-- // Snapshots drops null providers), which happens when the command is- // interrupted as a second backend connects and supersedes the in-flight- // update. A stored view never re-polls, so persisting it would pin the- // row's spinner forever once the pending flag expires. Drop it and let- // the live per-environment provider state (pill) plus the pending expiry- // drive the row, so it self-heals to whatever the backend actually did.- if (isTerminalProviderUpdatePhase(view.phase)) {- setResultByEnvironment((previous) => new Map(previous).set(environmentId, view));- }- } catch (error) {- if (isCurrentRequest()) {- setErrorByEnvironment((previous) =>- new Map(previous).set(- environmentId,- error instanceof Error ? error.message : "Provider update failed.",- ),- );- }- } finally {- clearTimeout(expiry);- // Only the current attempt owns the shared spinner and in-flight guard;- // a superseded attempt resolving late must not clear a newer one's.- if (isCurrentRequest()) {- clearPending(environmentId);- inFlightEnvironmentsRef.current.delete(environmentId);- }- }- },- [clearPending, groupByEnvironment, onInteract, updateProvider],- );-- const rows = groups- .map((group) => ({- group,- status: resolveEnvironmentUpdateRowStatus({- group,- error: errorByEnvironment.get(group.environmentId),- result: resultByEnvironment.get(group.environmentId),- // Derive the live pill from the candidates this row is actually- // tracking, not every provider in the environment. Otherwise an- // unrelated provider's recent success (or one candidate succeeding while- // another was interrupted) makes the pill report success and hides the- // Update action for candidates that are still outdated.- pill: getProviderUpdateSidebarPillView(group.candidates, {- 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>- );-}diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.environments.ts b/apps/web/src/components/ProviderUpdateLaunchNotification.environments.tsdeleted file mode 100644index 5999f9241..000000000--- a/apps/web/src/components/ProviderUpdateLaunchNotification.environments.ts+++ /dev/null@@ -1,97 +0,0 @@-import type { ConnectionCatalogEntry } from "@t3tools/client-runtime/connection";-import type { ServerConfig } from "@t3tools/contracts";-import { useMemo } from "react";--import { useEnvironments, usePrimaryEnvironmentId } from "~/state/environments";-import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";-import {- buildLocalEnvironmentUpdateGroups,- deriveEnvironmentDisplayLabel,- type EnvironmentUpdateConnectionState,- type LocalEnvironmentProvidersInput,- type LocalEnvironmentUpdateGroup,-} from "./ProviderUpdateLaunchNotification.logic";--/**- * A local environment is either the same-origin primary backend or a- * desktop-local secondary (the parallel WSL backend), which connects over- * loopback with a bearer token and carries a `local:<backendInstanceId>`- * connection id. SSH and other remote targets are excluded.- */-function isLocalConnectionTarget(target: ConnectionCatalogEntry["target"]): boolean {- return target._tag === "PrimaryConnectionTarget" || isDesktopLocalConnectionTarget(target);-}--function normalizeConnectionState(phase: string | undefined): EnvironmentUpdateConnectionState {- switch (phase) {- case "connected":- return "ready";- case "connecting":- case "reconnecting":- return "connecting";- case "error":- return "error";- case "offline":- return "disconnected";- default:- // "available" (or anything not yet observed) — the backend has not- // confirmed it is serving yet, so treat it as still settling so the- // popover waits for it.- return "connecting";- }-}--/**- * Reactively enumerate the enabled local environments (the primary plus any- * desktop-local secondary such as WSL) with each one's full provider list 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 { environments } = useEnvironments();- const primaryEnvironmentId = usePrimaryEnvironmentId();-- return useMemo(() => {- const inputs: LocalEnvironmentProvidersInput[] = [];-- for (const environment of environments) {- if (!isLocalConnectionTarget(environment.entry.target)) {- continue;- }-- const isPrimary = environment.environmentId === primaryEnvironmentId;- const serverConfig: ServerConfig | null = environment.serverConfig;-- inputs.push({- environmentId: environment.environmentId,- // Secondaries carry a meaningful label straight from the platform source- // (e.g. "WSL (Ubuntu)"). The primary's catalog label can be the account- // name, so fall back to its platform OS so the row reads "Windows"/"Linux".- label: isPrimary- ? deriveEnvironmentDisplayLabel({- isWsl: false,- wslDistro: null,- platformOs: serverConfig?.environment.platform.os,- fallbackLabel: environment.label,- })- : environment.label,- isPrimary,- // The primary is the backend serving this renderer, so it is ready- // whenever its providers are available; secondaries report their live- // connection phase.- connectionState: isPrimary- ? "ready"- : normalizeConnectionState(environment.connection.phase),- providers: serverConfig?.providers ?? [],- });- }-- // Primary first, then the rest in catalog order.- inputs.sort((left, right) => Number(right.isPrimary) - Number(left.isPrimary));-- return buildLocalEnvironmentUpdateGroups(inputs);- }, [environments, primaryEnvironmentId]);-}diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.logic.test.ts b/apps/web/src/components/ProviderUpdateLaunchNotification.logic.test.tsdeleted file mode 100644index 2ee06a6b6..000000000--- a/apps/web/src/components/ProviderUpdateLaunchNotification.logic.test.ts+++ /dev/null@@ -1,1131 +0,0 @@-import { describe, expect, it } from "vite-plus/test";-import {- type EnvironmentId,- ProviderDriverKind,- ProviderInstanceId,- type ServerProvider,-} from "@t3tools/contracts";-import * as Cause from "effect/Cause";-import { AsyncResult } from "effect/unstable/reactivity";--import {- buildLocalEnvironmentUpdateGroups,- canOneClickUpdateProviderCandidate,- collectProviderUpdateCandidates,- collectProviderUpdateOutcomeSnapshots,- collectUpdatedProviderSnapshots,- deriveEnvironmentDisplayLabel,- environmentGroupsWithUpdates,- firstFailedProviderUpdateMessage,- firstRejectedProviderUpdateMessage,- firstUnsuccessfulSecondaryProviderOutcome,- getProviderUpdateInitialToastView,- getProviderUpdateProgressToastView,- getProviderUpdateRejectedToastView,- getProviderUpdateSidebarPillView,- getSingleProviderUpdateProgressToastView,- hasOneClickUpdateProviderCandidate,- isProviderUpdateCandidate,- isTerminalProviderUpdatePhase,- localEnvironmentUpdateNotificationKey,- parseWslDistroFromInstanceId,- providerUpdateNotificationKey,- resolveEnvironmentUpdateRowStatus,- shouldShowPrimaryProviderUpdateToast,- type LocalEnvironmentProvidersInput,- type LocalEnvironmentUpdateGroup,- type LocalProviderUpdateOutcome,- type ProviderUpdateCandidate,- type ProviderUpdateSidebarPillView,- type ProviderUpdateToastView,-} from "./ProviderUpdateLaunchNotification.logic";--const checkedAt = "2026-04-23T10:00:00.000Z";-const sessionStartedAt = "2026-04-23T09:59:00.000Z";-const laterCheckedAt = "2026-04-23T10:01:00.000Z";--const driver = (value: string) => ProviderDriverKind.make(value);-const instanceId = (value: string) => ProviderInstanceId.make(value);--function provider(input: {- readonly driver: ReturnType<typeof ProviderDriverKind.make>;- readonly instanceId?: ReturnType<typeof ProviderInstanceId.make>;- readonly enabled?: boolean;- readonly version?: string | null;- readonly latestVersion?: string | null;- readonly canUpdate?: boolean;- readonly updateCommand?: string | null;- readonly updateState?: ServerProvider["updateState"];- readonly advisoryStatus?: NonNullable<ServerProvider["versionAdvisory"]>["status"];-}): ServerProvider {- const result: ServerProvider = {- instanceId: input.instanceId ?? instanceId(String(input.driver)),- driver: input.driver,- enabled: input.enabled ?? true,- installed: true,- version: input.version ?? "1.0.0",- status: "ready",- auth: { status: "authenticated" },- checkedAt,- models: [],- slashCommands: [],- skills: [],- versionAdvisory: {- status: input.advisoryStatus ?? "behind_latest",- currentVersion: input.version ?? "1.0.0",- latestVersion: "latestVersion" in input ? input.latestVersion : "1.1.0",- updateCommand: "updateCommand" in input ? input.updateCommand : "npm install -g provider",- canUpdate: input.canUpdate ?? true,- checkedAt,- message: "Update available.",- },- };-- if (input.updateState) {- return { ...result, updateState: input.updateState };- }-- return result;-}--function updateCandidate(input: Parameters<typeof provider>[0]): ProviderUpdateCandidate {- return provider(input) as ProviderUpdateCandidate;-}--describe("provider update launch notification logic", () => {- it("detects enabled providers with a latest-version advisory", () => {- expect(isProviderUpdateCandidate(provider({ driver: driver("codex") }))).toBe(true);- expect(isProviderUpdateCandidate(provider({ driver: driver("codex"), enabled: false }))).toBe(- false,- );- expect(- isProviderUpdateCandidate(- provider({ driver: driver("codex"), advisoryStatus: "current", latestVersion: null }),- ),- ).toBe(false);- expect(- isProviderUpdateCandidate(provider({ driver: driver("codex"), latestVersion: null })),- ).toBe(false);- });-- it("deduplicates multi-instance provider candidates by driver", () => {- expect(- collectProviderUpdateCandidates([- provider({- driver: driver("codex"),- instanceId: instanceId("codex_personal"),- latestVersion: "1.1.0",- }),- provider({- driver: driver("codex"),- instanceId: instanceId("codex"),- latestVersion: "1.1.0",- }),- provider({ driver: driver("cursor"), latestVersion: "0.3.0" }),- ]),- ).toHaveLength(2);- });-- it("disables one-click updates when provider instances disagree on the update command", () => {- const candidate = updateCandidate({- driver: driver("claudeAgent"),- instanceId: instanceId("claude_personal"),- latestVersion: "2.1.123",- });-- expect(- canOneClickUpdateProviderCandidate(candidate, [- candidate,- provider({- driver: driver("claudeAgent"),- instanceId: instanceId("claude_work"),- latestVersion: "2.1.123",- canUpdate: true,- updateCommand: "bun add -g @anthropic-ai/claude-code@latest",- }),- ]),- ).toBe(false);- });-- it("keeps one-click updates enabled when sibling instances are already current", () => {- const candidate = updateCandidate({- driver: driver("claudeAgent"),- instanceId: instanceId("claude_personal"),- latestVersion: "2.1.123",- updateCommand: "npm install -g @anthropic-ai/claude-code@latest",- });-- expect(- hasOneClickUpdateProviderCandidate(candidate, [- candidate,- provider({- driver: driver("claudeAgent"),- instanceId: instanceId("claude_work"),- version: "2.1.123",- latestVersion: "2.1.123",- advisoryStatus: "current",- canUpdate: false,- updateCommand: null,- }),- ]),- ).toBe(true);- expect(- canOneClickUpdateProviderCandidate(candidate, [- candidate,- provider({- driver: driver("claudeAgent"),- instanceId: instanceId("claude_work"),- version: "2.1.123",- latestVersion: "2.1.123",- advisoryStatus: "current",- canUpdate: false,- updateCommand: null,- }),- ]),- ).toBe(true);- });-- it("keeps the inline update action available while a provider update is already running", () => {- const candidate = updateCandidate({- driver: driver("codex"),- updateState: {- status: "running",- startedAt: checkedAt,- finishedAt: null,- message: "Updating provider.",- output: null,- },- });-- expect(hasOneClickUpdateProviderCandidate(candidate, [candidate])).toBe(true);- expect(canOneClickUpdateProviderCandidate(candidate, [candidate])).toBe(false);- });-- it("builds a notification key from provider latest versions", () => {- const codex = updateCandidate({- driver: driver("codex"),- version: "1.0.0",- latestVersion: "1.1.0",- });- const cursor = updateCandidate({- driver: driver("cursor"),- version: "0.2.0",- latestVersion: "0.3.0",- });-- expect(providerUpdateNotificationKey([codex, cursor])).toBe("codex:1.1.0|cursor:0.3.0");- expect(providerUpdateNotificationKey([])).toBeNull();- });-- it("keeps the same notification key while the published update version is unchanged", () => {- const first = updateCandidate({- driver: driver("codex"),- version: "1.0.0",- latestVersion: "1.2.0",- });- const second = updateCandidate({- driver: driver("codex"),- version: "1.1.0",- latestVersion: "1.2.0",- });- const nextPublishedVersion = updateCandidate({- driver: driver("codex"),- version: "1.1.0",- latestVersion: "1.3.0",- });-- expect(providerUpdateNotificationKey([first])).toBe(providerUpdateNotificationKey([second]));- expect(providerUpdateNotificationKey([nextPublishedVersion])).not.toBe(- providerUpdateNotificationKey([first]),- );- });-- it("tracks updated provider snapshots by instance instead of collapsing to a sibling driver", () => {- const targetInstanceId = instanceId("codex_personal");- const siblingInstanceId = instanceId("codex");- const updatedPersonal = provider({- driver: driver("codex"),- instanceId: targetInstanceId,- version: "1.1.0",- latestVersion: "1.1.0",- advisoryStatus: "current",- updateState: {- status: "succeeded",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "Provider updated.",- output: null,- },- });- const currentDefaultSibling = provider({- driver: driver("codex"),- instanceId: siblingInstanceId,- version: "1.1.0",- latestVersion: "1.1.0",- advisoryStatus: "current",- updateState: undefined,- });-- expect(- collectUpdatedProviderSnapshots({- results: [- AsyncResult.success({- providers: [updatedPersonal, currentDefaultSibling],- }),- ],- providerInstanceIds: new Set([targetInstanceId]),- }),- ).toEqual([updatedPersonal]);- });-- it("describes a single one-click update", () => {- const view = getProviderUpdateInitialToastView({- updateProviders: [updateCandidate({ driver: driver("codex"), latestVersion: "1.1.0" })],- oneClickProviders: [updateCandidate({ driver: driver("codex"), latestVersion: "1.1.0" })],- });-- expect(view).toMatchObject({- phase: "initial",- type: "warning",- title: "Update Available: Codex v1.1.0",- description: "Install the update now or review provider settings.",- });- });-- it("describes settings-only updates without one-click support", () => {- const view = getProviderUpdateInitialToastView({- updateProviders: [- updateCandidate({ driver: driver("codex"), canUpdate: false }),- updateCandidate({ driver: driver("cursor"), canUpdate: false }),- ],- oneClickProviders: [],- });-- expect(view.description).toBe("Codex and Cursor can be updated from provider settings.");- });-- it("uses server update state for running progress", () => {- const view = getProviderUpdateProgressToastView({- providers: [- provider({- driver: driver("codex"),- updateState: {- status: "running",- startedAt: checkedAt,- finishedAt: null,- message: "Updating provider.",- output: null,- },- }),- ],- providerCount: 1,- });-- expect(view).toMatchObject({- phase: "running",- type: "loading",- title: "Updating provider",- });- expect(shouldShowPrimaryProviderUpdateToast(view)).toBe(false);- });-- it("keeps the initial prompt and terminal outcomes visible as toasts", () => {- expect(- shouldShowPrimaryProviderUpdateToast(- getProviderUpdateInitialToastView({- updateProviders: [updateCandidate({ driver: driver("codex") })],- oneClickProviders: [updateCandidate({ driver: driver("codex") })],- }),- ),- ).toBe(true);- expect(- shouldShowPrimaryProviderUpdateToast(getProviderUpdateRejectedToastView(1, "boom")),- ).toBe(true);- });-- it("uses server failure state for failed progress", () => {- const view = getProviderUpdateProgressToastView({- providers: [- provider({- driver: driver("codex"),- updateState: {- status: "failed",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "command failed",- output: "stderr",- },- }),- ],- providerCount: 1,- });-- expect(view).toMatchObject({- phase: "failed",- type: "error",- title: "Provider update failed",- description: "command failed",- });- });-- it("resolves a single-provider completion view from the returned provider snapshot", () => {- const view = getSingleProviderUpdateProgressToastView(- provider({- driver: driver("codex"),- updateState: {- status: "failed",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "command failed",- output: "stderr",- },- }),- );-- expect(view).toMatchObject({- phase: "failed",- type: "error",- title: "Codex v1.1.0 update failed",- description: "command failed",- });- });-- it("keeps unchanged providers actionable from settings", () => {- const view = getProviderUpdateProgressToastView({- providers: [- provider({- driver: driver("cursor"),- updateState: {- status: "unchanged",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "still old",- output: null,- },- }),- ],- providerCount: 1,- });-- expect(view).toMatchObject({- phase: "unchanged",- type: "warning",- title: "Provider still needs an update",- description: "Cursor still appears outdated. Check provider settings for details.",- });- });-- it("marks progress succeeded once every attempted provider is no longer outdated", () => {- const view = getProviderUpdateProgressToastView({- providers: [- provider({- driver: driver("codex"),- version: "1.1.0",- latestVersion: "1.1.0",- advisoryStatus: "current",- updateState: {- status: "succeeded",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "Provider updated.",- output: null,- },- }),- ],- providerCount: 1,- });-- expect(view).toMatchObject({- phase: "succeeded",- type: "success",- title: "Provider updated",- description: "New sessions will use the updated provider.",- dismissAfterVisibleMs: 3_000,- });- });-- it("uses the updated version in the single-provider success toast title", () => {- const view = getSingleProviderUpdateProgressToastView(- provider({- driver: driver("codex"),- version: "1.1.0",- latestVersion: "1.1.0",- advisoryStatus: "current",- updateState: {- status: "succeeded",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "Provider updated.",- output: null,- },- }),- );-- expect(view).toMatchObject({- phase: "succeeded",- type: "success",- title: "Codex updated: v1.1.0",- description: "New sessions will use the updated provider.",- });- });-- it("falls back to a rejected RPC message for transport-level failures", () => {- const results = [AsyncResult.failure(Cause.die(new Error("WebSocket closed")))];-- expect(firstFailedProviderUpdateMessage(results)).toBe("WebSocket closed");- expect(getProviderUpdateRejectedToastView(2, "WebSocket closed")).toMatchObject({- phase: "failed",- title: "Provider updates failed",- description: "WebSocket closed",- });- });-- it("collects only attempted provider snapshots from update responses", () => {- const codex = provider({ driver: driver("codex") });- const cursor = provider({ driver: driver("cursor") });- const results = [AsyncResult.success({ providers: [codex, cursor] })];-- expect(- collectUpdatedProviderSnapshots({- results,- providerInstanceIds: new Set([cursor.instanceId]),- }),- ).toEqual([cursor]);- });-- it("summarizes active provider updates for the sidebar pill", () => {- const view = getProviderUpdateSidebarPillView([- provider({- driver: driver("codex"),- updateState: {- status: "running",- startedAt: checkedAt,- finishedAt: null,- message: "Updating provider.",- output: null,- },- }),- provider({- driver: driver("cursor"),- updateState: {- status: "queued",- startedAt: null,- finishedAt: null,- message: "Waiting for another provider update to finish.",- output: null,- },- }),- ]);-- expect(view).toMatchObject({- tone: "loading",- title: "Updating 2 providers",- description: "Codex and Cursor updates are in progress.",- });- });-- it("uses the provider name for single active sidebar pill updates", () => {- const view = getProviderUpdateSidebarPillView([- provider({- driver: driver("codex"),- updateState: {- status: "running",- startedAt: checkedAt,- finishedAt: null,- message: "Updating provider.",- output: null,- },- }),- ]);-- expect(view).toMatchObject({- key: "loading:codex:running",- tone: "loading",- title: "Updating Codex",- description: "Codex update in progress.",- });- });-- it("uses the provider name for single failed sidebar pill updates", () => {- const view = getProviderUpdateSidebarPillView(- [- provider({- driver: driver("claudeAgent"),- updateState: {- status: "failed",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "Update command exited with code 1.",- output: null,- },- }),- ],- { visibleAfterIso: sessionStartedAt },- );-- expect(view).toMatchObject({- key: "failed:claudeAgent:2026-04-23T10:00:00.000Z:Update command exited with code 1.",- tone: "error",- title: "Claude v1.1.0 update failed",- description: "Update command exited with code 1.",- dismissible: true,- });- });-- it("shows a short-lived success sidebar pill after a single provider update succeeds", () => {- const view = getProviderUpdateSidebarPillView(- [- provider({- driver: driver("codex"),- version: "1.1.0",- latestVersion: "1.1.0",- advisoryStatus: "current",- updateState: {- status: "succeeded",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "Provider updated.",- output: null,- },- }),- ],- { visibleAfterIso: sessionStartedAt },- );-- expect(view).toMatchObject({- key: "succeeded:codex:2026-04-23T10:00:00.000Z:Provider updated.",- tone: "success",- title: "Codex updated: v1.1.0",- description: "New sessions will use the updated provider.",- dismissAfterVisibleMs: 3_000,- });- });-- it("keeps unchanged sidebar pill states dismissible", () => {- const view = getProviderUpdateSidebarPillView(- [- provider({- driver: driver("cursor"),- updateState: {- status: "unchanged",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "still old",- output: null,- },- }),- ],- { visibleAfterIso: sessionStartedAt },- );-- expect(view).toMatchObject({- key: "unchanged:cursor:2026-04-23T10:00:00.000Z:still old",- tone: "warning",- title: "Cursor still needs an update",- dismissible: true,- });- });-- it("does not show sidebar terminal states from before the current app session", () => {- expect(- getProviderUpdateSidebarPillView(- [- provider({- driver: driver("codex"),- updateState: {- status: "failed",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "command failed",- output: "stderr",- },- }),- ],- { visibleAfterIso: "2026-04-23T10:00:01.000Z" },- ),- ).toBeNull();- });-- it("shows a newer success before falling back to an older failure", () => {- const providers = [- provider({- driver: driver("claudeAgent"),- updateState: {- status: "failed",- startedAt: checkedAt,- finishedAt: checkedAt,- message: "Update command exited with code 1.",- output: null,- },- }),- provider({- driver: driver("codex"),- version: "1.2.0",- latestVersion: "1.2.0",- advisoryStatus: "current",- updateState: {- status: "succeeded",- startedAt: laterCheckedAt,- finishedAt: laterCheckedAt,- message: "Provider updated.",- output: null,- },- }),- ] satisfies ReadonlyArray<ServerProvider>;-- const successView = getProviderUpdateSidebarPillView(providers, {- visibleAfterIso: sessionStartedAt,- });- expect(successView).toMatchObject({- key: "succeeded:codex:2026-04-23T10:01:00.000Z:Provider updated.",- tone: "success",- title: "Codex updated: v1.2.0",- });-- const failureView = getProviderUpdateSidebarPillView(providers, {- visibleAfterIso: sessionStartedAt,- dismissedKeys: new Set(["succeeded:codex:2026-04-23T10:01:00.000Z:Provider updated."]),- });- expect(failureView).toMatchObject({- key: "failed:claudeAgent:2026-04-23T10:00:00.000Z:Update command exited with code 1.",- tone: "error",- title: "Claude v1.1.0 update failed",- });- });-- it("does not show a sidebar pill for passive update availability", () => {- expect(- getProviderUpdateSidebarPillView([- provider({ driver: driver("codex"), canUpdate: true }),- provider({ driver: driver("cursor"), canUpdate: false }),- ]),- ).toBeNull();- });-- describe("multi-backend update outcomes", () => {- const terminalState = (- status: "succeeded" | "failed" | "unchanged",- message: string,- ): NonNullable<ServerProvider["updateState"]> => ({- status,- startedAt: checkedAt,- finishedAt: checkedAt,- message,- output: null,- });-- const fulfilledOutcome = (- isPrimary: boolean,- snapshot: ServerProvider | null,- environment = "env",- ): PromiseSettledResult<LocalProviderUpdateOutcome> => ({- status: "fulfilled",- value: {- environmentId: environment as LocalProviderUpdateOutcome["environmentId"],- isPrimary,- driver: snapshot?.driver ?? driver("codex"),- instanceId: snapshot?.instanceId ?? instanceId("codex"),- provider: snapshot,- },- });-- it("surfaces a secondary backend's failed update over the primary's success", () => {- const snapshots = collectProviderUpdateOutcomeSnapshots([- fulfilledOutcome(- true,- provider({- driver: driver("codex"),- updateState: terminalState("succeeded", "Provider updated."),- }),- ),- fulfilledOutcome(- false,- provider({- driver: driver("codex"),- updateState: terminalState("failed", "npm: NotFound"),- }),- ),- ]);-- expect(snapshots).toHaveLength(1);- expect(snapshots[0]?.updateState?.status).toBe("failed");- expect(- getProviderUpdateProgressToastView({ providers: snapshots, providerCount: 1 }),- ).toMatchObject({ phase: "failed" });- });-- it("surfaces a secondary backend that stayed outdated over the primary's success", () => {- const snapshots = collectProviderUpdateOutcomeSnapshots([- fulfilledOutcome(- true,- provider({- driver: driver("codex"),- updateState: terminalState("succeeded", "Provider updated."),- }),- ),- fulfilledOutcome(- false,- provider({- driver: driver("codex"),- updateState: terminalState("unchanged", "still outdated"),- }),- ),- ]);-- expect(snapshots[0]?.updateState?.status).toBe("unchanged");- expect(- getProviderUpdateProgressToastView({ providers: snapshots, providerCount: 1 }),- ).toMatchObject({ phase: "unchanged" });- });-- it("reports success only when every backend succeeded", () => {- const snapshots = collectProviderUpdateOutcomeSnapshots([- fulfilledOutcome(- true,- provider({- driver: driver("codex"),- updateState: terminalState("succeeded", "Provider updated."),- }),- ),- fulfilledOutcome(- false,- provider({- driver: driver("codex"),- updateState: terminalState("succeeded", "Provider updated."),- }),- ),- ]);-- expect(- getProviderUpdateProgressToastView({ providers: snapshots, providerCount: 1 }),- ).toMatchObject({ phase: "succeeded" });- });-- it("ignores backends that did not return the targeted instance", () => {- const primary = provider({- driver: driver("codex"),- updateState: terminalState("succeeded", "Provider updated."),- });- const snapshots = collectProviderUpdateOutcomeSnapshots([- fulfilledOutcome(true, primary),- fulfilledOutcome(false, null),- ]);-- expect(snapshots).toEqual([primary]);- });-- it("flags the first unsuccessful secondary outcome, skipping the primary and successes", () => {- const primaryFailed = provider({- driver: driver("codex"),- updateState: terminalState("failed", "primary boom"),- });-- expect(- firstUnsuccessfulSecondaryProviderOutcome([- fulfilledOutcome(true, primaryFailed),- fulfilledOutcome(- false,- provider({- driver: driver("codex"),- updateState: terminalState("succeeded", "ok"),- }),- ),- ]),- ).toBeNull();-- expect(- firstUnsuccessfulSecondaryProviderOutcome([- fulfilledOutcome(true, primaryFailed),- fulfilledOutcome(- false,- provider({- driver: driver("codex"),- updateState: terminalState("failed", "wsl boom"),- }),- ),- ]),- ).toMatchObject({ status: "failed", provider: { updateState: { message: "wsl boom" } } });- });-- it("treats a rejected dispatch as not contributing a snapshot", () => {- const primary = provider({- driver: driver("codex"),- updateState: terminalState("succeeded", "Provider updated."),- });- const results: PromiseSettledResult<LocalProviderUpdateOutcome>[] = [- fulfilledOutcome(true, primary),- { status: "rejected", reason: new Error("WebSocket closed") },- ];-- expect(collectProviderUpdateOutcomeSnapshots(results)).toEqual([primary]);- 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();- });- });-- describe("isTerminalProviderUpdatePhase", () => {- it("treats succeeded/failed/unchanged as terminal", () => {- expect(isTerminalProviderUpdatePhase("succeeded")).toBe(true);- expect(isTerminalProviderUpdatePhase("failed")).toBe(true);- expect(isTerminalProviderUpdatePhase("unchanged")).toBe(true);- });-- it("treats running/initial as non-terminal so they are not persisted", () => {- // The per-environment update row uses this to decide what to store. A- // "running"/"initial" snapshot never re-polls, so persisting it would pin- // the row's spinner forever once pending clears (see the- // resolveEnvironmentUpdateRowStatus "keeps a non-terminal result on- // loading even after pending clears" case). Dropping these lets the live- // per-environment provider state drive the row so it self-heals.- expect(isTerminalProviderUpdatePhase("running")).toBe(false);- expect(isTerminalProviderUpdatePhase("initial")).toBe(false);- });- });-- describe("resolveEnvironmentUpdateRowStatus", () => {- const group: LocalEnvironmentUpdateGroup = {- environmentId: "env-wsl" as EnvironmentId,- label: "WSL",- isPrimary: false,- isSettling: false,- candidates: [updateCandidate({ driver: driver("codex"), latestVersion: "1.1.0" })],- providers: [],- };- const runningResult: ProviderUpdateToastView = {- phase: "running",- type: "loading",- title: "Updating providers",- description: "Running provider update command.",- };- const succeededResult: ProviderUpdateToastView = {- phase: "succeeded",- type: "success",- title: "Provider updated",- description: "New sessions will use the updated provider.",- };- const successPill: ProviderUpdateSidebarPillView = {- key: "succeeded:codex",- tone: "success",- title: "Codex updated",- description: "New sessions will use the updated provider.",- };-- it("prefers a transport error", () => {- expect(- resolveEnvironmentUpdateRowStatus({- group,- error: "boom",- result: succeededResult,- pill: successPill,- isPending: true,- }),- ).toMatchObject({ kind: "failed", text: "boom" });- });-- it("uses a terminal result snapshot", () => {- expect(- resolveEnvironmentUpdateRowStatus({- group,- error: undefined,- result: succeededResult,- pill: null,- isPending: false,- }),- ).toMatchObject({ kind: "success" });- });-- it("falls through a non-terminal result to live server state", () => {- // The dispatch snapshot is still "running", but server state already- // reports success — the row must not stay pinned on "Updating…".- expect(- resolveEnvironmentUpdateRowStatus({- group,- error: undefined,- result: runningResult,- pill: successPill,- isPending: true,- }),- ).toMatchObject({ kind: "success" });- });-- it("shows the pending spinner before any signal arrives", () => {- expect(- resolveEnvironmentUpdateRowStatus({- group,- error: undefined,- result: runningResult,- pill: null,- isPending: true,- }),- ).toMatchObject({ kind: "loading" });- });-- it("keeps a non-terminal result on loading even after pending clears", () => {- // The dispatch returned an incomplete ("running") snapshot and pending was- // cleared in finally — the row must not revert to the idle Update button.- expect(- resolveEnvironmentUpdateRowStatus({- group,- error: undefined,- result: runningResult,- pill: null,- isPending: false,- }),- ).toMatchObject({ kind: "loading" });- });-- it("lists the providers when idle", () => {- expect(- resolveEnvironmentUpdateRowStatus({- group,- error: undefined,- result: undefined,- pill: null,- isPending: false,- }),- ).toMatchObject({ kind: "idle", text: "Codex" });- });- });-});diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.logic.ts b/apps/web/src/components/ProviderUpdateLaunchNotification.logic.tsdeleted file mode 100644index 8d8abf73e..000000000--- a/apps/web/src/components/ProviderUpdateLaunchNotification.logic.ts+++ /dev/null@@ -1,839 +0,0 @@-import {- defaultInstanceIdForDriver,- PROVIDER_DISPLAY_NAMES,- type EnvironmentId,- type ExecutionEnvironmentPlatformOs,- type ProviderDriverKind,- type ProviderInstanceId,- type ServerProvider,-} from "@t3tools/contracts";-import {- squashAtomCommandFailure,- type AtomCommandResult,-} from "@t3tools/client-runtime/state/runtime";--export type ProviderUpdateCandidate = ServerProvider & {- readonly versionAdvisory: NonNullable<ServerProvider["versionAdvisory"]> & {- readonly status: "behind_latest";- readonly latestVersion: string;- };-};--export type ProviderUpdateToastType = "warning" | "loading" | "error" | "success";-export type ProviderUpdateToastPhase = "initial" | "running" | "failed" | "unchanged" | "succeeded";--export interface ProviderUpdateToastView {- readonly phase: ProviderUpdateToastPhase;- readonly type: ProviderUpdateToastType;- readonly title: string;- readonly description: string;- readonly dismissAfterVisibleMs?: number;-}--/**- * Terminal update phases — outcomes that are safe to persist as a one-shot row- * result. A non-terminal ("initial"/"running") snapshot never re-polls itself,- * so storing one pins an update row's spinner indefinitely once its pending flag- * expires; such phases must be dropped in favor of the live per-environment- * provider state instead of being persisted.- */-export function isTerminalProviderUpdatePhase(phase: ProviderUpdateToastPhase): boolean {- return phase === "succeeded" || phase === "failed" || phase === "unchanged";-}--export type ProviderUpdateSidebarPillTone = "loading" | "warning" | "error" | "success";--export interface ProviderUpdateSidebarPillView {- readonly key: string;- readonly tone: ProviderUpdateSidebarPillTone;- readonly title: string;- readonly description: string;- readonly dismissible?: boolean;- readonly dismissAfterVisibleMs?: number;-}--interface ProviderUpdateSidebarPillOptions {- readonly visibleAfterIso?: string;- readonly dismissedKeys?: ReadonlySet<string>;-}--const PROVIDER_UPDATE_SUCCESS_VISIBLE_MS = 3_000;--function formatVersion(value: string): string {- return value.startsWith("v") ? value : `v${value}`;-}--function chooseRepresentativeProvider(- current: ServerProvider | undefined,- candidate: ServerProvider,-): ServerProvider {- if (!current) {- return candidate;- }- const defaultInstanceId = defaultInstanceIdForDriver(candidate.driver);- if (candidate.instanceId === defaultInstanceId) {- return candidate;- }- if (current.instanceId === defaultInstanceId) {- return current;- }- return candidate.checkedAt.localeCompare(current.checkedAt) >= 0 ? candidate : current;-}--function dedupeProvidersByDriver<T extends ServerProvider>(providers: ReadonlyArray<T>): T[] {- const latestProviderByDriver = new Map<ProviderDriverKind, T>();-- for (const provider of providers) {- latestProviderByDriver.set(- provider.driver,- chooseRepresentativeProvider(latestProviderByDriver.get(provider.driver), provider) as T,- );- }-- return [...latestProviderByDriver.values()];-}--function dedupeProvidersByInstanceId<T extends ServerProvider>(providers: ReadonlyArray<T>): T[] {- const latestProviderByInstanceId = new Map<ProviderInstanceId, T>();-- for (const provider of providers) {- const current = latestProviderByInstanceId.get(provider.instanceId);- if (!current || provider.checkedAt.localeCompare(current.checkedAt) >= 0) {- latestProviderByInstanceId.set(provider.instanceId, provider);- }- }-- return [...latestProviderByInstanceId.values()];-}--function getProviderUpdatedTitle(provider: Pick<ServerProvider, "driver" | "version">): string {- const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;- return provider.version- ? `${providerName} updated: ${formatVersion(provider.version)}`- : `${providerName} updated`;-}--function getProviderUpdatedDescription(providerCount: number): string {- return providerCount === 1- ? "New sessions will use the updated provider."- : "New sessions will use the updated providers.";-}--function getProviderFailedUpdateTitle(- provider: Pick<ServerProvider, "driver" | "versionAdvisory">,-): string {- const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;- const attemptedVersion = provider.versionAdvisory?.latestVersion;- return attemptedVersion- ? `${providerName} ${formatVersion(attemptedVersion)} update failed`- : `${providerName} update failed`;-}--export function isProviderUpdateCandidate(- provider: ServerProvider,-): provider is ProviderUpdateCandidate {- return (- provider.enabled &&- provider.versionAdvisory?.status === "behind_latest" &&- provider.versionAdvisory.latestVersion !== null- );-}--export function isProviderUpdateActive(provider: Pick<ServerProvider, "updateState">): boolean {- return provider.updateState?.status === "queued" || provider.updateState?.status === "running";-}--export function collectProviderUpdateCandidates(- providers: ReadonlyArray<ServerProvider>,-): ProviderUpdateCandidate[] {- return dedupeProvidersByDriver(providers.filter(isProviderUpdateCandidate));-}--export function hasOneClickUpdateProviderCandidate(- candidate: ProviderUpdateCandidate,- providers: ReadonlyArray<ServerProvider>,-): boolean {- if (- candidate.versionAdvisory.canUpdate !== true ||- candidate.versionAdvisory.updateCommand === null- ) {- return false;- }-- const driverProviders = providers.filter((provider) => provider.driver === candidate.driver);- if (driverProviders.length === 0) {- return false;- }-- const updateCommands = new Set<string>();- for (const provider of driverProviders) {- if (!isProviderUpdateCandidate(provider)) {- continue;- }- const advisory = provider.versionAdvisory;- if (!advisory || advisory.canUpdate !== true || advisory.updateCommand === null) {- return false;- }- updateCommands.add(advisory.updateCommand);- }-- return updateCommands.size === 1;-}--export function canOneClickUpdateProviderCandidate(- candidate: ProviderUpdateCandidate,- providers: ReadonlyArray<ServerProvider>,-): boolean {- return (- !isProviderUpdateActive(candidate) && hasOneClickUpdateProviderCandidate(candidate, providers)- );-}--export function providerUpdateNotificationKey(- providers: ReadonlyArray<ProviderUpdateCandidate>,-): string | null {- const parts = dedupeProvidersByDriver(providers)- .map((provider) => {- const advisory = provider.versionAdvisory;- return [provider.driver, advisory.latestVersion].join(":");- })- .toSorted();-- return parts.length > 0 ? parts.join("|") : null;-}--export function providerUpdateCandidateKey(provider: ProviderUpdateCandidate): string {- return providerUpdateNotificationKey([provider])!;-}--export function formatProviderList(providers: ReadonlyArray<Pick<ServerProvider, "driver">>) {- const names = providers.map(- (provider) => PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver,- );- if (names.length <= 2) {- return names.join(" and ");- }- return `${names.slice(0, -1).join(", ")}, and ${names[names.length - 1]}`;-}--export function getProviderUpdateInitialToastView(input: {- readonly updateProviders: ReadonlyArray<ProviderUpdateCandidate>;- readonly oneClickProviders: ReadonlyArray<ProviderUpdateCandidate>;-}): ProviderUpdateToastView {- return {- phase: "initial",- type: "warning",- title: getProviderUpdateInitialToastTitle(input.updateProviders),- description:- input.oneClickProviders.length > 0- ? "Install the update now or review provider settings."- : `${formatProviderList(input.updateProviders)} can be updated from provider settings.`,- };-}--export function shouldShowPrimaryProviderUpdateToast(view: ProviderUpdateToastView): boolean {- return view.phase !== "running";-}--export function getProviderUpdateRunningToastView(providerCount: number): ProviderUpdateToastView {- return {- phase: "running",- type: "loading",- title: providerCount === 1 ? "Updating provider" : "Updating providers",- description: "Running provider update command.",- };-}--export function getProviderUpdateRejectedToastView(- providerCount: number,- message: string,-): ProviderUpdateToastView {- return {- phase: "failed",- type: "error",- title: providerCount === 1 ? "Provider update failed" : "Provider updates failed",- description: message,- };-}--export function getProviderUpdateProgressToastView(input: {- readonly providers: ReadonlyArray<ServerProvider>;- readonly providerCount: number;-}): ProviderUpdateToastView {- const providers = dedupeProvidersByDriver(input.providers);- const failedProviders = providers.filter((provider) => provider.updateState?.status === "failed");- if (failedProviders.length > 0) {- return {- phase: "failed",- type: "error",- title: failedProviders.length === 1 ? "Provider update failed" : "Provider updates failed",- description: getFailedProviderUpdateDescription(failedProviders),- };- }-- const unchangedProviders = providers.filter(- (provider) => provider.updateState?.status === "unchanged",- );- if (unchangedProviders.length > 0) {- return {- phase: "unchanged",- type: "warning",- title:- unchangedProviders.length === 1- ? "Provider still needs an update"- : "Providers still need updates",- description: `${formatProviderList(unchangedProviders)} ${- unchangedProviders.length === 1 ? "still appears" : "still appear"- } outdated. Check provider settings for details.`,- };- }-- if (providers.some(isProviderUpdateActive)) {- return getProviderUpdateRunningToastView(input.providerCount);- }-- const hasCompleteProviderSnapshots = providers.length >= input.providerCount;- const allProvidersUpdated =- hasCompleteProviderSnapshots &&- providers.every(- (provider) =>- provider.updateState?.status === "succeeded" || !isProviderUpdateCandidate(provider),- );- if (allProvidersUpdated) {- return {- phase: "succeeded",- type: "success",- title: input.providerCount === 1 ? "Provider updated" : "Provider updates finished",- description: getProviderUpdatedDescription(input.providerCount),- dismissAfterVisibleMs: PROVIDER_UPDATE_SUCCESS_VISIBLE_MS,- };- }-- return getProviderUpdateRunningToastView(input.providerCount);-}--export function getSingleProviderUpdateProgressToastView(- provider: ServerProvider,-): ProviderUpdateToastView {- const view = getProviderUpdateProgressToastView({- providers: [provider],- providerCount: 1,- });- const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;-- switch (view.phase) {- case "running":- return {- ...view,- title: `Updating ${providerName}`,- };- case "failed":- return {- ...view,- title: getProviderFailedUpdateTitle(provider),- };- case "unchanged":- return {- ...view,- title: `${providerName} still needs an update`,- };- case "succeeded":- return {- ...view,- title: getProviderUpdatedTitle(provider),- };- default:- return view;- }-}--export function collectUpdatedProviderSnapshots(input: {- readonly results: ReadonlyArray<- AtomCommandResult<{ readonly providers: ReadonlyArray<ServerProvider> }, unknown>- >;- readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;-}): ServerProvider[] {- const matchedProviders: ServerProvider[] = [];-- for (const result of input.results) {- if (result._tag === "Failure") {- continue;- }- for (const provider of result.value.providers) {- if (input.providerInstanceIds.has(provider.instanceId)) {- matchedProviders.push(provider);- }- }- }-- return dedupeProvidersByInstanceId(matchedProviders);-}--export function firstFailedProviderUpdateMessage(- results: ReadonlyArray<AtomCommandResult<unknown, unknown>>,-): string | null {- const failed = results.find((result) => result._tag === "Failure");- if (!failed || failed._tag !== "Failure") {- return null;- }- const error = squashAtomCommandFailure(failed);- return error instanceof Error ? error.message : "Provider update failed.";-}--function getUpdateFinishedAt(provider: ServerProvider): string | null {- return provider.updateState?.finishedAt ?? null;-}--function isRecentTerminalProvider(- provider: ServerProvider,- visibleAfterIso: string | undefined,-): boolean {- const status = provider.updateState?.status;- if (status !== "failed" && status !== "unchanged" && status !== "succeeded") {- return false;- }- if (visibleAfterIso === undefined) {- return true;- }- const finishedAt = getUpdateFinishedAt(provider);- return finishedAt !== null && finishedAt >= visibleAfterIso;-}--function latestFinishedAtForProviders(providers: ReadonlyArray<ServerProvider>): string | null {- return providers.reduce<string | null>((latest, provider) => {- const finishedAt = getUpdateFinishedAt(provider);- if (finishedAt === null) {- return latest;- }- return latest === null || finishedAt > latest ? finishedAt : latest;- }, null);-}--export function getProviderUpdateSidebarPillView(- providers: ReadonlyArray<ServerProvider>,- options?: ProviderUpdateSidebarPillOptions,-): ProviderUpdateSidebarPillView | null {- const dedupedProviders = dedupeProvidersByDriver(providers);- const activeProviders = dedupedProviders.filter(isProviderUpdateActive);- if (activeProviders.length > 0) {- const activeProvider = activeProviders[0]!;- const activeProviderName =- PROVIDER_DISPLAY_NAMES[activeProvider.driver] ?? activeProvider.driver;- return {- key: `loading:${activeProviders- .map((provider) => `${provider.driver}:${provider.updateState?.status ?? "idle"}`)- .toSorted()- .join("|")}`,- tone: "loading",- title:- activeProviders.length === 1- ? `Updating ${activeProviderName}`- : `Updating ${activeProviders.length} providers`,- description:- activeProviders.length === 1- ? `${formatProviderList(activeProviders)} update in progress.`- : `${formatProviderList(activeProviders)} updates are in progress.`,- };- }-- const recentTerminalProviders = dedupedProviders.filter((provider) =>- isRecentTerminalProvider(provider, options?.visibleAfterIso),- );- const terminalCandidates: ProviderUpdateSidebarPillView[] = [];-- const failedProviders = recentTerminalProviders.filter(- (provider) => provider.updateState?.status === "failed",- );- if (failedProviders.length > 0) {- const failedProvider = failedProviders[0]!;- terminalCandidates.push({- key: `failed:${failedProviders- .map(- (provider) =>- `${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,- )- .toSorted()- .join("|")}`,- tone: "error",- title:- failedProviders.length === 1- ? getProviderFailedUpdateTitle(failedProvider)- : `${failedProviders.length} provider updates failed`,- description: getFailedProviderUpdateDescription(failedProviders),- dismissible: true,- });- }-- const unchangedProviders = recentTerminalProviders.filter(- (provider) => provider.updateState?.status === "unchanged",- );- if (unchangedProviders.length > 0) {- const unchangedProvider = unchangedProviders[0]!;- const unchangedProviderName =- PROVIDER_DISPLAY_NAMES[unchangedProvider.driver] ?? unchangedProvider.driver;- terminalCandidates.push({- key: `unchanged:${unchangedProviders- .map(- (provider) =>- `${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,- )- .toSorted()- .join("|")}`,- tone: "warning",- title:- unchangedProviders.length === 1- ? `${unchangedProviderName} still needs an update`- : `${unchangedProviders.length} providers still need updates`,- description: `${formatProviderList(unchangedProviders)} ${- unchangedProviders.length === 1 ? "still appears" : "still appear"- } outdated. Review provider settings for details.`,- dismissible: true,- });- }-- const succeededProviders = recentTerminalProviders.filter(- (provider) => provider.updateState?.status === "succeeded",- );- if (succeededProviders.length > 0) {- const succeededProvider = succeededProviders[0]!;- terminalCandidates.push({- key: `succeeded:${succeededProviders- .map(- (provider) =>- `${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,- )- .toSorted()- .join("|")}`,- tone: "success",- title:- succeededProviders.length === 1- ? getProviderUpdatedTitle(succeededProvider)- : `${succeededProviders.length} providers updated`,- description: getProviderUpdatedDescription(succeededProviders.length),- dismissAfterVisibleMs: PROVIDER_UPDATE_SUCCESS_VISIBLE_MS,- });- }-- return (- terminalCandidates- .toSorted((left, right) => {- const leftProviders =- left.tone === "error"- ? failedProviders- : left.tone === "warning"- ? unchangedProviders- : succeededProviders;- const rightProviders =- right.tone === "error"- ? failedProviders- : right.tone === "warning"- ? unchangedProviders- : succeededProviders;- const leftFinishedAt = latestFinishedAtForProviders(leftProviders) ?? "";- const rightFinishedAt = latestFinishedAtForProviders(rightProviders) ?? "";- return rightFinishedAt.localeCompare(leftFinishedAt);- })- .find((candidate) => !options?.dismissedKeys?.has(candidate.key)) ?? null- );-}--function getProviderUpdateInitialToastTitle(- providers: ReadonlyArray<ProviderUpdateCandidate>,-): string {- if (providers.length === 1) {- const provider = providers[0]!;- const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;- return `Update Available: ${providerName} ${formatVersion(provider.versionAdvisory.latestVersion)}`;- }- return `Updates Available: ${providers.length} providers`;-}--function getFailedProviderUpdateDescription(providers: ReadonlyArray<ServerProvider>): string {- if (providers.length === 1) {- const provider = providers[0]!;- if (provider.updateState?.message) {- return provider.updateState.message;- }- }- return `${formatProviderList(providers)} failed to update. Check provider settings for details.`;-}--// ===========================================================================-// Multi-environment provider updates-//-// With a desktop-local secondary backend present (the WSL backend alongside the-// Windows primary), a provider update is applied across every local backend.-// Each environment owns its own provider instances, so candidates and progress-// are computed per environment and the dispatch targets that environment's-// connection. These helpers are pure; the dispatch itself runs through the-// `serverEnvironment.updateProvider` atom command in the components.-// ===========================================================================--/**- * The settled result of dispatching a provider update to one local backend.- * `provider` is the post-update snapshot of the targeted instance returned by- * that backend (null when the backend did not report the targeted instance,- * e.g. it does not have it installed).- */-export interface LocalProviderUpdateOutcome {- readonly environmentId: EnvironmentId;- readonly isPrimary: boolean;- readonly driver: ProviderDriverKind;- readonly instanceId: ProviderInstanceId;- readonly provider: ServerProvider | null;-}--// Worst-case ordering across backends: a failed copy outranks an unchanged one,-// which outranks a still-running one, which outranks a succeeded one.-const PROVIDER_UPDATE_STATUS_SEVERITY: Record<string, number> = {- succeeded: 1,- queued: 2,- running: 2,- unchanged: 3,- failed: 4,-};--function providerUpdateOutcomeSeverity(provider: ServerProvider): number {- return PROVIDER_UPDATE_STATUS_SEVERITY[provider.updateState?.status ?? ""] ?? 0;-}--export function firstRejectedProviderUpdateMessage(- results: ReadonlyArray<PromiseSettledResult<unknown>>,-): string | null {- const rejected = results.find((result) => result.status === "rejected");- if (!rejected) {- return null;- }- return rejected.reason instanceof Error ? rejected.reason.message : "Provider update failed.";-}--/**- * Reduce per-backend update outcomes to one representative snapshot per driver,- * keeping the worst-case status across every local backend. Because the same- * driver has a distinct instance id per environment, a secondary backend (e.g.- * WSL) that *resolved* with a failed or unchanged provider would otherwise be- * filtered out (its instance id is not the primary's) or collapsed behind the- * primary's success — this surfaces it instead.- */-export function collectProviderUpdateOutcomeSnapshots(- results: ReadonlyArray<PromiseSettledResult<LocalProviderUpdateOutcome>>,-): ServerProvider[] {- const worstByDriver = new Map<ProviderDriverKind, ServerProvider>();- for (const result of results) {- if (result.status !== "fulfilled" || result.value.provider === null) {- continue;- }- const provider = result.value.provider;- const current = worstByDriver.get(provider.driver);- if (- !current ||- providerUpdateOutcomeSeverity(provider) > providerUpdateOutcomeSeverity(current)- ) {- worstByDriver.set(provider.driver, provider);- }- }- return [...worstByDriver.values()];-}--/**- * The first secondary (non-primary) backend whose update resolved without- * succeeding. The primary's own failed/unchanged state is already surfaced- * inline in settings, so only secondaries (which have no inline row) need an- * explicit callout.- */-export function firstUnsuccessfulSecondaryProviderOutcome(- results: ReadonlyArray<PromiseSettledResult<LocalProviderUpdateOutcome>>,-): { readonly provider: ServerProvider; readonly status: "failed" | "unchanged" } | null {- for (const result of results) {- if (result.status !== "fulfilled") {- continue;- }- const outcome = result.value;- if (outcome.isPrimary || outcome.provider === null) {- continue;- }- const status = outcome.provider.updateState?.status;- if (status === "failed" || status === "unchanged") {- return { provider: outcome.provider, status };- }- }- return null;-}--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;-}--export type ProviderUpdateRowStatusKind = "idle" | "loading" | "success" | "failed" | "unchanged";--export interface ProviderUpdateRowStatus {- readonly kind: ProviderUpdateRowStatusKind;- readonly text: string;-}--function environmentProviderNames(group: LocalEnvironmentUpdateGroup): string {- return group.candidates- .map((candidate) => PROVIDER_DISPLAY_NAMES[candidate.driver] ?? candidate.driver)- .join(", ");-}--/**- * Resolve one environment row's display from every available signal, in- * priority order: a transport rejection, then the dispatch's own *terminal*- * 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 state.- *- * A non-terminal result snapshot ("running") is intentionally skipped rather- * than treated as authoritative, so live server state can still drive the row- * to its terminal status instead of pinning it on "Updating…".- */-export function resolveEnvironmentUpdateRowStatus(input: {- readonly group: LocalEnvironmentUpdateGroup;- readonly error: string | undefined;- readonly result: ProviderUpdateToastView | undefined;- readonly pill: ProviderUpdateSidebarPillView | null;- readonly isPending: boolean;-}): ProviderUpdateRowStatus {- 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 };- // "running" / "initial": non-terminal snapshot — fall through to live state.- }- }- 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…" };- }- }- // A non-terminal result snapshot or the optimistic pending flag means an- // update is still in flight — keep showing the spinner rather than reverting- // to the Update button as if nothing happened.- if (input.result || input.isPending) {- return { kind: "loading", text: "Updating…" };- }- return { kind: "idle", text: environmentProviderNames(input.group) };-}diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.tsx b/apps/web/src/components/ProviderUpdateLaunchNotification.tsxdeleted file mode 100644index 70e771305..000000000--- a/apps/web/src/components/ProviderUpdateLaunchNotification.tsx+++ /dev/null@@ -1,197 +0,0 @@-import { DownloadIcon } from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";--import { useEnvironments } from "~/state/environments";-import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";-import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal";-import { ProviderUpdateEnvironmentRows } from "./ProviderUpdateEnvironmentRows";-import { useLocalEnvironmentUpdateGroups } from "./ProviderUpdateLaunchNotification.environments";-import {- collectProviderUpdateCandidates,- environmentGroupsWithUpdates,- getProviderUpdateInitialToastView,- localEnvironmentUpdateNotificationKey,-} from "./ProviderUpdateLaunchNotification.logic";-import { ProviderUpdatePrimaryNotification } from "./ProviderUpdatePrimaryNotification";-import { stackedThreadToast, toastManager } from "./ui/toast";-import { openSettings } from "~/settingsDialogStore";--/**- * True when a desktop-local secondary backend (the parallel WSL backend) is- * present alongside the primary. Local secondaries connect over loopback with a- * `local:<backendInstanceId>` bearer connection id; everything else (SSH or- * another remote target) is ignored. Gating on this keeps non-WSL users on the unchanged- * single-prompt flow.- */-function useHasLocalSecondaryEnvironment(): boolean {- const { environments } = useEnvironments();- return useMemo(- () =>- environments.some((environment) => isDesktopLocalConnectionTarget(environment.entry.target)),- [environments],- );-}--/**- * 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 hasLocalSecondary = useHasLocalSecondaryEnvironment();-- return hasLocalSecondary ? (- <ProviderUpdateEnvironmentsNotification />- ) : (- <ProviderUpdatePrimaryNotification />- );-}--const seenProviderUpdateNotificationKeys = new Set<string>();-type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;--// 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 ProviderUpdateEnvironmentsNotification() {- const { groups, isAnySettling } = useLocalEnvironmentUpdateGroups();- const { dismissedNotificationKeys, dismissNotificationKey } =- useDismissedProviderUpdateNotificationKeys();-- const activeToastRef = useRef<{- readonly toastId: ProviderUpdateToastId;- readonly key: string;- } | null>(null);- const notificationKeyRef = useRef<string | null>(null);- // Whether the user has triggered an update from the current toast. Until they- // do, the prompt is replaced when the available updates change; afterward it- // is kept so in-progress rows are not torn down.- const hasInteractedRef = useRef(false);-- // 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.toastId);- activeToastRef.current = null;- }- };- }, []);-- 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(() => {- if (!isAnySettling) {- setSettleGraceElapsed(false);- return;- }- const timer = setTimeout(() => setSettleGraceElapsed(true), SETTLING_GRACE_MS);- return () => clearTimeout(timer);- }, [isAnySettling]);- const isGated = isAnySettling && !settleGraceElapsed;-- const openProviderSettings = useCallback(() => {- const active = activeToastRef.current;- if (active !== null) {- toastManager.close(active.toastId);- activeToastRef.current = null;- }- openSettings("providers");- }, []);-- useEffect(() => {- // Whether a fresh prompt can actually be shown for the current update set.- const canShowPrompt =- notificationKey !== null &&- !isGated &&- !dismissedNotificationKeys.has(notificationKey) &&- !seenProviderUpdateNotificationKeys.has(notificationKey);-- // Close a prompt the user hasn't acted on yet when the available updates- // change: when they clear entirely (key null) so the toast doesn't linger,- // and when a fresh set is ready to replace it. Keep it only while a backend- // is re-settling (updates still exist, just gated) — and once an update is- // in progress, so its rows survive.- const active = activeToastRef.current;- if (- active &&- active.key !== notificationKey &&- !hasInteractedRef.current &&- (notificationKey === null || !isGated)- ) {- toastManager.close(active.toastId);- activeToastRef.current = null;- }-- if (!notificationKey || !canShowPrompt || activeToastRef.current !== null) {- return;- }-- seenProviderUpdateNotificationKeys.add(notificationKey);- hasInteractedRef.current = false;-- const dismissPrompt = () => {- // 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);- }- activeToastRef.current = null;- };-- const toastId = toastManager.add(- stackedThreadToast({- type: "warning",- title: getProviderUpdateInitialToastView({- updateProviders: candidateUnion,- oneClickProviders: candidateUnion,- }).title,- description: (- <ProviderUpdateEnvironmentRows- onInteract={() => {- hasInteractedRef.current = true;- }}- />- ),- timeout: 0,- actionProps: {- children: "Settings",- onClick: openProviderSettings,- },- actionVariant: "outline",- data: {- hideCopyButton: true,- leadingIcon: <DownloadIcon aria-hidden="true" className="size-4 text-success" />,- onClose: dismissPrompt,- },- }),- );- activeToastRef.current = { toastId, key: notificationKey };- }, [- notificationKey,- isGated,- candidateUnion,- dismissedNotificationKeys,- dismissNotificationKey,- openProviderSettings,- ]);-- return null;-}diff --git a/apps/web/src/components/ProviderUpdatePrimaryNotification.test.tsx b/apps/web/src/components/ProviderUpdatePrimaryNotification.test.tsxdeleted file mode 100644index a9423979a..000000000--- a/apps/web/src/components/ProviderUpdatePrimaryNotification.test.tsx+++ /dev/null@@ -1,177 +0,0 @@-import type { ReactElement } from "react";-import {- EnvironmentId,- ProviderDriverKind,- ProviderInstanceId,- type ServerProvider,-} from "@t3tools/contracts";-import * as Cause from "effect/Cause";-import { AsyncResult } from "effect/unstable/reactivity";-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";--import { reactHookHarness as hooks } from "../test/reactHookHarness";--const state = vi.hoisted(() => ({- environmentId: "environment-a" as EnvironmentId,- providers: [] as ServerProvider[],- updateProvider: vi.fn(),- openSettings: vi.fn(),- dismissNotificationKey: vi.fn(),- toasts: [] as Array<Record<string, unknown>>,- closedToastIds: [] as string[],- notificationVersion: 0,-}));--vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- const { reactHookHarness } = await import("../test/reactHookHarness");- return {- ...actual,- useCallback: reactHookHarness.useCallback,- useEffect: (effect: () => void | (() => void)) => {- effect();- },- useMemo: reactHookHarness.useMemo,- useRef: reactHookHarness.useRef,- };-});--vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});--vi.mock("@effect/atom-react", () => ({- useAtomValue: () => state.providers,-}));--vi.mock("../state/server", () => ({- primaryServerProvidersAtom: Symbol("primaryServerProvidersAtom"),- serverEnvironment: { updateProvider: Symbol("updateProvider") },-}));--vi.mock("../state/environments", () => ({- usePrimaryEnvironment: () => ({ environmentId: state.environmentId }),-}));--vi.mock("../state/use-atom-command", () => ({- useAtomCommand: () => state.updateProvider,-}));--vi.mock("../providerUpdateDismissal", () => ({- useDismissedProviderUpdateNotificationKeys: () => ({- dismissedNotificationKeys: new Set<string>(),- dismissNotificationKey: state.dismissNotificationKey,- }),-}));--vi.mock("~/settingsDialogStore", () => ({- openSettings: state.openSettings,-}));--vi.mock("./ui/toast", () => ({- hiddenToastActionProps: { children: null },- stackedThreadToast: (input: Record<string, unknown>) => input,- toastManager: {- add: (input: Record<string, unknown>) => {- state.toasts.push(input);- return `toast-${state.toasts.length}`;- },- close: (toastId: string) => state.closedToastIds.push(toastId),- },-}));--import { ProviderUpdatePrimaryNotification } from "./ProviderUpdatePrimaryNotification";--const providerInstanceId = ProviderInstanceId.make("codex");--function provider(updateState?: ServerProvider["updateState"]): ServerProvider {- return {- instanceId: providerInstanceId,- driver: ProviderDriverKind.make("codex"),- enabled: true,- installed: true,- version: "1.0.0",- status: "ready",- auth: { status: "authenticated" },- checkedAt: "2026-08-30T12:00:00.000Z",- models: [],- slashCommands: [],- skills: [],- versionAdvisory: {- status: "behind_latest",- currentVersion: "1.0.0",- latestVersion: `1.1.${state.notificationVersion}`,- updateCommand: "npm install -g @openai/codex@latest",- canUpdate: true,- checkedAt: "2026-08-30T12:00:00.000Z",- message: "Update available.",- },- ...(updateState ? { updateState } : {}),- };-}--function renderNotification() {- hooks.beginRender();- return ProviderUpdatePrimaryNotification() as ReactElement | null;-}--describe("ProviderUpdatePrimaryNotification", () => {- beforeEach(() => {- hooks.reset();- state.environmentId = EnvironmentId.make("environment-a");- state.providers = [provider()];- state.updateProvider.mockReset().mockReturnValue(new Promise(() => {}));- state.openSettings.mockReset();- state.dismissNotificationKey.mockReset();- state.toasts = [];- state.closedToastIds = [];- state.notificationVersion += 1;- });-- it("uses an outline action for routine update notices", () => {- renderNotification();-- expect(state.toasts[0]).toMatchObject({ actionVariant: "outline" });- });-- it("opens repair settings for the environment where the update started", async () => {- let finishUpdate!: () => void;- state.updateProvider.mockImplementation(- () =>- new Promise((resolve) => {- finishUpdate = () => resolve(AsyncResult.failure(Cause.die(new Error("Update failed"))));- }),- );- renderNotification();-- const prompt = state.toasts[0] as {- actionProps?: { onClick?: () => void };- };- prompt.actionProps?.onClick?.();-- state.environmentId = EnvironmentId.make("environment-b");- renderNotification();- expect(state.toasts).toHaveLength(1);-- finishUpdate();- await Promise.resolve();- await Promise.resolve();-- const repairToast = state.toasts[1] as {- actionProps?: { onClick?: () => void };- };- repairToast.actionProps?.onClick?.();-- expect(state.openSettings).toHaveBeenCalledWith(- "providers",- null,- EnvironmentId.make("environment-a"),- );- expect(state.openSettings).not.toHaveBeenCalledWith(- "providers",- null,- EnvironmentId.make("environment-b"),- );- });-});diff --git a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsxdeleted file mode 100644index 7ab94f44b..000000000--- a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx+++ /dev/null@@ -1,342 +0,0 @@-import { useAtomValue } from "@effect/atom-react";-import { DownloadIcon } from "lucide-react";-import { useCallback, useEffect, useMemo, useRef } from "react";-import {- type EnvironmentId,- type ProviderDriverKind,- type ProviderInstanceId,-} from "@t3tools/contracts";--import { primaryServerProvidersAtom, serverEnvironment } from "../state/server";-import { usePrimaryEnvironment } from "../state/environments";-import { useDismissedProviderUpdateNotificationKeys } from "../providerUpdateDismissal";-import { PROVIDER_ICON_BY_PROVIDER } from "./chat/providerIconUtils";-import {- canOneClickUpdateProviderCandidate,- collectProviderUpdateCandidates,- collectUpdatedProviderSnapshots,- firstFailedProviderUpdateMessage,- getProviderUpdateInitialToastView,- getProviderUpdateProgressToastView,- getProviderUpdateRejectedToastView,- providerUpdateNotificationKey,- shouldShowPrimaryProviderUpdateToast,- type ProviderUpdateToastView,-} from "./ProviderUpdateLaunchNotification.logic";-import { hiddenToastActionProps, stackedThreadToast, toastManager } from "./ui/toast";-import { useAtomCommand } from "../state/use-atom-command";-import { openSettings } from "~/settingsDialogStore";--const seenProviderUpdateNotificationKeys = new Set<string>();-type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;--type ActiveProviderUpdateToast =- | {- readonly kind: "prompt";- readonly key: string;- readonly environmentId: EnvironmentId | null;- readonly toastId: ProviderUpdateToastId;- }- | {- readonly kind: "update";- readonly key: string;- readonly environmentId: EnvironmentId;- readonly providerInstanceIds: ReadonlySet<ProviderInstanceId>;- readonly providerCount: number;- };--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 addProviderUpdateToast(input: {- readonly view: ProviderUpdateToastView;- readonly openSettings: (toastId: ProviderUpdateToastId) => void;-}) {- if (input.view.type === "loading" || input.view.type === "success") {- return toastManager.add({- type: input.view.type,- title: input.view.title,- description: input.view.description,- timeout: 0,- actionProps: hiddenToastActionProps,- data: {- hideCopyButton: true,- ...(input.view.dismissAfterVisibleMs !== undefined- ? { dismissAfterVisibleMs: input.view.dismissAfterVisibleMs }- : {}),- },- });- }-- let toastId!: ProviderUpdateToastId;- toastId = toastManager.add(- stackedThreadToast({- type: input.view.type,- title: input.view.title,- description: input.view.description,- timeout: 0,- actionProps: {- children: "Settings",- onClick: () => input.openSettings(toastId),- },- actionVariant: "outline",- data: {- hideCopyButton: true,- },- }),- );- return toastId;-}--/**- * 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 providers = useAtomValue(primaryServerProvidersAtom);- const primaryEnvironment = usePrimaryEnvironment();- const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {- reportFailure: false,- });- 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?.kind === "prompt") {- 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 | undefined, environmentId: EnvironmentId | null) => {- const activeToast = activeToastRef.current;- if (toastId !== undefined) {- toastManager.close(toastId);- } else if (activeToast?.kind === "prompt") {- toastManager.close(activeToast.toastId);- }- if (- activeToast &&- (toastId === undefined ||- (activeToast.kind === "prompt" && activeToast.toastId === toastId))- ) {- activeToastRef.current = null;- }- openSettings("providers", null, environmentId);- },- [],- );-- useEffect(() => {- const activeToast = activeToastRef.current;- if (activeToast?.kind !== "update") {- return;- }- if (primaryEnvironment?.environmentId !== activeToast.environmentId) {- return;- }-- const activeProviders = providers.filter((provider) =>- activeToast.providerInstanceIds.has(provider.instanceId),- );- const view = getProviderUpdateProgressToastView({- providers: activeProviders,- providerCount: activeToast.providerCount,- });- if (!shouldShowPrimaryProviderUpdateToast(view)) {- return;- }-- addProviderUpdateToast({- view,- openSettings: (toastId) => openProviderSettings(toastId, activeToast.environmentId),- });- activeToastRef.current = null;- }, [primaryEnvironment?.environmentId, 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 });- const promptEnvironmentId = primaryEnvironment?.environmentId ?? null;-- let toastId!: ProviderUpdateToastId;- let updateStarted = false;- const openSettings = () => openProviderSettings(toastId, promptEnvironmentId);- const dismissPrompt = () => {- dismissNotificationKey(notificationKey);- };-- const runUpdates = () => {- if (updateStarted || oneClickProviders.length === 0 || promptEnvironmentId === null) {- return;- }- updateStarted = true;-- const providerCount = oneClickProviders.length;- const providerInstanceIds = new Set(oneClickProviders.map((provider) => provider.instanceId));- const activeUpdate: ActiveProviderUpdateToast = {- kind: "update",- key: notificationKey,- environmentId: promptEnvironmentId,- providerInstanceIds,- providerCount,- };- activeToastRef.current = activeUpdate;-- toastManager.close(toastId);-- void (async () => {- const results = [];- for (const provider of oneClickProviders) {- results.push(- await updateProvider({- environmentId: activeUpdate.environmentId,- input: {- provider: provider.driver,- instanceId: provider.instanceId,- },- }),- );- }-- const activeUpdateToast = activeToastRef.current;- if (activeUpdateToast !== activeUpdate) {- return;- }-- const failedMessage = firstFailedProviderUpdateMessage(results);- if (failedMessage) {- addProviderUpdateToast({- view: getProviderUpdateRejectedToastView(providerCount, failedMessage),- openSettings: (toastId) => openProviderSettings(toastId, activeUpdate.environmentId),- });- activeToastRef.current = null;- return;- }-- const updatedProviderSnapshots = collectUpdatedProviderSnapshots({- results,- providerInstanceIds,- });- const view = getProviderUpdateProgressToastView({- providers: updatedProviderSnapshots,- providerCount,- });- if (shouldShowPrimaryProviderUpdateToast(view)) {- addProviderUpdateToast({- view,- openSettings: (toastId) => openProviderSettings(toastId, activeUpdate.environmentId),- });- 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: "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,- environmentId: promptEnvironmentId,- toastId,- };- }, [- updateProvider,- dismissNotificationKey,- dismissedNotificationKeys,- notificationKey,- oneClickProviders,- openProviderSettings,- primaryEnvironment,- updateProviders,- ]);-- return null;-}diff --git a/apps/web/src/components/providerUpdates.logic.test.ts b/apps/web/src/components/providerUpdates.logic.test.tsnew file mode 100644index 000000000..dfe525b74--- /dev/null+++ b/apps/web/src/components/providerUpdates.logic.test.ts@@ -0,0 +1,382 @@+import { describe, expect, it } from "vite-plus/test";+import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";++import {+ canOneClickUpdateProviderCandidate,+ collectProviderUpdateCandidates,+ getProviderUpdateSidebarPillView,+ hasOneClickUpdateProviderCandidate,+ isProviderUpdateCandidate,+ type ProviderUpdateCandidate,+} from "./providerUpdates.logic";++const checkedAt = "2026-04-23T10:00:00.000Z";+const sessionStartedAt = "2026-04-23T09:59:00.000Z";+const laterCheckedAt = "2026-04-23T10:01:00.000Z";++const driver = (value: string) => ProviderDriverKind.make(value);+const instanceId = (value: string) => ProviderInstanceId.make(value);++function provider(input: {+ readonly driver: ReturnType<typeof ProviderDriverKind.make>;+ readonly instanceId?: ReturnType<typeof ProviderInstanceId.make>;+ readonly enabled?: boolean;+ readonly version?: string | null;+ readonly latestVersion?: string | null;+ readonly canUpdate?: boolean;+ readonly updateCommand?: string | null;+ readonly updateState?: ServerProvider["updateState"];+ readonly advisoryStatus?: NonNullable<ServerProvider["versionAdvisory"]>["status"];+}): ServerProvider {+ const result: ServerProvider = {+ instanceId: input.instanceId ?? instanceId(String(input.driver)),+ driver: input.driver,+ enabled: input.enabled ?? true,+ installed: true,+ version: input.version ?? "1.0.0",+ status: "ready",+ auth: { status: "authenticated" },+ checkedAt,+ models: [],+ slashCommands: [],+ skills: [],+ versionAdvisory: {+ status: input.advisoryStatus ?? "behind_latest",+ currentVersion: input.version ?? "1.0.0",+ latestVersion: "latestVersion" in input ? input.latestVersion : "1.1.0",+ updateCommand: "updateCommand" in input ? input.updateCommand : "npm install -g provider",+ canUpdate: input.canUpdate ?? true,+ checkedAt,+ message: "Update available.",+ },+ };++ if (input.updateState) {+ return { ...result, updateState: input.updateState };+ }++ return result;+}++function updateCandidate(input: Parameters<typeof provider>[0]): ProviderUpdateCandidate {+ return provider(input) as ProviderUpdateCandidate;+}++describe("provider update logic", () => {+ it("detects enabled providers with a latest-version advisory", () => {+ expect(isProviderUpdateCandidate(provider({ driver: driver("codex") }))).toBe(true);+ expect(isProviderUpdateCandidate(provider({ driver: driver("codex"), enabled: false }))).toBe(+ false,+ );+ expect(+ isProviderUpdateCandidate(+ provider({ driver: driver("codex"), advisoryStatus: "current", latestVersion: null }),+ ),+ ).toBe(false);+ expect(+ isProviderUpdateCandidate(provider({ driver: driver("codex"), latestVersion: null })),+ ).toBe(false);+ });++ it("deduplicates multi-instance provider candidates by driver", () => {+ expect(+ collectProviderUpdateCandidates([+ provider({+ driver: driver("codex"),+ instanceId: instanceId("codex_personal"),+ latestVersion: "1.1.0",+ }),+ provider({+ driver: driver("codex"),+ instanceId: instanceId("codex"),+ latestVersion: "1.1.0",+ }),+ provider({ driver: driver("cursor"), latestVersion: "0.3.0" }),+ ]),+ ).toHaveLength(2);+ });++ it("disables one-click updates when provider instances disagree on the update command", () => {+ const candidate = updateCandidate({+ driver: driver("claudeAgent"),+ instanceId: instanceId("claude_personal"),+ latestVersion: "2.1.123",+ });++ expect(+ canOneClickUpdateProviderCandidate(candidate, [+ candidate,+ provider({+ driver: driver("claudeAgent"),+ instanceId: instanceId("claude_work"),+ latestVersion: "2.1.123",+ canUpdate: true,+ updateCommand: "bun add -g @anthropic-ai/claude-code@latest",+ }),+ ]),+ ).toBe(false);+ });++ it("keeps one-click updates enabled when sibling instances are already current", () => {+ const candidate = updateCandidate({+ driver: driver("claudeAgent"),+ instanceId: instanceId("claude_personal"),+ latestVersion: "2.1.123",+ updateCommand: "npm install -g @anthropic-ai/claude-code@latest",+ });++ expect(+ hasOneClickUpdateProviderCandidate(candidate, [+ candidate,+ provider({+ driver: driver("claudeAgent"),+ instanceId: instanceId("claude_work"),+ version: "2.1.123",+ latestVersion: "2.1.123",+ advisoryStatus: "current",+ canUpdate: false,+ updateCommand: null,+ }),+ ]),+ ).toBe(true);+ expect(+ canOneClickUpdateProviderCandidate(candidate, [+ candidate,+ provider({+ driver: driver("claudeAgent"),+ instanceId: instanceId("claude_work"),+ version: "2.1.123",+ latestVersion: "2.1.123",+ advisoryStatus: "current",+ canUpdate: false,+ updateCommand: null,+ }),+ ]),+ ).toBe(true);+ });++ it("keeps the inline update action available while a provider update is already running", () => {+ const candidate = updateCandidate({+ driver: driver("codex"),+ updateState: {+ status: "running",+ startedAt: checkedAt,+ finishedAt: null,+ message: "Updating provider.",+ output: null,+ },+ });++ expect(hasOneClickUpdateProviderCandidate(candidate, [candidate])).toBe(true);+ expect(canOneClickUpdateProviderCandidate(candidate, [candidate])).toBe(false);+ });++ it("summarizes active provider updates for the sidebar pill", () => {+ const view = getProviderUpdateSidebarPillView([+ provider({+ driver: driver("codex"),+ updateState: {+ status: "running",+ startedAt: checkedAt,+ finishedAt: null,+ message: "Updating provider.",+ output: null,+ },+ }),+ provider({+ driver: driver("cursor"),+ updateState: {+ status: "queued",+ startedAt: null,+ finishedAt: null,+ message: "Waiting for another provider update to finish.",+ output: null,+ },+ }),+ ]);++ expect(view).toMatchObject({+ tone: "loading",+ title: "Updating 2 providers",+ description: "Codex and Cursor updates are in progress.",+ });+ });++ it("uses the provider name for single active sidebar pill updates", () => {+ const view = getProviderUpdateSidebarPillView([+ provider({+ driver: driver("codex"),+ updateState: {+ status: "running",+ startedAt: checkedAt,+ finishedAt: null,+ message: "Updating provider.",+ output: null,+ },+ }),+ ]);++ expect(view).toMatchObject({+ key: "loading:codex:running",+ tone: "loading",+ title: "Updating Codex",+ description: "Codex update in progress.",+ });+ });++ it("uses the provider name for single failed sidebar pill updates", () => {+ const view = getProviderUpdateSidebarPillView(+ [+ provider({+ driver: driver("claudeAgent"),+ updateState: {+ status: "failed",+ startedAt: checkedAt,+ finishedAt: checkedAt,+ message: "Update command exited with code 1.",+ output: null,+ },+ }),+ ],+ { visibleAfterIso: sessionStartedAt },+ );++ expect(view).toMatchObject({+ key: "failed:claudeAgent:2026-04-23T10:00:00.000Z:Update command exited with code 1.",+ tone: "error",+ title: "Claude v1.1.0 update failed",+ description: "Update command exited with code 1.",+ dismissible: true,+ });+ });++ it("shows a short-lived success sidebar pill after a single provider update succeeds", () => {+ const view = getProviderUpdateSidebarPillView(+ [+ provider({+ driver: driver("codex"),+ version: "1.1.0",+ latestVersion: "1.1.0",+ advisoryStatus: "current",+ updateState: {+ status: "succeeded",+ startedAt: checkedAt,+ finishedAt: checkedAt,+ message: "Provider updated.",+ output: null,+ },+ }),+ ],+ { visibleAfterIso: sessionStartedAt },+ );++ expect(view).toMatchObject({+ key: "succeeded:codex:2026-04-23T10:00:00.000Z:Provider updated.",+ tone: "success",+ title: "Codex updated: v1.1.0",+ description: "New sessions will use the updated provider.",+ dismissAfterVisibleMs: 3_000,+ });+ });++ it("keeps unchanged sidebar pill states dismissible", () => {+ const view = getProviderUpdateSidebarPillView(+ [+ provider({+ driver: driver("cursor"),+ updateState: {+ status: "unchanged",+ startedAt: checkedAt,+ finishedAt: checkedAt,+ message: "still old",+ output: null,+ },+ }),+ ],+ { visibleAfterIso: sessionStartedAt },+ );++ expect(view).toMatchObject({+ key: "unchanged:cursor:2026-04-23T10:00:00.000Z:still old",+ tone: "warning",+ title: "Cursor still needs an update",+ dismissible: true,+ });+ });++ it("does not show sidebar terminal states from before the current app session", () => {+ expect(+ getProviderUpdateSidebarPillView(+ [+ provider({+ driver: driver("codex"),+ updateState: {+ status: "failed",+ startedAt: checkedAt,+ finishedAt: checkedAt,+ message: "command failed",+ output: "stderr",+ },+ }),+ ],+ { visibleAfterIso: "2026-04-23T10:00:01.000Z" },+ ),+ ).toBeNull();+ });++ it("shows a newer success before falling back to an older failure", () => {+ const providers = [+ provider({+ driver: driver("claudeAgent"),+ updateState: {+ status: "failed",+ startedAt: checkedAt,+ finishedAt: checkedAt,+ message: "Update command exited with code 1.",+ output: null,+ },+ }),+ provider({+ driver: driver("codex"),+ version: "1.2.0",+ latestVersion: "1.2.0",+ advisoryStatus: "current",+ updateState: {+ status: "succeeded",+ startedAt: laterCheckedAt,+ finishedAt: laterCheckedAt,+ message: "Provider updated.",+ output: null,+ },+ }),+ ] satisfies ReadonlyArray<ServerProvider>;++ const successView = getProviderUpdateSidebarPillView(providers, {+ visibleAfterIso: sessionStartedAt,+ });+ expect(successView).toMatchObject({+ key: "succeeded:codex:2026-04-23T10:01:00.000Z:Provider updated.",+ tone: "success",+ title: "Codex updated: v1.2.0",+ });++ const failureView = getProviderUpdateSidebarPillView(providers, {+ visibleAfterIso: sessionStartedAt,+ dismissedKeys: new Set(["succeeded:codex:2026-04-23T10:01:00.000Z:Provider updated."]),+ });+ expect(failureView).toMatchObject({+ key: "failed:claudeAgent:2026-04-23T10:00:00.000Z:Update command exited with code 1.",+ tone: "error",+ title: "Claude v1.1.0 update failed",+ });+ });++ it("does not show a sidebar pill for passive update availability", () => {+ expect(+ getProviderUpdateSidebarPillView([+ provider({ driver: driver("codex"), canUpdate: true }),+ provider({ driver: driver("cursor"), canUpdate: false }),+ ]),+ ).toBeNull();+ });+});diff --git a/apps/web/src/components/providerUpdates.logic.ts b/apps/web/src/components/providerUpdates.logic.tsnew file mode 100644index 000000000..dda750fcc--- /dev/null+++ b/apps/web/src/components/providerUpdates.logic.ts@@ -0,0 +1,330 @@+import {+ defaultInstanceIdForDriver,+ PROVIDER_DISPLAY_NAMES,+ type ProviderDriverKind,+ type ServerProvider,+} from "@t3tools/contracts";++export type ProviderUpdateCandidate = ServerProvider & {+ readonly versionAdvisory: NonNullable<ServerProvider["versionAdvisory"]> & {+ readonly status: "behind_latest";+ readonly latestVersion: string;+ };+};++export type ProviderUpdateSidebarPillTone = "loading" | "warning" | "error" | "success";++export interface ProviderUpdateSidebarPillView {+ readonly key: string;+ readonly tone: ProviderUpdateSidebarPillTone;+ readonly title: string;+ readonly description: string;+ readonly dismissible?: boolean;+ readonly dismissAfterVisibleMs?: number;+}++interface ProviderUpdateSidebarPillOptions {+ readonly visibleAfterIso?: string;+ readonly dismissedKeys?: ReadonlySet<string>;+}++const PROVIDER_UPDATE_SUCCESS_VISIBLE_MS = 3_000;++function formatVersion(value: string): string {+ return value.startsWith("v") ? value : `v${value}`;+}++function chooseRepresentativeProvider(+ current: ServerProvider | undefined,+ candidate: ServerProvider,+): ServerProvider {+ if (!current) {+ return candidate;+ }+ const defaultInstanceId = defaultInstanceIdForDriver(candidate.driver);+ if (candidate.instanceId === defaultInstanceId) {+ return candidate;+ }+ if (current.instanceId === defaultInstanceId) {+ return current;+ }+ return candidate.checkedAt.localeCompare(current.checkedAt) >= 0 ? candidate : current;+}++function dedupeProvidersByDriver<T extends ServerProvider>(providers: ReadonlyArray<T>): T[] {+ const latestProviderByDriver = new Map<ProviderDriverKind, T>();++ for (const provider of providers) {+ latestProviderByDriver.set(+ provider.driver,+ chooseRepresentativeProvider(latestProviderByDriver.get(provider.driver), provider) as T,+ );+ }++ return [...latestProviderByDriver.values()];+}++function getProviderUpdatedTitle(provider: Pick<ServerProvider, "driver" | "version">): string {+ const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;+ return provider.version+ ? `${providerName} updated: ${formatVersion(provider.version)}`+ : `${providerName} updated`;+}++function getProviderUpdatedDescription(providerCount: number): string {+ return providerCount === 1+ ? "New sessions will use the updated provider."+ : "New sessions will use the updated providers.";+}++function getProviderFailedUpdateTitle(+ provider: Pick<ServerProvider, "driver" | "versionAdvisory">,+): string {+ const providerName = PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver;+ const attemptedVersion = provider.versionAdvisory?.latestVersion;+ return attemptedVersion+ ? `${providerName} ${formatVersion(attemptedVersion)} update failed`+ : `${providerName} update failed`;+}++export function isProviderUpdateCandidate(+ provider: ServerProvider,+): provider is ProviderUpdateCandidate {+ return (+ provider.enabled &&+ provider.versionAdvisory?.status === "behind_latest" &&+ provider.versionAdvisory.latestVersion !== null+ );+}++export function isProviderUpdateActive(provider: Pick<ServerProvider, "updateState">): boolean {+ return provider.updateState?.status === "queued" || provider.updateState?.status === "running";+}++export function collectProviderUpdateCandidates(+ providers: ReadonlyArray<ServerProvider>,+): ProviderUpdateCandidate[] {+ return dedupeProvidersByDriver(providers.filter(isProviderUpdateCandidate));+}++export function hasOneClickUpdateProviderCandidate(+ candidate: ProviderUpdateCandidate,+ providers: ReadonlyArray<ServerProvider>,+): boolean {+ if (+ candidate.versionAdvisory.canUpdate !== true ||+ candidate.versionAdvisory.updateCommand === null+ ) {+ return false;+ }++ const driverProviders = providers.filter((provider) => provider.driver === candidate.driver);+ if (driverProviders.length === 0) {+ return false;+ }++ const updateCommands = new Set<string>();+ for (const provider of driverProviders) {+ if (!isProviderUpdateCandidate(provider)) {+ continue;+ }+ const advisory = provider.versionAdvisory;+ if (!advisory || advisory.canUpdate !== true || advisory.updateCommand === null) {+ return false;+ }+ updateCommands.add(advisory.updateCommand);+ }++ return updateCommands.size === 1;+}++export function canOneClickUpdateProviderCandidate(+ candidate: ProviderUpdateCandidate,+ providers: ReadonlyArray<ServerProvider>,+): boolean {+ return (+ !isProviderUpdateActive(candidate) && hasOneClickUpdateProviderCandidate(candidate, providers)+ );+}++export function formatProviderList(providers: ReadonlyArray<Pick<ServerProvider, "driver">>) {+ const names = providers.map(+ (provider) => PROVIDER_DISPLAY_NAMES[provider.driver] ?? provider.driver,+ );+ if (names.length <= 2) {+ return names.join(" and ");+ }+ return `${names.slice(0, -1).join(", ")}, and ${names[names.length - 1]}`;+}++function getUpdateFinishedAt(provider: ServerProvider): string | null {+ return provider.updateState?.finishedAt ?? null;+}++function isRecentTerminalProvider(+ provider: ServerProvider,+ visibleAfterIso: string | undefined,+): boolean {+ const status = provider.updateState?.status;+ if (status !== "failed" && status !== "unchanged" && status !== "succeeded") {+ return false;+ }+ if (visibleAfterIso === undefined) {+ return true;+ }+ const finishedAt = getUpdateFinishedAt(provider);+ return finishedAt !== null && finishedAt >= visibleAfterIso;+}++function latestFinishedAtForProviders(providers: ReadonlyArray<ServerProvider>): string | null {+ return providers.reduce<string | null>((latest, provider) => {+ const finishedAt = getUpdateFinishedAt(provider);+ if (finishedAt === null) {+ return latest;+ }+ return latest === null || finishedAt > latest ? finishedAt : latest;+ }, null);+}++/**+ * The sidebar pill reports progress and outcome of an update the user started+ * from provider settings. Passive update availability never produces a pill;+ * that state is only shown inline in Settings → Providers.+ */+export function getProviderUpdateSidebarPillView(+ providers: ReadonlyArray<ServerProvider>,+ options?: ProviderUpdateSidebarPillOptions,+): ProviderUpdateSidebarPillView | null {+ const dedupedProviders = dedupeProvidersByDriver(providers);+ const activeProviders = dedupedProviders.filter(isProviderUpdateActive);+ if (activeProviders.length > 0) {+ const activeProvider = activeProviders[0]!;+ const activeProviderName =+ PROVIDER_DISPLAY_NAMES[activeProvider.driver] ?? activeProvider.driver;+ return {+ key: `loading:${activeProviders+ .map((provider) => `${provider.driver}:${provider.updateState?.status ?? "idle"}`)+ .toSorted()+ .join("|")}`,+ tone: "loading",+ title:+ activeProviders.length === 1+ ? `Updating ${activeProviderName}`+ : `Updating ${activeProviders.length} providers`,+ description:+ activeProviders.length === 1+ ? `${formatProviderList(activeProviders)} update in progress.`+ : `${formatProviderList(activeProviders)} updates are in progress.`,+ };+ }++ const recentTerminalProviders = dedupedProviders.filter((provider) =>+ isRecentTerminalProvider(provider, options?.visibleAfterIso),+ );+ const terminalCandidates: ProviderUpdateSidebarPillView[] = [];++ const failedProviders = recentTerminalProviders.filter(+ (provider) => provider.updateState?.status === "failed",+ );+ if (failedProviders.length > 0) {+ const failedProvider = failedProviders[0]!;+ terminalCandidates.push({+ key: `failed:${failedProviders+ .map(+ (provider) =>+ `${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,+ )+ .toSorted()+ .join("|")}`,+ tone: "error",+ title:+ failedProviders.length === 1+ ? getProviderFailedUpdateTitle(failedProvider)+ : `${failedProviders.length} provider updates failed`,+ description: getFailedProviderUpdateDescription(failedProviders),+ dismissible: true,+ });+ }++ const unchangedProviders = recentTerminalProviders.filter(+ (provider) => provider.updateState?.status === "unchanged",+ );+ if (unchangedProviders.length > 0) {+ const unchangedProvider = unchangedProviders[0]!;+ const unchangedProviderName =+ PROVIDER_DISPLAY_NAMES[unchangedProvider.driver] ?? unchangedProvider.driver;+ terminalCandidates.push({+ key: `unchanged:${unchangedProviders+ .map(+ (provider) =>+ `${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,+ )+ .toSorted()+ .join("|")}`,+ tone: "warning",+ title:+ unchangedProviders.length === 1+ ? `${unchangedProviderName} still needs an update`+ : `${unchangedProviders.length} providers still need updates`,+ description: `${formatProviderList(unchangedProviders)} ${+ unchangedProviders.length === 1 ? "still appears" : "still appear"+ } outdated. Review provider settings for details.`,+ dismissible: true,+ });+ }++ const succeededProviders = recentTerminalProviders.filter(+ (provider) => provider.updateState?.status === "succeeded",+ );+ if (succeededProviders.length > 0) {+ const succeededProvider = succeededProviders[0]!;+ terminalCandidates.push({+ key: `succeeded:${succeededProviders+ .map(+ (provider) =>+ `${provider.driver}:${provider.updateState?.finishedAt ?? "pending"}:${provider.updateState?.message ?? ""}`,+ )+ .toSorted()+ .join("|")}`,+ tone: "success",+ title:+ succeededProviders.length === 1+ ? getProviderUpdatedTitle(succeededProvider)+ : `${succeededProviders.length} providers updated`,+ description: getProviderUpdatedDescription(succeededProviders.length),+ dismissAfterVisibleMs: PROVIDER_UPDATE_SUCCESS_VISIBLE_MS,+ });+ }++ return (+ terminalCandidates+ .toSorted((left, right) => {+ const leftProviders =+ left.tone === "error"+ ? failedProviders+ : left.tone === "warning"+ ? unchangedProviders+ : succeededProviders;+ const rightProviders =+ right.tone === "error"+ ? failedProviders+ : right.tone === "warning"+ ? unchangedProviders+ : succeededProviders;+ const leftFinishedAt = latestFinishedAtForProviders(leftProviders) ?? "";+ const rightFinishedAt = latestFinishedAtForProviders(rightProviders) ?? "";+ return rightFinishedAt.localeCompare(leftFinishedAt);+ })+ .find((candidate) => !options?.dismissedKeys?.has(candidate.key)) ?? null+ );+}++function getFailedProviderUpdateDescription(providers: ReadonlyArray<ServerProvider>): string {+ if (providers.length === 1) {+ const provider = providers[0]!;+ if (provider.updateState?.message) {+ return provider.updateState.message;+ }+ }+ return `${formatProviderList(providers)} failed to update. Check provider settings for details.`;+}diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsxindex 799a0840b..e311b22bb 100644--- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx+++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx@@ -60,7 +60,7 @@ import {hasOneClickUpdateProviderCandidate,isProviderUpdateActive,type ProviderUpdateCandidate,-} from "../ProviderUpdateLaunchNotification.logic";+} from "../providerUpdates.logic";import { Button } from "../ui/button";import {NumberField,diff --git a/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsxindex 494ee97e7..fc3ca755a 100644--- a/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx+++ b/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx@@ -8,7 +8,7 @@ import { openSettings } from "../../settingsDialogStore";import {getProviderUpdateSidebarPillView,type ProviderUpdateSidebarPillView,-} from "../ProviderUpdateLaunchNotification.logic";+} from "../providerUpdates.logic";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { Button } from "../ui/button";diff --git a/apps/web/src/providerUpdateDismissal.test.ts b/apps/web/src/providerUpdateDismissal.test.tsdeleted file mode 100644index 732107cd8..000000000--- a/apps/web/src/providerUpdateDismissal.test.ts+++ /dev/null@@ -1,23 +0,0 @@-import { beforeEach, describe, expect, it } from "vite-plus/test";--import { removeLocalStorageItem } from "./hooks/useLocalStorage";-import {- dismissProviderUpdateNotification,- isProviderUpdateNotificationDismissed,- PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,-} from "./providerUpdateDismissal";--describe("providerUpdateDismissal", () => {- beforeEach(() => {- removeLocalStorageItem(PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY);- });-- it("persists provider update dismissals by notification key", () => {- expect(isProviderUpdateNotificationDismissed("opencode:1.14.33")).toBe(false);-- dismissProviderUpdateNotification("opencode:1.14.33");-- expect(isProviderUpdateNotificationDismissed("opencode:1.14.33")).toBe(true);- expect(isProviderUpdateNotificationDismissed("opencode:1.14.34")).toBe(false);- });-});diff --git a/apps/web/src/providerUpdateDismissal.ts b/apps/web/src/providerUpdateDismissal.tsdeleted file mode 100644index 28789152b..000000000--- a/apps/web/src/providerUpdateDismissal.ts+++ /dev/null@@ -1,93 +0,0 @@-import { useCallback, useMemo } from "react";-import * as Schema from "effect/Schema";--import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "./hooks/useLocalStorage";--export const PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY = "t3code:provider-update-dismissals:v1";--const ProviderUpdateDismissalsSchema = Schema.Struct({- keys: Schema.Array(Schema.String),-});--type ProviderUpdateDismissals = typeof ProviderUpdateDismissalsSchema.Type;--function readProviderUpdateDismissals(): ProviderUpdateDismissals {- try {- return (- getLocalStorageItem(- PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,- ProviderUpdateDismissalsSchema,- ) ?? {- keys: [],- }- );- } catch (error) {- console.error("Could not read provider-update dismissals.", error);- return { keys: [] };- }-}--function writeProviderUpdateDismissals(document: ProviderUpdateDismissals): void {- try {- setLocalStorageItem(- PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,- document,- ProviderUpdateDismissalsSchema,- );- } catch (error) {- console.error("Could not persist provider-update dismissals.", error);- }-}--export function isProviderUpdateNotificationDismissed(- dismissalKey: string | null | undefined,-): boolean {- if (!dismissalKey) {- return false;- }- return readProviderUpdateDismissals().keys.includes(dismissalKey);-}--export function dismissProviderUpdateNotification(dismissalKey: string | null | undefined): void {- const trimmedKey = dismissalKey?.trim();- if (!trimmedKey) {- return;- }- const document = readProviderUpdateDismissals();- if (document.keys.includes(trimmedKey)) {- return;- }- writeProviderUpdateDismissals({- keys: [...document.keys, trimmedKey],- });-}--export function useDismissedProviderUpdateNotificationKeys() {- const [dismissals, setDismissals] = useLocalStorage(- PROVIDER_UPDATE_DISMISSALS_STORAGE_KEY,- { keys: [] },- ProviderUpdateDismissalsSchema,- );- const dismissedKeys = dismissals.keys;-- const dismissedKeySet = useMemo(() => new Set(dismissedKeys), [dismissedKeys]);-- const dismissNotificationKey = useCallback(- (key: string) => {- const trimmedKey = key.trim();- if (trimmedKey.length === 0 || dismissedKeySet.has(trimmedKey)) {- return;- }-- setDismissals({- keys: [...dismissedKeys, trimmedKey],- });- },- [dismissedKeySet, dismissedKeys, setDismissals],- );-- return {- dismissedNotificationKeys: dismissedKeySet,- dismissNotificationKey,- };-}diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex 22a343090..77b63b30b 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -10,7 +10,6 @@ import { AppSidebarLayout } from "../components/AppSidebarLayout";import { CommandPalette } from "../components/CommandPalette";import { ConfirmDialogHost } from "../components/ConfirmDialogHost";import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";-import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";import { VoiceCallProvider } from "../components/voice/VoiceCall";import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";@@ -140,7 +139,6 @@ function RootRouteView() {<HostedStaticEnvironmentBootstrap />{primaryEnvironmentAuthenticated ? <EventRouter /> : null}{primaryEnvironmentAuthenticated ? <PlanAgentSelectionHeal /> : null}- {primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}<VoiceCallProvider>{appShell}</VoiceCallProvider><SettingsDialog /><PluginsDialog />