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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions apps/desktop/src/renderer/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { useDiagnostics } from "./hooks/useDiagnostics";
import { useDiscovery } from "./hooks/useDiscovery";
import { useHelm } from "./hooks/useHelm";
import { useMutation } from "./hooks/useMutation";
import { discardPortForwards, retryPendingForwardStops, setPortForwardContext, usePendingForwardStops } from "./hooks/usePortForwards";
import { useNamespaces } from "./hooks/useNamespaces";
import { useOverview } from "./hooks/useOverview";
import { useResourceDetail } from "./hooks/useResourceDetail";
Expand Down Expand Up @@ -62,6 +63,11 @@ export default function App() {
const contexts = useContexts(core);
const { contextId } = contexts;
const [error, setError] = useState("");
const pendingForwardStops = usePendingForwardStops();
useEffect(() => {
if (core.state === "ready") void setPortForwardContext(contextId);
else discardPortForwards();
}, [contextId, core.state]);
const [kind, setKind] = useState<ResourceKind>(DEFAULT_KIND);
const namespaces = useNamespaces(contextId, contexts.contexts, setError);
const resources = useResourceList({
Expand Down Expand Up @@ -320,6 +326,7 @@ export default function App() {
setError("");
namespaces.setNamespace(target.namespace || "");
contexts.setContextChoice(target.id);
void setPortForwardContext(target.id).catch((cause) => setError(messageOf(cause)));
contexts.setContextId(target.id);
contexts.setView("workbench");
localStorage.setItem("aster.lastContext", target.id);
Expand All @@ -331,6 +338,7 @@ export default function App() {
const showContextPicker = useCallback(() => {
contexts.setContextChoice(contextId);
contexts.setContextQuery("");
void setPortForwardContext("").catch((cause) => setError(messageOf(cause)));
contexts.setContextId("");
namespaces.setNamespace("");
resources.setQuery("");
Expand Down Expand Up @@ -473,6 +481,22 @@ export default function App() {
void desktop.app.version().then(setAppVersion).catch(() => undefined);
}, []);

const forwardCleanupNotice = pendingForwardStops.length > 0 ? (
<aside className="update-notice port-forward-cleanup-notice" data-testid="port-forward-cleanup" role="status">
<div className="update-notice-body">
<p className="update-notice-title">{pendingForwardStops.some((entry) => entry.error) ? "Could not stop port forwards" : "Stopping port forwards"}</p>
{pendingForwardStops.map((entry) => (
<p className="update-notice-notes" key={entry.id}>
{entry.contextId} · {entry.namespace}/{entry.name} · localhost:{entry.localPort}
{entry.error ? ` — ${entry.error}` : " — Stopping…"}
</p>
))}
<Button size="sm" variant="outline" disabled={pendingForwardStops.every((entry) => entry.busy)}
onClick={() => void retryPendingForwardStops()}>Retry stopping</Button>
</div>
</aside>
) : null;

if (contexts.view === "settings") {
return (
<>
Expand Down Expand Up @@ -502,7 +526,7 @@ export default function App() {
if (contexts.settingsFrom === "contexts") void contexts.loadContexts();
}}
/>
{updateCard && <UpdateNotice card={updateCard} onOpenExternal={(url) => void desktop.app.openExternal(url)} />}
{forwardCleanupNotice || (updateCard && <UpdateNotice card={updateCard} onOpenExternal={(url) => void desktop.app.openExternal(url)} />)}
</>
);
}
Expand Down Expand Up @@ -548,7 +572,7 @@ export default function App() {
}}
onOpenExternal={(url) => void desktop.app.openExternal(url)}
/>
{updateCard && <UpdateNotice card={updateCard} onOpenExternal={(url) => void desktop.app.openExternal(url)} />}
{forwardCleanupNotice || (updateCard && <UpdateNotice card={updateCard} onOpenExternal={(url) => void desktop.app.openExternal(url)} />)}
</>
);
}
Expand Down Expand Up @@ -746,15 +770,15 @@ export default function App() {
</Suspense>
)}
</div>
{welcomeVisible ? (
{forwardCleanupNotice || (welcomeVisible ? (
<WelcomeCard
isMac={desktop.platform === "darwin"}
onDismiss={dismissWelcome}
onOpenExternal={(url) => void desktop.app.openExternal(url)}
/>
) : updateCard ? (
<UpdateNotice card={updateCard} onOpenExternal={(url) => void desktop.app.openExternal(url)} />
) : null}
) : null)}
<CommandPalette
open={paletteOpen}
onOpenChange={(open) => {
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src/renderer/detail/OverviewTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { useMemo, useState, type ReactNode } from "react";
import type { RelatedResource, ResourceEvent, ResourceRow } from "../../shared/types";
import { Button } from "../components/ui/button";
import { StatusDot } from "../components/ResourceTable";
import { PortForwardSection } from "./PortForwardSection";

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Unused imports. PortForwardSection and ForwardPort are imported here but never used in this file — dead wiring (or an unfinished refactor). Remove them.

import type { ForwardPort } from "./port-forward-ports";
import { formatReady } from "../lib/format";
import { formatAge, formatTimestamp } from "./resource-format";
import type { WorkloadCondition, WorkloadDetails } from "./workload-detail";
Expand Down
182 changes: 182 additions & 0 deletions apps/desktop/src/renderer/detail/PortForwardSection.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import { ArrowRightLeft, Check, Copy, LoaderCircle, Square } from "lucide-react";
import { useState } from "react";

import { Button } from "../components/ui/button";
import { forwardKey, usePortForwards } from "../hooks/usePortForwards";
import type { ForwardPort } from "./port-forward-ports";

export interface PortForwardSectionProps {
contextId: string;
namespace: string;
name: string;
kind: string;
ports: ForwardPort[];
}

/**
* Forwardable TCP ports for one resource. Each declared port row starts or
* stops a forward; a manual input covers pods listening on undeclared ports.
* Forwards live in a module-scoped store, so they survive navigation.
*/
export function PortForwardSection({ contextId, namespace, name, kind, ports }: PortForwardSectionProps) {
const { entries, start, stop, byKey } = usePortForwards(contextId);
const [manualPort, setManualPort] = useState("");
const [manualLocalPort, setManualLocalPort] = useState("");
const [localPorts, setLocalPorts] = useState<Record<number, string>>({});
const visiblePorts = [...new Map(ports.map((port) => [port.port, port])).values()];
for (const entry of entries) {
if (entry.kind === kind && entry.namespace === namespace && entry.name === name &&
!visiblePorts.some((port) => port.port === entry.podPort)) {
visiblePorts.push({ label: "Other port", port: entry.podPort, protocol: "TCP" });
}
}
function startForward(podPort: number, localValue = localPorts[podPort] ?? "") {
if (!validLocalPort(localValue)) return;
const localPort = localValue === "" ? 0 : Number(localValue);
void start({
contextId,
namespace,
name,
podPort,
kind,
localPort,
});
}

const manualValue = Number(manualPort);
const manualValid = Number.isInteger(manualValue) && manualValue >= 1 && manualValue <= 65_535 && validLocalPort(manualLocalPort);

return (
<section className="resource-detail-section port-forward-section" data-testid="port-forward-section" aria-label="Port forwarding">
<div className="resource-section-heading">
<div>
<h2>Port forwarding</h2>
<p>Connect through a local TCP port. Leave the local port empty to assign one automatically.</p>
</div>
</div>

<div className="port-forward-columns" aria-hidden="true">
<span>Container / port</span><span>Remote port</span><span>Local port</span><span />
</div>
<div className="port-forward-rows">
{visiblePorts.map((port) => {
const key = forwardKey(kind, namespace, name, port.port);
const entry = byKey(key);
return (
<div className="port-forward-row" key={key} data-testid="port-forward-row">
<span className="port-forward-label" title={port.label}>{port.label}</span>
<span className="port-forward-port">{port.port}/{port.protocol}</span>
{entry?.localPort ? (
<>
<div className="port-forward-address">
<div className="port-forward-address-line">
<span className="port-forward-local" data-testid="port-forward-local">localhost:{entry.localPort}</span>
<CopyLocalButton port={entry.localPort} />
</div>
{entry.pod ? <span className="port-forward-pod" title={entry.pod}>via {entry.pod}</span> : null}
</div>
<Button
variant="outline"
data-testid="port-forward-stop"
disabled={entry.busy}
onClick={() => void stop(key)}
>
<Square aria-hidden="true" />
Stop
</Button>
</>
) : (
<>
<input
className="port-forward-input"
inputMode="numeric"
placeholder="Auto"
value={localPorts[port.port] ?? ""}
aria-label={`Local port for ${port.label} ${port.port}`}
aria-invalid={!validLocalPort(localPorts[port.port] ?? "")}
title="Local port: 1–65535, or empty for a random port"
onChange={(event) =>
setLocalPorts((current) => ({ ...current, [port.port]: event.target.value.replace(/[^0-9]/g, "").slice(0, 5) }))
}
/>
<Button
variant="outline"
data-testid="port-forward-start"
disabled={entry?.busy || !validLocalPort(localPorts[port.port] ?? "")}
onClick={() => startForward(port.port)}
>
{entry?.busy ? <LoaderCircle className="spin" aria-hidden="true" /> : <ArrowRightLeft aria-hidden="true" />}
Forward
</Button>
</>
)}
</div>
);
})}

<form
className="port-forward-row port-forward-manual"
onSubmit={(event) => {
event.preventDefault();
if (!manualValid) return;
startForward(manualValue, manualLocalPort);
setManualPort("");
}}
>
<span className="port-forward-label">Other port</span>
<input
className="port-forward-input"
inputMode="numeric"
placeholder="8080"
value={manualPort}
aria-label="Pod port"
onChange={(event) => setManualPort(event.target.value.replace(/[^0-9]/g, ""))}
/>
<input
className="port-forward-input"
inputMode="numeric"
placeholder="Auto"
value={manualLocalPort}
aria-label="Local port for other port"
aria-invalid={!validLocalPort(manualLocalPort)}
title="Local port: 1–65535, or empty for a random port"
onChange={(event) => setManualLocalPort(event.target.value.replace(/[^0-9]/g, "").slice(0, 5))}
/>
<Button variant="outline" type="submit" disabled={!manualValid} data-testid="port-forward-manual-start">
<ArrowRightLeft aria-hidden="true" />
Forward
</Button>
</form>
</div>

<p className="port-forward-status" role="status" aria-live="polite">
{[...new Set(visiblePorts.map((port) => byKey(forwardKey(kind, namespace, name, port.port))?.error).filter(Boolean))].join(" · ")}
</p>
</section>
);
}

function validLocalPort(value: string): boolean {
return value === "" || (Number.isInteger(Number(value)) && Number(value) >= 1 && Number(value) <= 65_535);
}

function CopyLocalButton({ port }: { port: number }) {
const [copied, setCopied] = useState(false);
return (
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-label={`Copy localhost:${port}`}
title={copied ? "Copied" : "Copy local address"}
onClick={() => {
void navigator.clipboard?.writeText(`localhost:${port}`).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1200);
}).catch(() => undefined);
}}
>
{copied ? <Check aria-hidden="true" /> : <Copy aria-hidden="true" />}
</Button>
);
}
40 changes: 34 additions & 6 deletions apps/desktop/src/renderer/detail/ResourceDetailView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ import { DetailHeader } from "./DetailHeader";
import { LogViewer } from "./LogViewer";
import { MutationDiffView } from "./MutationDiffView";
import { OverviewTab, type PodsPreview } from "./OverviewTab";
import { PortForwardSection } from "./PortForwardSection";
import { extractForwardPorts } from "./port-forward-ports";
import { resourceActionsFor, type ResourceActionId } from "./resource-actions";
import { formatTimestamp } from "./resource-format";
import { HighlightedYaml } from "./yaml-highlight";
Expand All @@ -48,7 +50,7 @@ type MutationDraft = Omit<
"contextId" | "resourceKind" | "namespace" | "name"
>;

type DetailTab = "overview" | "pods" | "yaml" | "events" | "related" | "logs";
type DetailTab = "overview" | "ports" | "pods" | "yaml" | "events" | "related" | "logs";
type OperationDialog = "image" | null;

/** Static catalog entry; module-level so the pods hook sees a stable reference. */
Expand Down Expand Up @@ -175,6 +177,15 @@ export function ResourceDetailView({
});
// Live CPU/memory for a single Pod; the hook idles (no polls) for other kinds.
const isPod = row?.kind === "Pod";
// The Ports tab serves every kind whose forward the core can resolve; it
// stays visible even without declared ports (manual input covers those).
const canForward = Boolean(row && isPortForwardKind(row.kind));
// Forwardable TCP ports from the live YAML; service and workload targets
// resolve to a backing pod in the core before the SPDY dial.
const forwardPorts = useMemo(
() => (detail && row && isPortForwardKind(row.kind) ? extractForwardPorts(row.kind, detail.yaml) : []),
[detail, row],
);
const metrics = usePodMetrics(
contextId,
isPod ? row?.namespace ?? "" : "",
Expand Down Expand Up @@ -277,6 +288,7 @@ export function ResourceDetailView({
>
<TabsList className="resource-detail-tab-list" aria-label="Resource details">
<TabsTrigger value="overview">Overview</TabsTrigger>
{canForward && <TabsTrigger value="ports">Ports</TabsTrigger>}
{workload && (
<TabsTrigger value="pods">
Pods{podCount ? ` (${podCount}${pods.list.continueToken ? "+" : ""})` : ""}
Expand Down Expand Up @@ -311,8 +323,20 @@ export function ResourceDetailView({
/>
</TabsContent>

{canForward && (
<TabsContent value="ports" className="resource-detail-padded-tab">
<PortForwardSection
contextId={contextId}
namespace={row!.namespace}
name={row!.name}
kind={row!.kind}
ports={forwardPorts}
/>
</TabsContent>
)}

{workload && (
<TabsContent value="pods">
<TabsContent value="pods" className="resource-detail-padded-tab">
{details?.selectorPartial ? (
<EmptyTab
icon={<Box />}
Expand All @@ -333,7 +357,7 @@ export function ResourceDetailView({
</TabsContent>
)}

<TabsContent value="yaml">
<TabsContent value="yaml" className="resource-detail-padded-tab">
<ResourceYamlTab
key={row.uid || `${row.namespace}/${row.name}`}
kind={row.kind}
Expand All @@ -348,16 +372,16 @@ export function ResourceDetailView({
/>
</TabsContent>

<TabsContent value="events">
<TabsContent value="events" className="resource-detail-padded-tab">
<EventsView events={events} />
</TabsContent>

<TabsContent value="related">
<TabsContent value="related" className="resource-detail-padded-tab">
<RelatedView related={related} onNavigate={onNavigateRelated} />
</TabsContent>

{showLogs && (
<TabsContent value="logs">
<TabsContent value="logs" className="resource-detail-padded-tab">
<section className="resource-detail-section log-viewer-section">
<LogViewer
contextId={contextId}
Expand Down Expand Up @@ -426,6 +450,10 @@ export function ResourceDetailView({
);
}

function isPortForwardKind(kind: string): boolean {
return ["Pod", "Service", "Deployment", "StatefulSet", "DaemonSet", "ReplicaSet"].includes(kind);
}

function isWorkloadLogKind(kind: string): kind is WorkloadKind {
return kind === "Deployment" || kind === "StatefulSet" || kind === "DaemonSet" || kind === "Job";
}
Expand Down
Loading