feat: improve agent runtime update flow (#1982)

This commit is contained in:
Carlos Florêncio
2026-07-27 19:34:13 +01:00
committed by GitHub
parent b118a4fe98
commit 2bd2bae2ea
27 changed files with 1543 additions and 435 deletions
@@ -1,143 +0,0 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { ComponentType } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { InstalledAgentCard } from "./installed-agent-card";
const ManagedCard = InstalledAgentCard as ComponentType<Record<string, unknown>>;
const AGENT_NAME = "claude-acp";
const discoveryAgent = {
name: AGENT_NAME,
supports_mcp: true,
installation_paths: [],
available: true,
matched_path: "/usr/bin/npx",
};
const runtimeUpdate = {
supported: true,
package: "@agentclientprotocol/claude-agent-acp",
current_version: "1.0.0",
};
function renderCard(overrides: Record<string, unknown> = {}) {
const onUpdate = vi.fn();
render(
<ManagedCard
agent={discoveryAgent}
savedAgent={undefined}
displayName="Claude"
runtimeUpdate={runtimeUpdate}
onUpdate={onUpdate}
{...overrides}
/>,
);
return onUpdate;
}
afterEach(cleanup);
describe("AgentRuntimeUpdateControl", () => {
it("shows a labeled touch action only for managed installed agents", () => {
const onUpdate = renderCard();
const button = screen.getByRole("button", { name: "Update agent" });
expect(button.className).toContain("min-h-11");
fireEvent.click(button);
expect(onUpdate).toHaveBeenCalledWith(AGENT_NAME);
cleanup();
renderCard({ runtimeUpdate: undefined });
expect(screen.queryByRole("button", { name: "Update agent" })).toBeNull();
});
it("shows current to target progress and a bounded wrapping log", () => {
renderCard({
updateJob: {
job_id: "update-1",
agent_name: AGENT_NAME,
status: "updating",
current_version: "1.0.0",
target_version: "1.1.0",
output: "fetching package\n",
started_at: "2026-07-26T10:00:00Z",
},
});
expect(screen.getByText("1.0.0 → 1.1.0")).not.toBeNull();
expect(screen.getByText("Updating runtime…")).not.toBeNull();
const log = screen.getByTestId("agent-update-log-claude-acp");
expect(log.className).toContain("max-h-40");
expect(log.className).toContain("overflow-y-auto");
expect(log.className).toContain("break-words");
expect(screen.getByRole("button", { name: "Updating agent" }).hasAttribute("disabled")).toBe(
true,
);
});
it("distinguishes refresh warnings from retryable update failures", () => {
const { rerender } = render(
<ManagedCard
agent={discoveryAgent}
savedAgent={undefined}
displayName="Claude"
runtimeUpdate={runtimeUpdate}
onUpdate={vi.fn()}
updateJob={{
job_id: "update-1",
agent_name: AGENT_NAME,
status: "succeeded",
current_version: "1.0.0",
target_version: "1.1.0",
refresh_error: "Authentication required",
started_at: "2026-07-26T10:00:00Z",
}}
/>,
);
expect(
screen.getByText(/runtime updated, but capabilities could not be refreshed/i),
).not.toBeNull();
expect(screen.getByText(/authentication required/i)).not.toBeNull();
rerender(
<ManagedCard
agent={discoveryAgent}
savedAgent={undefined}
displayName="Claude"
runtimeUpdate={runtimeUpdate}
onUpdate={vi.fn()}
updateJob={{
job_id: "update-2",
agent_name: AGENT_NAME,
status: "failed",
current_version: "1.0.0",
error: "Registry unavailable",
started_at: "2026-07-26T10:01:00Z",
}}
/>,
);
expect(screen.getByText("Registry unavailable")).not.toBeNull();
expect(screen.getByRole("button", { name: "Retry update" }).hasAttribute("disabled")).toBe(
false,
);
});
it("disables updates while the same agent is installing", () => {
renderCard({
installJob: {
job_id: "install-1",
agent_name: AGENT_NAME,
status: "running",
started_at: "2026-07-26T10:00:00Z",
},
});
expect(screen.getByRole("button", { name: "Update agent" }).hasAttribute("disabled")).toBe(
true,
);
expect(screen.getByText("Agent installation is in progress.")).not.toBeNull();
});
});
@@ -1,10 +1,28 @@
"use client";
import { IconLoader2, IconRefresh } from "@tabler/icons-react";
import { IconAlertTriangle, IconLoader2, IconRefresh } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import type { AgentUpdateJob, InstallJob } from "@/lib/api";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@kandev/ui/dialog";
import {
Drawer,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
} from "@kandev/ui/drawer";
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import type { AgentUpdateJob, AgentUpdatePreview, InstallJob } from "@/lib/api";
import type { RuntimeUpdate } from "@/lib/types/http";
import { useAgentUpdateDialogState } from "./use-agent-update-dialog-state";
const ACTIVE_UPDATE_STATUSES = new Set<AgentUpdateJob["status"]>([
"queued",
@@ -22,52 +40,18 @@ function updatePhase(status: AgentUpdateJob["status"] | undefined): string | nul
case "updating":
return "Updating runtime…";
case "refreshing":
return "Refreshing models…";
return "Refreshing agent capabilities…";
default:
return null;
}
}
function updateButtonLabel(status: AgentUpdateJob["status"] | undefined) {
switch (status) {
case "queued":
return "Update queued";
case "resolving":
return "Resolving update";
case "updating":
return "Updating agent";
case "refreshing":
return "Refreshing agent capabilities";
case "failed":
return "Retry update";
default:
return "Update agent";
}
}
function VersionSummary({
runtimeUpdate,
job,
}: {
runtimeUpdate: RuntimeUpdate;
job?: AgentUpdateJob;
}) {
const current = job?.current_version || runtimeUpdate.current_version || "Unknown";
if (job?.target_version) {
return <p className="break-words font-mono text-xs">{`${current} → ${job.target_version}`}</p>;
}
if (job?.status === "resolving") {
return <p className="break-words font-mono text-xs">{`${current} → Checking latest…`}</p>;
}
return <p className="break-words text-xs text-muted-foreground">Current version: {current}</p>;
}
function UpdateResult({ agentName, job }: { agentName: string; job?: AgentUpdateJob }) {
if (!job) return null;
if (job.status === "succeeded" && job.refresh_error) {
return (
<p
className="break-words text-xs text-amber-600 dark:text-amber-400"
className="break-words text-amber-600 dark:text-amber-400"
role="alert"
data-testid={`agent-update-result-${agentName}`}
>
@@ -78,7 +62,7 @@ function UpdateResult({ agentName, job }: { agentName: string; job?: AgentUpdate
if (job.status === "succeeded") {
return (
<p
className="break-words text-xs text-green-600 dark:text-green-400"
className="break-words text-green-600 dark:text-green-400"
role="status"
data-testid={`agent-update-result-${agentName}`}
>
@@ -89,7 +73,7 @@ function UpdateResult({ agentName, job }: { agentName: string; job?: AgentUpdate
if (job.status === "failed") {
return (
<p
className="break-words text-xs text-destructive"
className="break-words text-destructive"
role="alert"
data-testid={`agent-update-result-${agentName}`}
>
@@ -100,71 +84,338 @@ function UpdateResult({ agentName, job }: { agentName: string; job?: AgentUpdate
return null;
}
export function AgentRuntimeUpdateControl({
agentName,
runtimeUpdate,
job,
installJob,
onUpdate,
}: {
type UpdateBodyProps = {
agentName: string;
runtimeUpdate: RuntimeUpdate;
preview: AgentUpdatePreview | null;
loading: boolean;
previewError: string | null;
approveError: string | null;
job?: AgentUpdateJob;
installJob?: InstallJob;
onUpdate: (agentName: string) => void;
}) {
if (!runtimeUpdate.supported) return null;
onRetryPreview: () => void;
};
const updateInFlight = Boolean(job && ACTIVE_UPDATE_STATUSES.has(job.status));
const installInFlight = installJob?.status === "queued" || installJob?.status === "running";
const disabled = updateInFlight || installInFlight;
function UpdateBody({
agentName,
preview,
loading,
previewError,
approveError,
job,
onRetryPreview,
}: UpdateBodyProps) {
const phase = updatePhase(job?.status);
const buttonLabel = updateButtonLabel(job?.status);
return (
<div className="min-w-0 space-y-2" data-testid={`agent-update-control-${agentName}`}>
<VersionSummary runtimeUpdate={runtimeUpdate} job={job} />
<div
className="max-h-[calc(80dvh-10rem)] min-h-0 space-y-4 overflow-y-auto overscroll-contain px-4 py-3 text-xs/relaxed"
data-testid={`agent-update-dialog-body-${agentName}`}
>
{loading && (
<p className="flex items-center gap-2 text-muted-foreground" role="status">
<IconLoader2 className="size-4 animate-spin" />
Checking the latest runtime version…
</p>
)}
{previewError && (
<div
className="space-y-2 rounded-md border border-destructive/30 bg-destructive/5 p-3"
role="alert"
>
<p className="flex items-start gap-2 text-destructive">
<IconAlertTriangle className="mt-0.5 size-4 shrink-0" />
<span>{previewError}</span>
</p>
<Button type="button" variant="outline" size="sm" onClick={onRetryPreview}>
Retry version check
</Button>
</div>
)}
{approveError && (
<div
className="rounded-md border border-destructive/30 bg-destructive/5 p-3"
role="alert"
data-testid={`agent-update-approve-error-${agentName}`}
>
<p className="flex items-start gap-2 text-destructive">
<IconAlertTriangle className="mt-0.5 size-4 shrink-0" />
<span>Unable to start update: {approveError}</span>
</p>
</div>
)}
{preview && (
<>
<div className="space-y-1">
<p className="font-medium">Runtime version</p>
<p className="break-words font-mono text-sm">
{(job?.current_version || preview.current_version || "Unknown") +
" → " +
(job?.target_version || preview.target_version)}
</p>
</div>
<div className="space-y-1 text-muted-foreground">
<p>
This updates the managed runtime on this Kandev host, then refreshes its models and
capabilities.
</p>
<p>
Active sessions keep running; only later probes and launches use the refreshed
runtime.
</p>
</div>
<div className="space-y-1">
<p className="font-medium">Command that will run</p>
<pre className="whitespace-pre-wrap break-all rounded-md bg-muted p-3 font-mono text-xs text-muted-foreground">
{preview.command_string}
</pre>
</div>
</>
)}
{phase && (
<p
className="flex items-center gap-1.5 text-xs text-muted-foreground"
className="flex items-center gap-1.5 text-muted-foreground"
role="status"
data-testid={`agent-update-phase-${agentName}`}
>
<IconLoader2 className="h-3.5 w-3.5 shrink-0 animate-spin" />
<span className="min-w-0 break-words">{phase}</span>
</p>
)}
{installInFlight && (
<p className="break-words text-xs text-muted-foreground">
Agent installation is in progress.
<IconLoader2 className="size-3.5 shrink-0 animate-spin" />
{phase}
</p>
)}
{job?.output && (
<pre
data-testid={`agent-update-log-${agentName}`}
className="max-h-40 overflow-x-hidden overflow-y-auto whitespace-pre-wrap break-words rounded-md bg-muted px-2 py-1.5 font-mono text-xs text-muted-foreground"
className="whitespace-pre-wrap break-words rounded-md bg-muted p-3 font-mono text-xs text-muted-foreground"
>
{job.output}
</pre>
)}
<UpdateResult agentName={agentName} job={job} />
<Button
type="button"
variant="outline"
size="sm"
className="min-h-11 w-full cursor-pointer whitespace-normal"
disabled={disabled}
aria-label={buttonLabel}
onClick={() => onUpdate(agentName)}
data-testid={`agent-update-button-${agentName}`}
>
{updateInFlight ? (
<IconLoader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<IconRefresh className="mr-2 h-4 w-4" />
)}
{buttonLabel}
</Button>
</div>
);
}
type UpdateFooterProps = {
agentName: string;
preview: AgentUpdatePreview | null;
previewError: string | null;
job?: AgentUpdateJob;
loading: boolean;
starting: boolean;
installInFlight: boolean;
onApprove: () => void;
onClose: () => void;
mobile?: boolean;
};
function canApproveUpdate({
preview,
previewError,
loading,
updateInFlight,
starting,
installInFlight,
}: {
preview: AgentUpdatePreview | null;
previewError: string | null;
loading: boolean;
updateInFlight: boolean;
starting: boolean;
installInFlight: boolean;
}) {
return (
Boolean(preview?.current_version) &&
!previewError &&
!loading &&
!updateInFlight &&
!starting &&
!installInFlight
);
}
function UpdateFooter({
agentName,
preview,
previewError,
job,
loading,
starting,
installInFlight,
onApprove,
onClose,
mobile,
}: UpdateFooterProps) {
const updateInFlight = Boolean(job && ACTIVE_UPDATE_STATUSES.has(job.status));
const canRetry = job?.status === "failed";
const canApprove = canApproveUpdate({
preview,
previewError,
loading,
updateInFlight,
starting,
installInFlight,
});
const showApprove = !job || canRetry;
const content = (
<>
<Button type="button" variant="outline" onClick={onClose}>
{job?.status === "succeeded" ? "Done" : "Cancel"}
</Button>
{showApprove && (
<Button
type="button"
disabled={!canApprove}
onClick={onApprove}
data-testid={`agent-update-confirm-${agentName}`}
>
{starting && <IconLoader2 className="mr-2 size-4 animate-spin" />}
{canRetry ? "Retry update" : "Approve update"}
</Button>
)}
</>
);
if (mobile) {
return (
<DrawerFooter className="border-t pb-[max(1rem,env(safe-area-inset-bottom))]">
{content}
</DrawerFooter>
);
}
return <DialogFooter className="border-t px-4 py-3">{content}</DialogFooter>;
}
function UpdateTrigger({
agentName,
displayName,
installInFlight,
onOpen,
}: {
agentName: string;
displayName: string;
installInFlight: boolean;
onOpen: () => void;
}) {
return (
<Tooltip>
<TooltipTrigger asChild>
<span tabIndex={installInFlight ? 0 : -1} className="inline-flex">
<Button
type="button"
variant="ghost"
size="icon"
className="h-11 w-11 cursor-pointer active:scale-95 sm:h-7 sm:w-7"
aria-label={`Update ${displayName}`}
disabled={installInFlight}
onClick={onOpen}
data-testid={`agent-update-trigger-${agentName}`}
>
<IconRefresh className="size-4" />
</Button>
</span>
</TooltipTrigger>
<TooltipContent>
{installInFlight ? "Agent installation is in progress" : `Update ${displayName}`}
</TooltipContent>
</Tooltip>
);
}
export function AgentRuntimeUpdateControl({
agentName,
displayName,
runtimeUpdate,
job,
installJob,
onPreview,
onUpdate,
}: {
agentName: string;
displayName: string;
runtimeUpdate: RuntimeUpdate;
job?: AgentUpdateJob;
installJob?: InstallJob;
onPreview: (agentName: string) => Promise<AgentUpdatePreview>;
onUpdate: (agentName: string) => Promise<AgentUpdateJob>;
}) {
const { isMobile } = useResponsiveBreakpoint();
const {
activeJob,
approve,
approveError,
handleOpenChange,
loading,
loadPreview,
open,
preview,
previewError,
starting,
} = useAgentUpdateDialogState({ agentName, job, onPreview, onUpdate });
const installInFlight = installJob?.status === "queued" || installJob?.status === "running";
if (!runtimeUpdate.supported) return null;
const body = (
<UpdateBody
agentName={agentName}
preview={preview}
loading={loading}
previewError={previewError}
approveError={approveError}
job={activeJob}
onRetryPreview={() => void loadPreview()}
/>
);
const footer = (mobile = false) => (
<UpdateFooter
agentName={agentName}
preview={preview}
previewError={previewError}
job={activeJob}
loading={loading}
starting={starting}
installInFlight={installInFlight}
onApprove={() => void approve()}
onClose={() => handleOpenChange(false)}
mobile={mobile}
/>
);
return (
<>
<UpdateTrigger
agentName={agentName}
displayName={displayName}
installInFlight={installInFlight}
onOpen={() => handleOpenChange(true)}
/>
{isMobile ? (
<Drawer open={open} onOpenChange={handleOpenChange}>
<DrawerContent className="max-h-[80dvh]" data-testid={`agent-update-drawer-${agentName}`}>
<DrawerHeader className="shrink-0 text-left">
<DrawerTitle>Update {displayName}</DrawerTitle>
<DrawerDescription>
Review the update before Kandev changes this host runtime.
</DrawerDescription>
</DrawerHeader>
{body}
{footer(true)}
</DrawerContent>
</Drawer>
) : (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent
className="max-h-[80dvh] gap-0 p-0 sm:max-w-xl"
data-testid={`agent-update-dialog-${agentName}`}
>
<DialogHeader className="px-4 pt-4">
<DialogTitle>Update {displayName}</DialogTitle>
<DialogDescription>
Review the update before Kandev changes this host runtime.
</DialogDescription>
</DialogHeader>
{body}
{footer()}
</DialogContent>
</Dialog>
)}
</>
);
}
@@ -11,7 +11,7 @@ import { AgentLogo } from "@/components/agent-logo";
import { AgentLoginDialog } from "@/components/settings/agent-login-dialog";
import { AgentRuntimeUpdateControl } from "@/components/settings/agent-runtime-update-control";
import { HostShellDialog } from "@/components/settings/host-shell-dialog";
import type { AgentUpdateJob, InstallJob } from "@/lib/api";
import type { AgentUpdateJob, AgentUpdatePreview, InstallJob } from "@/lib/api";
import type { Agent, AgentDiscovery, RuntimeUpdate } from "@/lib/types/http";
type Props = {
@@ -23,7 +23,8 @@ type Props = {
runtimeUpdate?: RuntimeUpdate;
updateJob?: AgentUpdateJob;
installJob?: InstallJob;
onUpdate?: (agentName: string) => void;
onPreview?: (agentName: string) => Promise<AgentUpdatePreview>;
onUpdate?: (agentName: string) => Promise<AgentUpdateJob>;
/**
* Called when the auth/shell dialog closes so the page can refresh
* discovery + availability. Without this the yellow lock stays put even
@@ -56,40 +57,42 @@ function InstalledAgentIdentity({
<h4 className="min-w-0 truncate font-medium">{displayName}</h4>
{agent.supports_mcp && <Badge variant="secondary">MCP</Badge>}
{configured && <Badge variant="outline">Configured</Badge>}
{probing && (
<Tooltip>
<TooltipTrigger asChild>
<span
data-testid={`probing-icon-${agent.name}`}
className="ml-auto flex items-center text-muted-foreground cursor-help"
aria-label="Checking authentication"
>
<IconLoader2 className="h-3.5 w-3.5 animate-spin" />
</span>
</TooltipTrigger>
<TooltipContent>Checking agent capabilities and authentication...</TooltipContent>
</Tooltip>
)}
{authRequired && (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={onAuthClick}
data-testid={`auth-icon-${agent.name}`}
className="ml-auto flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs text-amber-500 cursor-pointer hover:bg-amber-500/10"
aria-label="Authentication required"
>
<IconLock className="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent>
{loginAvailable
? "Authentication required - click to open login terminal"
: "Authentication required - click to open a shell and sign in"}
</TooltipContent>
</Tooltip>
)}
<div className="ml-auto flex shrink-0 items-center gap-1">
{probing && (
<Tooltip>
<TooltipTrigger asChild>
<span
data-testid={`probing-icon-${agent.name}`}
className="flex items-center text-muted-foreground cursor-help"
aria-label="Checking authentication"
>
<IconLoader2 className="h-3.5 w-3.5 animate-spin" />
</span>
</TooltipTrigger>
<TooltipContent>Checking agent capabilities and authentication...</TooltipContent>
</Tooltip>
)}
{authRequired && (
<Tooltip>
<TooltipTrigger asChild>
<button
type="button"
onClick={onAuthClick}
data-testid={`auth-icon-${agent.name}`}
className="flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs text-amber-500 cursor-pointer hover:bg-amber-500/10"
aria-label="Authentication required"
>
<IconLock className="h-3.5 w-3.5" />
</button>
</TooltipTrigger>
<TooltipContent>
{loginAvailable
? "Authentication required - click to open login terminal"
: "Authentication required - click to open a shell and sign in"}
</TooltipContent>
</Tooltip>
)}
</div>
</div>
<p
className="text-xs text-muted-foreground line-clamp-2 min-h-[2rem]"
@@ -115,6 +118,7 @@ export function InstalledAgentCard({
runtimeUpdate,
updateJob,
installJob,
onPreview,
onUpdate,
onAuthComplete,
}: Props) {
@@ -146,27 +150,35 @@ export function InstalledAgentCard({
loginAvailable={loginAvailable}
onAuthClick={handleAuthClick}
/>
{runtimeUpdate?.supported && onUpdate && (
<AgentRuntimeUpdateControl
agentName={agent.name}
runtimeUpdate={runtimeUpdate}
job={updateJob}
installJob={installJob}
onUpdate={onUpdate}
/>
)}
<Button size="sm" className="cursor-pointer mt-auto" asChild>
<Link
href={
hasAgentRecord
? `/settings/agents/${encodeURIComponent(agent.name)}?mode=create`
: `/settings/agents/${encodeURIComponent(agent.name)}`
}
<div className="mt-auto flex items-center gap-2">
<Button
size="sm"
className="h-11 min-h-11 flex-1 cursor-pointer sm:h-7 sm:min-h-7"
asChild
>
<IconSettings className="h-4 w-4 mr-2" />
{hasAgentRecord ? "Create new profile" : "Setup Profile"}
</Link>
</Button>
<Link
href={
hasAgentRecord
? `/settings/agents/${encodeURIComponent(agent.name)}?mode=create`
: `/settings/agents/${encodeURIComponent(agent.name)}`
}
>
<IconSettings className="mr-2 h-4 w-4" />
{hasAgentRecord ? "Create new profile" : "Setup Profile"}
</Link>
</Button>
{runtimeUpdate?.supported && onPreview && onUpdate && (
<AgentRuntimeUpdateControl
agentName={agent.name}
displayName={displayName}
runtimeUpdate={runtimeUpdate}
job={updateJob}
installJob={installJob}
onPreview={onPreview}
onUpdate={onUpdate}
/>
)}
</div>
<AuthDialogs
agent={agent}
loginOpen={loginOpen}
@@ -0,0 +1,109 @@
import { act, renderHook, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import type { AgentUpdateJob, AgentUpdatePreview } from "@/lib/api";
import { useAgentUpdateDialogState } from "./use-agent-update-dialog-state";
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: unknown) => void;
const promise = new Promise<T>((complete, fail) => {
resolve = complete;
reject = fail;
});
return { promise, reject, resolve };
}
const FIRST_PREVIEW: AgentUpdatePreview = {
agent_name: "claude-acp",
package: "@agentclientprotocol/claude-agent-acp",
current_version: "0.62.0",
target_version: "0.63.0",
command: ["npm", "exec"],
command_string: "npm exec",
};
const AGENT_NAME = FIRST_PREVIEW.agent_name;
const UPDATE_ALREADY_RUNNING = "Update is already running";
describe("useAgentUpdateDialogState", () => {
it("ignores a preview that resolves after close and reopen", async () => {
const firstRequest = deferred<AgentUpdatePreview>();
const secondRequest = deferred<AgentUpdatePreview>();
const onPreview = vi
.fn<(agentName: string) => Promise<AgentUpdatePreview>>()
.mockReturnValueOnce(firstRequest.promise)
.mockReturnValueOnce(secondRequest.promise);
const { result } = renderHook(() =>
useAgentUpdateDialogState({
agentName: AGENT_NAME,
onPreview,
onUpdate: vi.fn(),
}),
);
act(() => result.current.handleOpenChange(true));
await waitFor(() => expect(onPreview).toHaveBeenCalledTimes(1));
act(() => result.current.handleOpenChange(false));
act(() => result.current.handleOpenChange(true));
await waitFor(() => expect(onPreview).toHaveBeenCalledTimes(2));
await act(async () => {
firstRequest.resolve(FIRST_PREVIEW);
await firstRequest.promise;
});
expect(result.current.preview).toBeNull();
expect(result.current.loading).toBe(true);
await act(async () => {
secondRequest.resolve({ ...FIRST_PREVIEW, target_version: "0.64.0" });
await secondRequest.promise;
});
await waitFor(() => expect(result.current.preview?.target_version).toBe("0.64.0"));
});
it("ignores an approval failure after the dialog closes", async () => {
const updateRequest = deferred<AgentUpdateJob>();
const onUpdate = vi
.fn<(agentName: string) => Promise<AgentUpdateJob>>()
.mockReturnValue(updateRequest.promise);
const { result } = renderHook(() =>
useAgentUpdateDialogState({
agentName: AGENT_NAME,
onPreview: vi.fn().mockResolvedValue(FIRST_PREVIEW),
onUpdate,
}),
);
act(() => {
void result.current.approve();
});
await waitFor(() => expect(onUpdate).toHaveBeenCalledTimes(1));
act(() => result.current.handleOpenChange(false));
await act(async () => {
updateRequest.reject(new Error(UPDATE_ALREADY_RUNNING));
await updateRequest.promise.catch(() => undefined);
});
expect(result.current.previewError).toBeNull();
expect(result.current.starting).toBe(false);
});
it("keeps a start failure separate from the update preview", async () => {
const { result } = renderHook(() =>
useAgentUpdateDialogState({
agentName: AGENT_NAME,
onPreview: vi.fn().mockResolvedValue(FIRST_PREVIEW),
onUpdate: vi.fn().mockRejectedValue(new Error(UPDATE_ALREADY_RUNNING)),
}),
);
await act(async () => {
await result.current.approve();
});
expect(result.current.previewError).toBeNull();
expect(result.current.approveError).toBe(UPDATE_ALREADY_RUNNING);
});
});
@@ -0,0 +1,94 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { AgentUpdateJob, AgentUpdatePreview } from "@/lib/api";
function errorMessage(error: unknown) {
return error instanceof Error ? error.message : String(error);
}
type UseAgentUpdateDialogStateOptions = {
agentName: string;
job?: AgentUpdateJob;
onPreview: (agentName: string) => Promise<AgentUpdatePreview>;
onUpdate: (agentName: string) => Promise<AgentUpdateJob>;
};
export function useAgentUpdateDialogState({
agentName,
job,
onPreview,
onUpdate,
}: UseAgentUpdateDialogStateOptions) {
const [open, setOpen] = useState(false);
const [preview, setPreview] = useState<AgentUpdatePreview | null>(null);
const [previewError, setPreviewError] = useState<string | null>(null);
const [approveError, setApproveError] = useState<string | null>(null);
const [loading, setLoading] = useState(false);
const [starting, setStarting] = useState(false);
const [activeJobID, setActiveJobID] = useState<string | null>(null);
const previewRequestID = useRef(0);
const activeJob = activeJobID === job?.job_id ? job : undefined;
const reset = useCallback(() => {
previewRequestID.current += 1;
setPreview(null);
setPreviewError(null);
setApproveError(null);
setLoading(false);
setStarting(false);
setActiveJobID(null);
}, []);
const loadPreview = useCallback(async () => {
const requestID = ++previewRequestID.current;
setLoading(true);
setPreview(null);
setPreviewError(null);
setApproveError(null);
try {
const nextPreview = await onPreview(agentName);
if (requestID === previewRequestID.current) setPreview(nextPreview);
} catch (error) {
if (requestID === previewRequestID.current) setPreviewError(errorMessage(error));
} finally {
if (requestID === previewRequestID.current) setLoading(false);
}
}, [agentName, onPreview]);
useEffect(() => {
if (open) void loadPreview();
}, [loadPreview, open]);
const handleOpenChange = (nextOpen: boolean) => {
setOpen(nextOpen);
if (!nextOpen) reset();
};
const approve = async () => {
const requestID = previewRequestID.current;
setStarting(true);
setApproveError(null);
try {
const nextJob = await onUpdate(agentName);
if (requestID === previewRequestID.current) setActiveJobID(nextJob.job_id);
} catch (error) {
if (requestID === previewRequestID.current) setApproveError(errorMessage(error));
} finally {
if (requestID === previewRequestID.current) setStarting(false);
}
};
return {
activeJob,
approve,
approveError,
handleOpenChange,
loading,
loadPreview,
open,
preview,
previewError,
starting,
};
}