feat(ui): make the core stack flow usable on mobile (#1327)

* feat(ui): make the core stack flow usable on mobile

Below the md breakpoint the app collapses to a single full-width column:
the stack list is full-screen, tapping a stack opens a full-screen detail
with a Health / Logs / Compose segmented control (Logs first) and a back
button, and a bottom tab bar switches Stacks, Fleet, Schedules, and
Settings. Compose is read-only on a phone with a prompt to edit on desktop.

Desktop (md and up) is unchanged: the mobile shell is gated behind a
useIsMobile hook plus max-md/md variants, and the stack-detail blocks are
shared with the desktop two-pane view so it renders identically.

Also generalizes the unsaved-changes guard so leaving a dirty editor (back,
tab bar, hamburger) prompts before discarding; adds 44px touch targets on
list rows, filter chips, and actions; makes log and shell modals full-screen
on mobile; and offsets toasts and the deploy pill above the bottom tab bar.

* fix(ui): keep mobile nav in sync when opening views from outside the bottom bar

On a phone the sidebar activity actions, the node switcher's Manage Nodes, the
profile Settings entry, and the dashboard configuration links set the active
view without flipping the mobile surface to content, so the user stayed on the
stack list and never saw the destination. Route these through the mobile-aware
navigation and settings helpers (a no-op on desktop).
This commit is contained in:
Anso
2026-06-07 01:03:13 -04:00
committed by GitHub
parent 57fe430db8
commit e8f271f5f6
26 changed files with 1696 additions and 659 deletions
@@ -1,30 +1,16 @@
import { Suspense, useRef, useEffect } from 'react';
import { Editor } from '@/lib/monacoLoader';
import {
RotateCw,
Play,
Square,
Save,
Terminal,
CloudDownload,
Pencil,
X,
MoreVertical,
Rocket,
Trash2,
ScrollText,
Undo2,
Loader2,
Check,
ChevronDown,
GitBranch,
ShieldCheck,
ArrowUpRight,
Copy,
FolderOpen,
} from 'lucide-react';
import { Button } from '../ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '../ui/card';
import { Card, CardContent, CardHeader } from '../ui/card';
import {
Tabs,
TabsList,
@@ -36,7 +22,6 @@ import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '../ui/dropdown-menu';
import {
@@ -46,15 +31,13 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Sparkline } from '../ui/sparkline';
import { springs } from '@/lib/motion';
import { cn } from '@/lib/utils';
import { copyToClipboard } from '@/lib/clipboard';
import ErrorBoundary from '../ErrorBoundary';
import TerminalComponent from '../Terminal';
import StructuredLogViewer from '../StructuredLogViewer';
import StackAnatomyPanel from '../StackAnatomyPanel';
import { StackFileExplorer } from '@/components/files/StackFileExplorer';
import { useIsMobile } from '@/hooks/use-is-mobile';
import { StackIdentityHeader, ContainersHealth, StackLogsSection } from './editor-view-blocks';
import { MobileStackDetail } from './MobileStackDetail';
import type { NotificationItem } from '../dashboard/types';
import type { Node } from '@/context/NodeContext';
import type { useAuth } from '@/context/AuthContext';
@@ -88,75 +71,6 @@ export interface ContainerStatsEntry {
history: { cpu: number[]; mem: number[]; netIn: number[]; netOut: number[] };
}
const extractUptime = (status: string | undefined): string | null => {
if (!status) return null;
const match = status.match(/^\s*Up\s+(.+?)(?:\s*\(.*\))?\s*$/i);
if (!match) return null;
return `up ${match[1].trim()}`;
};
const healthcheckLabel = (
health?: 'healthy' | 'unhealthy' | 'starting' | 'none',
): string | null => {
if (!health || health === 'none') return null;
if (health === 'healthy') return 'healthcheck passing';
if (health === 'unhealthy') return 'healthcheck failing';
return 'healthcheck starting';
};
type StackPill = {
label: string;
dotClass: string;
className: string;
pulse: boolean;
};
const getStackStatePill = (containers: ContainerInfo[]): StackPill | null => {
if (!containers || containers.length === 0) return null;
const running = containers.some(c => c.State === 'running');
if (!running) {
return {
label: 'exited',
dotClass: 'bg-destructive',
className: 'border-destructive/40 bg-destructive/10 text-destructive',
pulse: false,
};
}
const anyUnhealthy = containers.some(c => c.healthStatus === 'unhealthy');
const anyStarting = containers.some(c => c.healthStatus === 'starting');
const anyHealthy = containers.some(c => c.healthStatus === 'healthy');
if (anyUnhealthy) {
return {
label: 'running · unhealthy',
dotClass: 'bg-destructive',
className: 'border-destructive/40 bg-destructive/10 text-destructive',
pulse: true,
};
}
if (anyStarting) {
return {
label: 'running · starting',
dotClass: 'bg-warning',
className: 'border-warning/40 bg-warning/10 text-warning',
pulse: true,
};
}
if (anyHealthy) {
return {
label: 'running · healthy',
dotClass: 'bg-success',
className: 'border-success/40 bg-success/10 text-success',
pulse: true,
};
}
return {
label: 'running',
dotClass: 'bg-success',
className: 'border-success/40 bg-success/10 text-success',
pulse: true,
};
};
export interface EditorViewProps {
// Identity
stackName: string;
@@ -226,60 +140,64 @@ export interface EditorViewProps {
setGitSourceOpen: (open: boolean) => void;
setCopiedDigest: React.Dispatch<React.SetStateAction<string | null>>;
// Composed action wraps setStackToDelete + setDeleteDialogOpen
// Composed action: wraps setStackToDelete + setDeleteDialogOpen
requestDeleteStack: () => void;
// Mobile-only: back affordance in the detail header returns to the stack list.
onMobileBack?: () => void;
}
export function EditorView({
stackName,
isDarkMode,
containers,
containerStats,
containerStatsError,
content,
envContent,
envExists,
envFiles,
selectedEnvFile,
isFileLoading,
backupInfo,
gitSourcePendingMap,
notifications,
activeTab,
isEditing,
editingCompose,
logsMode,
copiedDigest,
loadingAction,
stackMisconfigScanning,
can,
isAdmin,
trivy,
activeNode,
copiedDigestTimerRef,
deployStack,
restartStack,
stopStack,
updateStack,
rollbackStack,
scanStackConfig,
enterEditMode,
requestSave,
requestSaveAndDeploy,
discardChanges,
setContent,
setEnvContent,
changeEnvFile,
openLogViewer,
openBashModal,
serviceAction,
setActiveTab,
setLogsMode,
setEditingCompose,
setGitSourceOpen,
setCopiedDigest,
requestDeleteStack,
}: EditorViewProps) {
export function EditorView(props: EditorViewProps) {
const {
stackName,
isDarkMode,
containers,
containerStats,
containerStatsError,
content,
envContent,
envExists,
envFiles,
selectedEnvFile,
isFileLoading,
backupInfo,
gitSourcePendingMap,
notifications,
activeTab,
isEditing,
editingCompose,
logsMode,
copiedDigest,
loadingAction,
stackMisconfigScanning,
can,
isAdmin,
trivy,
activeNode,
copiedDigestTimerRef,
deployStack,
restartStack,
stopStack,
updateStack,
rollbackStack,
scanStackConfig,
enterEditMode,
requestSave,
requestSaveAndDeploy,
discardChanges,
setContent,
setEnvContent,
changeEnvFile,
openLogViewer,
openBashModal,
serviceAction,
setActiveTab,
setLogsMode,
setEditingCompose,
setGitSourceOpen,
setCopiedDigest,
requestDeleteStack,
} = props;
const monacoEditorRef = useRef<import('monaco-editor').editor.IStandaloneCodeEditor | null>(null);
// Dispose the underlying Monaco model when EditorView unmounts. The
@@ -325,6 +243,14 @@ export function EditorView({
}
}, [activeTab, canRead, setActiveTab]);
// Below md, render the segmented full-screen mobile detail instead of the
// desktop two-pane grid. All hooks above run unconditionally before this
// branch so hook order stays stable across breakpoints.
const isMobile = useIsMobile();
if (isMobile) {
return <MobileStackDetail {...props} />;
}
return (
<ErrorBoundary>
<div className="grid gap-6 grid-cols-1 lg:grid-cols-2 min-h-[600px] h-[calc(100vh-160px)] max-h-[1040px]">
@@ -333,374 +259,45 @@ export function EditorView({
{/* Command Center Card (identity + health strip) */}
<Card className="rounded-xl border-muted bg-card shrink-0">
<CardHeader className="p-4 pb-2">
<div className="flex flex-col gap-3">
{/* Identity block */}
<div className="flex flex-col gap-1.5">
<div className="font-mono text-[10px] uppercase tracking-[0.22em] text-stat-subtitle">
{(activeNode?.name || 'local')} <span className="text-muted-foreground/60"></span> stacks <span className="text-muted-foreground/60"></span> {stackName}
</div>
<div className="flex items-center gap-3 flex-wrap">
<CardTitle className="font-display italic text-3xl leading-none tracking-tight">{stackName}</CardTitle>
{(() => {
const pill = getStackStatePill(safeContainers);
if (!pill) return null;
return (
<span className={`inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 ${pill.className}`}>
<span
aria-hidden="true"
className={`h-1.5 w-1.5 rounded-full ${pill.dotClass} ${pill.pulse ? 'animate-[pulse_2.4s_ease-in-out_infinite]' : ''}`}
/>
<span className="font-mono text-[10px] uppercase tracking-[0.18em]">{pill.label}</span>
</span>
);
})()}
</div>
{(() => {
const first = safeContainers[0];
if (!first?.Image) return null;
const digest = first.ImageID ? first.ImageID.replace(/^sha256:/, '').slice(0, 12) : '';
return (
<div className="flex items-center gap-1.5 font-mono text-[11px] text-stat-subtitle">
<span>image <span className="text-muted-foreground/60">·</span> <span className="text-foreground/90">{first.Image}</span></span>
{digest && first.ImageID && (
<>
<span className="text-muted-foreground/60">·</span>
<span>digest <span className="text-foreground/90">{digest}</span></span>
<button
type="button"
aria-label={copiedDigest === first.ImageID ? 'Copied' : 'Copy digest'}
onClick={() => {
const id = first.ImageID as string;
void copyToClipboard(id).then(() => {
setCopiedDigest(id);
if (copiedDigestTimerRef.current !== null) {
window.clearTimeout(copiedDigestTimerRef.current);
}
copiedDigestTimerRef.current = window.setTimeout(() => {
setCopiedDigest(prev => (prev === id ? null : prev));
copiedDigestTimerRef.current = null;
}, 1500);
}).catch(() => { /* clipboard unavailable */ });
}}
className="inline-flex h-4 w-4 items-center justify-center rounded text-stat-subtitle hover:text-foreground hover:bg-muted/60 transition-colors"
>
{copiedDigest === first.ImageID ? (
<Check className="h-3 w-3" strokeWidth={2} />
) : (
<Copy className="h-3 w-3" strokeWidth={1.5} />
)}
</button>
</>
)}
</div>
);
})()}
</div>
{/* Action Bar — deploy / delete affordances render against
their own backend permissions so a delete-only or
deploy-only persona sees exactly what they can act on. */}
{(() => {
const canDeploy = can('stack:deploy', 'stack', stackName);
const canDelete = can('stack:delete', 'stack', stackName);
const canRollback = canDeploy && backupInfo.exists;
const canScan = trivy.available && isAdmin;
const hasOverflowExtras = canRollback || canScan;
const hasOverflow = hasOverflowExtras || canDelete;
if (!canDeploy && !hasOverflow) return null;
return (
<div className="flex items-center gap-2 flex-wrap">
{canDeploy && (
<>
{isRunning ? (
<Button type="button" size="sm" data-testid="stack-deploy-button" className="rounded-lg bg-brand text-brand-foreground hover:bg-brand/90" onClick={restartStack} disabled={loadingAction !== null}>
<RotateCw className="w-4 h-4 mr-2" strokeWidth={1.5} />
{loadingAction === 'restart' ? 'Restarting...' : 'Restart'}
</Button>
) : (
<Button type="button" size="sm" data-testid="stack-deploy-button" className="rounded-lg bg-brand text-brand-foreground hover:bg-brand/90" onClick={deployStack} disabled={loadingAction !== null}>
<Play className="w-4 h-4 mr-2" strokeWidth={1.5} />
{loadingAction === 'deploy' ? 'Starting...' : 'Start'}
</Button>
)}
{isRunning && (
<Button type="button" size="sm" variant="outline" className="rounded-lg" onClick={stopStack} disabled={loadingAction !== null}>
<Square className="w-4 h-4 mr-2" strokeWidth={1.5} />
{loadingAction === 'stop' ? 'Stopping...' : 'Stop'}
</Button>
)}
<Button type="button" size="sm" variant="outline" className="rounded-lg" onClick={updateStack} disabled={loadingAction !== null}>
<CloudDownload className="w-4 h-4 mr-2" strokeWidth={1.5} />
{loadingAction === 'update' ? 'Updating...' : 'Update'}
</Button>
</>
)}
{hasOverflow && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" size="sm" variant="ghost" className="rounded-lg h-8 w-8 p-0" disabled={loadingAction !== null} aria-label="More actions">
<MoreVertical className="w-4 h-4" strokeWidth={1.5} />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
{canRollback && (
<DropdownMenuItem onClick={rollbackStack} disabled={loadingAction !== null}>
<Undo2 className="w-4 h-4 mr-2" strokeWidth={1.5} />
<div className="flex flex-col gap-0.5">
<span>{loadingAction === 'rollback' ? 'Rolling back...' : 'Rollback'}</span>
{backupInfo.timestamp && (
<span className="text-[10px] text-stat-subtitle font-mono">{new Date(backupInfo.timestamp).toLocaleString()}</span>
)}
</div>
</DropdownMenuItem>
)}
{canScan && (
<DropdownMenuItem onClick={scanStackConfig} disabled={loadingAction !== null || stackMisconfigScanning}>
{stackMisconfigScanning ? (
<Loader2 className="w-4 h-4 mr-2 animate-spin" strokeWidth={1.5} />
) : (
<ShieldCheck className="w-4 h-4 mr-2" strokeWidth={1.5} />
)}
{stackMisconfigScanning ? 'Scanning...' : 'Scan config'}
</DropdownMenuItem>
)}
{hasOverflowExtras && canDelete && <DropdownMenuSeparator />}
{canDelete && (
<DropdownMenuItem
className="text-destructive focus:text-destructive focus:bg-destructive/10"
disabled={loadingAction !== null}
onClick={requestDeleteStack}
>
<Trash2 className="w-4 h-4 mr-2" strokeWidth={1.5} />
{loadingAction === 'delete' ? 'Deleting...' : 'Delete'}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
);
})()}
</div>
<StackIdentityHeader
stackName={stackName}
activeNode={activeNode}
safeContainers={safeContainers}
isRunning={isRunning}
copiedDigest={copiedDigest}
setCopiedDigest={setCopiedDigest}
copiedDigestTimerRef={copiedDigestTimerRef}
can={can}
isAdmin={isAdmin}
trivy={trivy}
backupInfo={backupInfo}
loadingAction={loadingAction}
stackMisconfigScanning={stackMisconfigScanning}
deployStack={deployStack}
restartStack={restartStack}
stopStack={stopStack}
updateStack={updateStack}
rollbackStack={rollbackStack}
scanStackConfig={scanStackConfig}
requestDeleteStack={requestDeleteStack}
/>
</CardHeader>
<CardContent className="p-4 pt-2">
{/* Per-container health strip */}
<div className="mt-4">
<div className="flex items-center justify-between mb-3">
<h4 className="text-sm font-medium text-muted-foreground">CONTAINERS</h4>
{containerStatsError && safeContainers.length > 0 && (
<span
className="text-[10px] uppercase tracking-wider font-mono text-warning-foreground bg-warning/10 border border-warning/30 rounded-md px-2 py-0.5"
title={containerStatsError}
>
Stats unavailable
</span>
)}
</div>
{safeContainers.length === 0 ? (
<div className="text-muted-foreground text-sm">No containers running for this stack.</div>
) : (
<div className="flex flex-col gap-2">
{safeContainers.map(container => {
let mainPort: number | undefined;
let mainPortPrivate: number | undefined;
let mainPortProto: string | undefined;
if (container.Ports && container.Ports.length > 0) {
const WEB_UI_PORTS = [32400, 8989, 7878, 9696, 5055, 8080, 80, 443, 3000, 9000];
const IGNORE_PORTS = [1900, 53, 22];
let match = container.Ports.find(p => WEB_UI_PORTS.includes(p.PrivatePort));
if (!match) match = container.Ports.find(p => WEB_UI_PORTS.includes(p.PublicPort));
if (!match) match = container.Ports.find(p => !IGNORE_PORTS.includes(p.PrivatePort) && !IGNORE_PORTS.includes(p.PublicPort));
const chosen = match || container.Ports[0];
mainPort = chosen.PublicPort;
mainPortPrivate = chosen.PrivatePort;
mainPortProto = 'tcp';
}
const containerName = container?.Names?.[0]?.replace(/^\//, '') || container?.Id?.slice(0, 12) || 'container';
const isActive = container.State === 'running' || container.State === 'paused';
const health = container.healthStatus;
const uptime = isActive ? extractUptime(container.Status) : null;
const hcLabel = healthcheckLabel(health);
const stats = containerStats[container?.Id];
const history = stats?.history;
const badgeClass = health === 'unhealthy' || !isActive
? 'bg-destructive text-destructive-foreground'
: health === 'starting'
? 'bg-warning text-warning-foreground'
: 'bg-success text-success-foreground';
const badgeGlyph = health === 'unhealthy' || !isActive ? '✗' : health === 'starting' ? '…' : '✓';
const sparkStroke = health === 'unhealthy' ? 'var(--destructive)' : health === 'starting' ? 'var(--warning)' : 'var(--chart-1)';
return (
<div key={container?.Id || Math.random()} className="rounded-lg border border-card-border border-t-card-border-top bg-card shadow-card-bevel px-3 py-2.5">
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3 min-w-0 flex-1">
<div className={cn('mt-1 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold', badgeClass)}>
{badgeGlyph}
</div>
<div className="flex min-w-0 flex-col gap-0.5">
<div className="truncate font-mono text-sm text-foreground">{containerName}</div>
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 font-mono text-[11px] text-stat-subtitle">
{uptime ? <span>{uptime}</span> : <span>{(container.State || 'unknown').toLowerCase()}</span>}
{hcLabel ? <><span>·</span><span>{hcLabel}</span></> : null}
{mainPort && mainPortPrivate ? (
<>
<span>·</span>
<span>{mainPort} {mainPortPrivate}/{mainPortProto}</span>
<button
type="button"
onClick={() => {
const host = activeNode?.type === 'remote' && activeNode?.api_url
? new URL(activeNode.api_url).hostname
: window.location.hostname;
window.open(`http://${host}:${mainPort}`, '_blank');
}}
className="inline-flex items-center gap-1 text-brand hover:underline"
>
open <ArrowUpRight className="h-3 w-3" strokeWidth={1.5} />
</button>
</>
) : null}
</div>
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
size="icon"
variant="ghost"
className="h-7 w-7 rounded-md"
onClick={() => openLogViewer(container?.Id, containerName)}
disabled={!isActive}
aria-label="View logs"
>
<ScrollText className="h-3.5 w-3.5" strokeWidth={1.5} />
</Button>
{isAdmin && (
<Button
size="icon"
variant="ghost"
className="h-7 w-7 rounded-md"
onClick={() => openBashModal(container?.Id, containerName)}
disabled={!isActive}
aria-label="Open bash shell"
>
<Terminal className="h-3.5 w-3.5" strokeWidth={1.5} />
</Button>
)}
{container.Service && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 rounded-md"
aria-label="Service actions"
>
<MoreVertical className="h-3.5 w-3.5" strokeWidth={1.5} />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{isActive ? (
<>
<DropdownMenuItem onSelect={() => serviceAction('restart', container.Service!)}>
Restart service
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => serviceAction('stop', container.Service!)}>
Stop service
</DropdownMenuItem>
</>
) : (
<DropdownMenuItem onSelect={() => serviceAction('start', container.Service!)}>
Start service
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</div>
{isActive ? (
<div className="mt-2 grid grid-cols-3 gap-2">
<div className="flex items-center gap-2 rounded-md bg-background/60 px-2 py-1.5">
<div className="flex flex-col">
<span className="font-mono text-[10px] leading-3 uppercase tracking-[0.18em] text-stat-subtitle">cpu</span>
<span className="font-mono text-xs tabular-nums text-foreground">{stats?.cpu ?? '-'}</span>
</div>
<div className="ml-auto h-5 w-16">
<Sparkline points={history?.cpu ?? []} stroke={sparkStroke} fill={sparkStroke} showPeak={false} />
</div>
</div>
<div className="flex items-center gap-2 rounded-md bg-background/60 px-2 py-1.5">
<div className="flex flex-col">
<span className="font-mono text-[10px] leading-3 uppercase tracking-[0.18em] text-stat-subtitle">mem</span>
<span className="font-mono text-xs tabular-nums text-foreground">{stats?.ram ?? '-'}</span>
</div>
<div className="ml-auto h-5 w-16">
<Sparkline points={history?.mem ?? []} stroke={sparkStroke} fill={sparkStroke} showPeak={false} />
</div>
</div>
<div className="flex items-center gap-2 rounded-md bg-background/60 px-2 py-1.5">
<div className="flex flex-col">
<span className="font-mono text-[10px] leading-3 uppercase tracking-[0.18em] text-stat-subtitle">net i/o</span>
<span className="font-mono text-xs tabular-nums text-foreground">{stats?.net ?? '-'}</span>
</div>
<div className="ml-auto h-5 w-16">
<Sparkline points={history?.netIn ?? []} stroke={sparkStroke} fill={sparkStroke} showPeak={false} />
</div>
</div>
</div>
) : null}
</div>
);
})}
</div>
)}
</div>
<ContainersHealth
safeContainers={safeContainers}
containerStats={containerStats}
containerStatsError={containerStatsError}
isAdmin={isAdmin}
activeNode={activeNode}
openLogViewer={openLogViewer}
openBashModal={openBashModal}
serviceAction={serviceAction}
/>
</CardContent>
</Card>
{/* Logs Section (fills remaining left-column height) */}
<div className="flex-1 min-h-0 flex flex-col gap-2 overflow-hidden">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium text-stat-subtitle">Logs</h3>
<div className="inline-flex rounded-md border border-muted bg-muted/30 p-0.5">
<button
type="button"
onClick={() => setLogsMode('structured')}
className={cn(
'rounded px-2 py-0.5 font-mono text-[10px] uppercase tracking-wide transition-colors',
logsMode === 'structured' ? 'bg-brand/15 text-brand' : 'text-stat-subtitle hover:text-foreground',
)}
>
Structured
</button>
<button
type="button"
onClick={() => setLogsMode('raw')}
className={cn(
'rounded px-2 py-0.5 font-mono text-[10px] uppercase tracking-wide transition-colors',
logsMode === 'raw' ? 'bg-brand/15 text-brand' : 'text-stat-subtitle hover:text-foreground',
)}
>
Raw terminal
</button>
</div>
</div>
{logsMode === 'structured' ? (
<ErrorBoundary>
<StructuredLogViewer stackName={stackName} />
</ErrorBoundary>
) : (
<div className="flex-1 rounded-xl overflow-hidden border border-muted bg-black p-3 shadow-[inset_0_2px_4px_0_oklch(0_0_0/0.4)]">
<div className="h-full">
<ErrorBoundary>
<TerminalComponent stackName={stackName} />
</ErrorBoundary>
</div>
</div>
)}
</div>
<StackLogsSection stackName={stackName} logsMode={logsMode} setLogsMode={setLogsMode} />
</div>
{/* Right column: anatomy panel by default, Monaco editor when editing */}
@@ -0,0 +1,105 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import type { ReactNode } from 'react';
import { MobileStackDetail } from './MobileStackDetail';
import type { EditorViewProps } from './EditorView';
// The detail's heavy children stream logs, parse compose, and render container
// stats; stub them with markers so this test focuses on the segmented-control
// behavior (default segment + switching).
vi.mock('./editor-view-blocks', () => ({
StackIdentityHeader: () => <div>identity-header</div>,
ContainersHealth: () => <div>health-pane</div>,
StackLogsSection: () => <div>logs-pane</div>,
}));
vi.mock('../StackAnatomyPanel', () => ({ default: () => <div>compose-pane</div> }));
vi.mock('../ErrorBoundary', () => ({ default: ({ children }: { children: ReactNode }) => <>{children}</> }));
function makeProps(over: Partial<EditorViewProps> = {}): EditorViewProps {
return {
stackName: 'web',
activeNode: null,
containers: [],
containerStats: {},
containerStatsError: null,
content: '',
envContent: '',
selectedEnvFile: '',
gitSourcePendingMap: {},
notifications: [],
copiedDigest: null,
loadingAction: null,
stackMisconfigScanning: false,
can: () => true,
isAdmin: false,
trivy: { available: false },
backupInfo: { exists: false, timestamp: null },
logsMode: 'structured',
copiedDigestTimerRef: { current: null },
deployStack: vi.fn(),
restartStack: vi.fn(),
stopStack: vi.fn(),
updateStack: vi.fn(),
rollbackStack: vi.fn(),
scanStackConfig: vi.fn(),
openLogViewer: vi.fn(),
openBashModal: vi.fn(),
serviceAction: vi.fn(),
setLogsMode: vi.fn(),
setGitSourceOpen: vi.fn(),
setCopiedDigest: vi.fn(),
requestDeleteStack: vi.fn(),
onMobileBack: vi.fn(),
...over,
} as unknown as EditorViewProps;
}
describe('MobileStackDetail', () => {
it('defaults to the Logs segment', () => {
render(<MobileStackDetail {...makeProps()} />);
expect(screen.getByText('logs-pane')).toBeInTheDocument();
expect(screen.queryByText('health-pane')).not.toBeInTheDocument();
expect(screen.queryByText('compose-pane')).not.toBeInTheDocument();
expect(screen.getByText('identity-header')).toBeInTheDocument();
});
it('switches to Health and Compose segments', () => {
render(<MobileStackDetail {...makeProps()} />);
fireEvent.click(screen.getByRole('tab', { name: 'Health' }));
expect(screen.getByText('health-pane')).toBeInTheDocument();
expect(screen.queryByText('logs-pane')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: 'Compose' }));
expect(screen.getByText('compose-pane')).toBeInTheDocument();
});
it('marks the active segment with aria-selected and round-trips back to Logs', () => {
render(<MobileStackDetail {...makeProps()} />);
expect(screen.getByRole('tab', { name: 'Logs' })).toHaveAttribute('aria-selected', 'true');
fireEvent.click(screen.getByRole('tab', { name: 'Health' }));
expect(screen.getByRole('tab', { name: 'Health' })).toHaveAttribute('aria-selected', 'true');
expect(screen.getByRole('tab', { name: 'Logs' })).toHaveAttribute('aria-selected', 'false');
fireEvent.click(screen.getByRole('tab', { name: 'Logs' }));
expect(screen.getByRole('tab', { name: 'Logs' })).toHaveAttribute('aria-selected', 'true');
expect(screen.getByText('logs-pane')).toBeInTheDocument();
});
it('invokes the back handler', () => {
const onMobileBack = vi.fn();
render(<MobileStackDetail {...makeProps({ onMobileBack })} />);
fireEvent.click(screen.getByRole('button', { name: 'Back to stacks' }));
expect(onMobileBack).toHaveBeenCalledTimes(1);
});
it('shows the edit-on-desktop nudge in Compose when the user can edit', () => {
render(<MobileStackDetail {...makeProps({ can: () => true })} />);
fireEvent.click(screen.getByRole('tab', { name: 'Compose' }));
expect(screen.getByText(/Editing compose is available on a larger screen/i)).toBeInTheDocument();
});
it('hides the nudge when the user cannot edit', () => {
render(<MobileStackDetail {...makeProps({ can: () => false })} />);
fireEvent.click(screen.getByRole('tab', { name: 'Compose' }));
expect(screen.queryByText(/Editing compose is available/i)).not.toBeInTheDocument();
});
});
@@ -0,0 +1,180 @@
import { useState } from 'react';
import { ChevronLeft } from 'lucide-react';
import { cn } from '@/lib/utils';
import ErrorBoundary from '../ErrorBoundary';
import StackAnatomyPanel from '../StackAnatomyPanel';
import { StackIdentityHeader, ContainersHealth, StackLogsSection } from './editor-view-blocks';
import type { EditorViewProps } from './EditorView';
const SEGMENTS = [
{ id: 'health', label: 'Health' },
{ id: 'logs', label: 'Logs' },
{ id: 'compose', label: 'Compose' },
] as const;
type Segment = (typeof SEGMENTS)[number]['id'];
// Full-screen stack detail for the mobile shell (below md). The desktop
// two-pane grid does not fit a phone, so the same identity header, container
// health, logs, and anatomy are reorganized into a tracked-mono segmented
// control. Logs is the default segment (first-read, without copying Dockge's
// layout). Compose is read-only on mobile: full file editing stays on desktop.
export function MobileStackDetail(props: EditorViewProps) {
const {
stackName,
activeNode,
containers,
containerStats,
containerStatsError,
content,
envContent,
selectedEnvFile,
gitSourcePendingMap,
notifications,
copiedDigest,
loadingAction,
stackMisconfigScanning,
can,
isAdmin,
trivy,
backupInfo,
logsMode,
copiedDigestTimerRef,
deployStack,
restartStack,
stopStack,
updateStack,
rollbackStack,
scanStackConfig,
openLogViewer,
openBashModal,
serviceAction,
setLogsMode,
setGitSourceOpen,
setCopiedDigest,
requestDeleteStack,
onMobileBack,
} = props;
const [segment, setSegment] = useState<Segment>('logs');
const safeContainers = containers || [];
const isRunning = safeContainers.some(c => c.State === 'running');
const canEditStack = can('stack:edit', 'stack', stackName);
return (
<ErrorBoundary>
<div className="flex h-full min-h-0 flex-col">
{/* Detail header: back to list + identity + action bar */}
<div className="shrink-0 border-b border-hairline px-4 pb-3 pt-3">
<button
type="button"
onClick={onMobileBack}
aria-label="Back to stacks"
className="mb-1 inline-flex min-h-11 items-center gap-1 pr-3 font-mono text-xs text-brand"
>
<ChevronLeft className="h-4 w-4" strokeWidth={1.6} />
Stacks
</button>
<StackIdentityHeader
stackName={stackName}
activeNode={activeNode}
safeContainers={safeContainers}
isRunning={isRunning}
copiedDigest={copiedDigest}
setCopiedDigest={setCopiedDigest}
copiedDigestTimerRef={copiedDigestTimerRef}
can={can}
isAdmin={isAdmin}
trivy={trivy}
backupInfo={backupInfo}
loadingAction={loadingAction}
stackMisconfigScanning={stackMisconfigScanning}
deployStack={deployStack}
restartStack={restartStack}
stopStack={stopStack}
updateStack={updateStack}
rollbackStack={rollbackStack}
scanStackConfig={scanStackConfig}
requestDeleteStack={requestDeleteStack}
/>
</div>
{/* Segmented control: Health · Logs · Compose */}
<div className="shrink-0 px-4 pt-3">
<div
role="tablist"
aria-label="Stack detail sections"
className="flex gap-1 rounded-lg border border-card-border bg-well p-1 shadow-[var(--shadow-well)]"
>
{SEGMENTS.map(seg => {
const on = seg.id === segment;
return (
<button
key={seg.id}
type="button"
role="tab"
aria-selected={on}
onClick={() => setSegment(seg.id)}
className={cn(
'flex-1 rounded-md py-2 font-mono text-[11px] uppercase tracking-[0.14em] transition-colors',
on
? 'bg-card text-stat-value shadow-card-bevel'
: 'text-stat-subtitle hover:text-foreground',
)}
>
{seg.label}
</button>
);
})}
</div>
</div>
{/* Active segment */}
<div className="flex flex-1 min-h-0 flex-col overflow-hidden p-4">
{segment === 'health' && (
<div className="min-h-0 flex-1 overflow-y-auto">
<ContainersHealth
safeContainers={safeContainers}
containerStats={containerStats}
containerStatsError={containerStatsError}
isAdmin={isAdmin}
activeNode={activeNode}
openLogViewer={openLogViewer}
openBashModal={openBashModal}
serviceAction={serviceAction}
/>
</div>
)}
{segment === 'logs' && (
<StackLogsSection stackName={stackName} logsMode={logsMode} setLogsMode={setLogsMode} />
)}
{segment === 'compose' && (
<div className="flex min-h-0 flex-1 flex-col gap-3">
<div className="min-h-0 flex-1">
<StackAnatomyPanel
stackName={stackName}
content={content}
envContent={envContent}
selectedEnvFile={selectedEnvFile}
gitSourcePending={Boolean(gitSourcePendingMap[stackName])}
onEditCompose={() => {}}
onOpenGitSource={() => setGitSourceOpen(true)}
onApplyUpdate={() => { void updateStack(); }}
applying={loadingAction === 'update'}
canEdit={false}
notifications={notifications}
/>
</div>
{canEditStack && (
<div className="shrink-0 rounded-lg border border-card-border bg-card px-3 py-2.5 font-mono text-[11px] text-stat-subtitle">
Editing compose is available on a larger screen. Open this stack on desktop to edit the file.
</div>
)}
</div>
)}
</div>
</div>
</ErrorBoundary>
);
}
@@ -50,7 +50,7 @@ export function ShellOverlays({
}: ShellOverlaysProps) {
const {
deleteDialogOpen, closeDeleteDialog, stackToDelete,
pendingUnsavedLoad,
pendingUnsavedLoad, pendingLeaveAction,
bashModalOpen, selectedContainer,
logViewerOpen, logContainer,
stackMonitor, closeStackMonitor,
@@ -69,7 +69,7 @@ export function ShellOverlays({
/>
<UnsavedChangesDialog
open={!!pendingUnsavedLoad}
open={!!pendingUnsavedLoad || !!pendingLeaveAction}
onCancel={stackActions.cancelPendingUnsavedLoad}
onConfirm={stackActions.discardAndLoadPending}
/>
@@ -0,0 +1,557 @@
// Shared building blocks for the stack detail view. Extracted from EditorView so
// the desktop two-pane layout and the mobile segmented layout render the exact
// same identity header, container health list, and logs pane from one source.
import {
RotateCw,
Play,
Square,
Terminal,
MoreVertical,
Trash2,
ScrollText,
Undo2,
Loader2,
Check,
ShieldCheck,
ArrowUpRight,
Copy,
CloudDownload,
} from 'lucide-react';
import { Button } from '../ui/button';
import { CardTitle } from '../ui/card';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '../ui/dropdown-menu';
import { Sparkline } from '../ui/sparkline';
import { cn } from '@/lib/utils';
import { copyToClipboard } from '@/lib/clipboard';
import ErrorBoundary from '../ErrorBoundary';
import TerminalComponent from '../Terminal';
import StructuredLogViewer from '../StructuredLogViewer';
import type { Node } from '@/context/NodeContext';
import type { useAuth } from '@/context/AuthContext';
import type { ContainerInfo, ContainerStatsEntry, StackAction } from './EditorView';
const extractUptime = (status: string | undefined): string | null => {
if (!status) return null;
const match = status.match(/^\s*Up\s+(.+?)(?:\s*\(.*\))?\s*$/i);
if (!match) return null;
return `up ${match[1].trim()}`;
};
const healthcheckLabel = (
health?: 'healthy' | 'unhealthy' | 'starting' | 'none',
): string | null => {
if (!health || health === 'none') return null;
if (health === 'healthy') return 'healthcheck passing';
if (health === 'unhealthy') return 'healthcheck failing';
return 'healthcheck starting';
};
type StackPill = {
label: string;
dotClass: string;
className: string;
pulse: boolean;
};
const getStackStatePill = (containers: ContainerInfo[]): StackPill | null => {
if (!containers || containers.length === 0) return null;
const running = containers.some(c => c.State === 'running');
if (!running) {
return {
label: 'exited',
dotClass: 'bg-destructive',
className: 'border-destructive/40 bg-destructive/10 text-destructive',
pulse: false,
};
}
const anyUnhealthy = containers.some(c => c.healthStatus === 'unhealthy');
const anyStarting = containers.some(c => c.healthStatus === 'starting');
const anyHealthy = containers.some(c => c.healthStatus === 'healthy');
if (anyUnhealthy) {
return {
label: 'running · unhealthy',
dotClass: 'bg-destructive',
className: 'border-destructive/40 bg-destructive/10 text-destructive',
pulse: true,
};
}
if (anyStarting) {
return {
label: 'running · starting',
dotClass: 'bg-warning',
className: 'border-warning/40 bg-warning/10 text-warning',
pulse: true,
};
}
if (anyHealthy) {
return {
label: 'running · healthy',
dotClass: 'bg-success',
className: 'border-success/40 bg-success/10 text-success',
pulse: true,
};
}
return {
label: 'running',
dotClass: 'bg-success',
className: 'border-success/40 bg-success/10 text-success',
pulse: true,
};
};
export interface StackIdentityHeaderProps {
stackName: string;
activeNode: Node | null;
safeContainers: ContainerInfo[];
isRunning: boolean;
copiedDigest: string | null;
setCopiedDigest: React.Dispatch<React.SetStateAction<string | null>>;
copiedDigestTimerRef: React.MutableRefObject<number | null>;
can: ReturnType<typeof useAuth>['can'];
isAdmin: boolean;
trivy: { available: boolean };
backupInfo: { exists: boolean; timestamp: number | null };
loadingAction: StackAction | null;
stackMisconfigScanning: boolean;
deployStack: (e: React.MouseEvent) => Promise<void>;
restartStack: (e: React.MouseEvent) => Promise<void>;
stopStack: (e: React.MouseEvent) => Promise<void>;
updateStack: (e?: React.MouseEvent) => Promise<void>;
rollbackStack: () => Promise<void>;
scanStackConfig: () => Promise<void>;
requestDeleteStack: () => void;
}
// Breadcrumb + serif title + state pill + image ref + action bar. The action
// buttons grow to a 44px touch target below md without changing desktop.
export function StackIdentityHeader({
stackName,
activeNode,
safeContainers,
isRunning,
copiedDigest,
setCopiedDigest,
copiedDigestTimerRef,
can,
isAdmin,
trivy,
backupInfo,
loadingAction,
stackMisconfigScanning,
deployStack,
restartStack,
stopStack,
updateStack,
rollbackStack,
scanStackConfig,
requestDeleteStack,
}: StackIdentityHeaderProps) {
return (
<div className="flex flex-col gap-3">
{/* Identity block */}
<div className="flex flex-col gap-1.5">
<div className="font-mono text-[10px] uppercase tracking-[0.22em] text-stat-subtitle">
{(activeNode?.name || 'local')} <span className="text-muted-foreground/60"></span> stacks <span className="text-muted-foreground/60"></span> {stackName}
</div>
<div className="flex items-center gap-3 flex-wrap">
<CardTitle className="font-display italic text-3xl leading-none tracking-tight">{stackName}</CardTitle>
{(() => {
const pill = getStackStatePill(safeContainers);
if (!pill) return null;
return (
<span className={`inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 ${pill.className}`}>
<span
aria-hidden="true"
className={`h-1.5 w-1.5 rounded-full ${pill.dotClass} ${pill.pulse ? 'animate-[pulse_2.4s_ease-in-out_infinite]' : ''}`}
/>
<span className="font-mono text-[10px] uppercase tracking-[0.18em]">{pill.label}</span>
</span>
);
})()}
</div>
{(() => {
const first = safeContainers[0];
if (!first?.Image) return null;
const digest = first.ImageID ? first.ImageID.replace(/^sha256:/, '').slice(0, 12) : '';
return (
<div className="flex items-center gap-1.5 font-mono text-[11px] text-stat-subtitle">
<span>image <span className="text-muted-foreground/60">·</span> <span className="text-foreground/90">{first.Image}</span></span>
{digest && first.ImageID && (
<>
<span className="text-muted-foreground/60">·</span>
<span>digest <span className="text-foreground/90">{digest}</span></span>
<button
type="button"
aria-label={copiedDigest === first.ImageID ? 'Copied' : 'Copy digest'}
onClick={() => {
const id = first.ImageID as string;
void copyToClipboard(id).then(() => {
setCopiedDigest(id);
if (copiedDigestTimerRef.current !== null) {
window.clearTimeout(copiedDigestTimerRef.current);
}
copiedDigestTimerRef.current = window.setTimeout(() => {
setCopiedDigest(prev => (prev === id ? null : prev));
copiedDigestTimerRef.current = null;
}, 1500);
}).catch(() => { /* clipboard unavailable */ });
}}
className="inline-flex h-4 w-4 items-center justify-center rounded text-stat-subtitle hover:text-foreground hover:bg-muted/60 transition-colors"
>
{copiedDigest === first.ImageID ? (
<Check className="h-3 w-3" strokeWidth={2} />
) : (
<Copy className="h-3 w-3" strokeWidth={1.5} />
)}
</button>
</>
)}
</div>
);
})()}
</div>
{/* Action Bar: deploy and delete affordances render against their own
backend permissions so a delete-only or deploy-only persona sees
exactly what they can act on. */}
{(() => {
const canDeploy = can('stack:deploy', 'stack', stackName);
const canDelete = can('stack:delete', 'stack', stackName);
const canRollback = canDeploy && backupInfo.exists;
const canScan = trivy.available && isAdmin;
const hasOverflowExtras = canRollback || canScan;
const hasOverflow = hasOverflowExtras || canDelete;
if (!canDeploy && !hasOverflow) return null;
return (
<div className="flex items-center gap-2 flex-wrap">
{canDeploy && (
<>
{isRunning ? (
<Button type="button" size="sm" data-testid="stack-deploy-button" className="rounded-lg max-md:h-11 bg-brand text-brand-foreground hover:bg-brand/90" onClick={restartStack} disabled={loadingAction !== null}>
<RotateCw className="w-4 h-4 mr-2" strokeWidth={1.5} />
{loadingAction === 'restart' ? 'Restarting...' : 'Restart'}
</Button>
) : (
<Button type="button" size="sm" data-testid="stack-deploy-button" className="rounded-lg max-md:h-11 bg-brand text-brand-foreground hover:bg-brand/90" onClick={deployStack} disabled={loadingAction !== null}>
<Play className="w-4 h-4 mr-2" strokeWidth={1.5} />
{loadingAction === 'deploy' ? 'Starting...' : 'Start'}
</Button>
)}
{isRunning && (
<Button type="button" size="sm" variant="outline" className="rounded-lg max-md:h-11" onClick={stopStack} disabled={loadingAction !== null}>
<Square className="w-4 h-4 mr-2" strokeWidth={1.5} />
{loadingAction === 'stop' ? 'Stopping...' : 'Stop'}
</Button>
)}
<Button type="button" size="sm" variant="outline" className="rounded-lg max-md:h-11" onClick={updateStack} disabled={loadingAction !== null}>
<CloudDownload className="w-4 h-4 mr-2" strokeWidth={1.5} />
{loadingAction === 'update' ? 'Updating...' : 'Update'}
</Button>
</>
)}
{hasOverflow && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" size="sm" variant="ghost" className="rounded-lg h-8 w-8 p-0 max-md:h-11 max-md:w-11" disabled={loadingAction !== null} aria-label="More actions">
<MoreVertical className="w-4 h-4" strokeWidth={1.5} />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48">
{canRollback && (
<DropdownMenuItem onClick={rollbackStack} disabled={loadingAction !== null}>
<Undo2 className="w-4 h-4 mr-2" strokeWidth={1.5} />
<div className="flex flex-col gap-0.5">
<span>{loadingAction === 'rollback' ? 'Rolling back...' : 'Rollback'}</span>
{backupInfo.timestamp && (
<span className="text-[10px] text-stat-subtitle font-mono">{new Date(backupInfo.timestamp).toLocaleString()}</span>
)}
</div>
</DropdownMenuItem>
)}
{canScan && (
<DropdownMenuItem onClick={scanStackConfig} disabled={loadingAction !== null || stackMisconfigScanning}>
{stackMisconfigScanning ? (
<Loader2 className="w-4 h-4 mr-2 animate-spin" strokeWidth={1.5} />
) : (
<ShieldCheck className="w-4 h-4 mr-2" strokeWidth={1.5} />
)}
{stackMisconfigScanning ? 'Scanning...' : 'Scan config'}
</DropdownMenuItem>
)}
{hasOverflowExtras && canDelete && <DropdownMenuSeparator />}
{canDelete && (
<DropdownMenuItem
className="text-destructive focus:text-destructive focus:bg-destructive/10"
disabled={loadingAction !== null}
onClick={requestDeleteStack}
>
<Trash2 className="w-4 h-4 mr-2" strokeWidth={1.5} />
{loadingAction === 'delete' ? 'Deleting...' : 'Delete'}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
);
})()}
</div>
);
}
export interface ContainersHealthProps {
safeContainers: ContainerInfo[];
containerStats: Record<string, ContainerStatsEntry>;
containerStatsError: string | null;
isAdmin: boolean;
activeNode: Node | null;
openLogViewer: (containerId: string, containerName: string) => void;
openBashModal: (containerId: string, containerName: string) => void;
serviceAction: (action: 'start' | 'stop' | 'restart', serviceName: string) => Promise<void>;
}
// Per-container health strip: status badge, uptime, ports, and CPU/Mem/Net
// sparklines. Row action buttons grow to a 44px touch target below md.
export function ContainersHealth({
safeContainers,
containerStats,
containerStatsError,
isAdmin,
activeNode,
openLogViewer,
openBashModal,
serviceAction,
}: ContainersHealthProps) {
return (
<div className="mt-4">
<div className="flex items-center justify-between mb-3">
<h4 className="text-sm font-medium text-muted-foreground">CONTAINERS</h4>
{containerStatsError && safeContainers.length > 0 && (
<span
className="text-[10px] uppercase tracking-wider font-mono text-warning-foreground bg-warning/10 border border-warning/30 rounded-md px-2 py-0.5"
title={containerStatsError}
>
Stats unavailable
</span>
)}
</div>
{safeContainers.length === 0 ? (
<div className="text-muted-foreground text-sm">No containers running for this stack.</div>
) : (
<div className="flex flex-col gap-2">
{safeContainers.map(container => {
let mainPort: number | undefined;
let mainPortPrivate: number | undefined;
let mainPortProto: string | undefined;
if (container.Ports && container.Ports.length > 0) {
const WEB_UI_PORTS = [32400, 8989, 7878, 9696, 5055, 8080, 80, 443, 3000, 9000];
const IGNORE_PORTS = [1900, 53, 22];
let match = container.Ports.find(p => WEB_UI_PORTS.includes(p.PrivatePort));
if (!match) match = container.Ports.find(p => WEB_UI_PORTS.includes(p.PublicPort));
if (!match) match = container.Ports.find(p => !IGNORE_PORTS.includes(p.PrivatePort) && !IGNORE_PORTS.includes(p.PublicPort));
const chosen = match || container.Ports[0];
mainPort = chosen.PublicPort;
mainPortPrivate = chosen.PrivatePort;
mainPortProto = 'tcp';
}
const containerName = container?.Names?.[0]?.replace(/^\//, '') || container?.Id?.slice(0, 12) || 'container';
const isActive = container.State === 'running' || container.State === 'paused';
const health = container.healthStatus;
const uptime = isActive ? extractUptime(container.Status) : null;
const hcLabel = healthcheckLabel(health);
const stats = containerStats[container?.Id];
const history = stats?.history;
const badgeClass = health === 'unhealthy' || !isActive
? 'bg-destructive text-destructive-foreground'
: health === 'starting'
? 'bg-warning text-warning-foreground'
: 'bg-success text-success-foreground';
const badgeGlyph = health === 'unhealthy' || !isActive ? '✗' : health === 'starting' ? '…' : '✓';
const sparkStroke = health === 'unhealthy' ? 'var(--destructive)' : health === 'starting' ? 'var(--warning)' : 'var(--chart-1)';
return (
<div key={container?.Id || Math.random()} className="rounded-lg border border-card-border border-t-card-border-top bg-card shadow-card-bevel px-3 py-2.5">
<div className="flex items-start justify-between gap-4">
<div className="flex items-start gap-3 min-w-0 flex-1">
<div className={cn('mt-1 inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold', badgeClass)}>
{badgeGlyph}
</div>
<div className="flex min-w-0 flex-col gap-0.5">
<div className="truncate font-mono text-sm text-foreground">{containerName}</div>
<div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 font-mono text-[11px] text-stat-subtitle">
{uptime ? <span>{uptime}</span> : <span>{(container.State || 'unknown').toLowerCase()}</span>}
{hcLabel ? <><span>·</span><span>{hcLabel}</span></> : null}
{mainPort && mainPortPrivate ? (
<>
<span>·</span>
<span>{mainPort} {mainPortPrivate}/{mainPortProto}</span>
<button
type="button"
onClick={() => {
const host = activeNode?.type === 'remote' && activeNode?.api_url
? new URL(activeNode.api_url).hostname
: window.location.hostname;
window.open(`http://${host}:${mainPort}`, '_blank');
}}
className="inline-flex items-center gap-1 text-brand hover:underline"
>
open <ArrowUpRight className="h-3 w-3" strokeWidth={1.5} />
</button>
</>
) : null}
</div>
</div>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
size="icon"
variant="ghost"
className="h-7 w-7 rounded-md max-md:h-11 max-md:w-11"
onClick={() => openLogViewer(container?.Id, containerName)}
disabled={!isActive}
aria-label="View logs"
>
<ScrollText className="h-3.5 w-3.5" strokeWidth={1.5} />
</Button>
{isAdmin && (
<Button
size="icon"
variant="ghost"
className="h-7 w-7 rounded-md max-md:h-11 max-md:w-11"
onClick={() => openBashModal(container?.Id, containerName)}
disabled={!isActive}
aria-label="Open bash shell"
>
<Terminal className="h-3.5 w-3.5" strokeWidth={1.5} />
</Button>
)}
{container.Service && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
size="icon"
variant="ghost"
className="h-7 w-7 rounded-md max-md:h-11 max-md:w-11"
aria-label="Service actions"
>
<MoreVertical className="h-3.5 w-3.5" strokeWidth={1.5} />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{isActive ? (
<>
<DropdownMenuItem onSelect={() => serviceAction('restart', container.Service!)}>
Restart service
</DropdownMenuItem>
<DropdownMenuItem onSelect={() => serviceAction('stop', container.Service!)}>
Stop service
</DropdownMenuItem>
</>
) : (
<DropdownMenuItem onSelect={() => serviceAction('start', container.Service!)}>
Start service
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
</div>
{isActive ? (
<div className="mt-2 grid grid-cols-3 gap-2">
<div className="flex items-center gap-2 rounded-md bg-background/60 px-2 py-1.5">
<div className="flex flex-col">
<span className="font-mono text-[10px] leading-3 uppercase tracking-[0.18em] text-stat-subtitle">cpu</span>
<span className="font-mono text-xs tabular-nums text-foreground">{stats?.cpu ?? '-'}</span>
</div>
<div className="ml-auto h-5 w-16">
<Sparkline points={history?.cpu ?? []} stroke={sparkStroke} fill={sparkStroke} showPeak={false} />
</div>
</div>
<div className="flex items-center gap-2 rounded-md bg-background/60 px-2 py-1.5">
<div className="flex flex-col">
<span className="font-mono text-[10px] leading-3 uppercase tracking-[0.18em] text-stat-subtitle">mem</span>
<span className="font-mono text-xs tabular-nums text-foreground">{stats?.ram ?? '-'}</span>
</div>
<div className="ml-auto h-5 w-16">
<Sparkline points={history?.mem ?? []} stroke={sparkStroke} fill={sparkStroke} showPeak={false} />
</div>
</div>
<div className="flex items-center gap-2 rounded-md bg-background/60 px-2 py-1.5">
<div className="flex flex-col">
<span className="font-mono text-[10px] leading-3 uppercase tracking-[0.18em] text-stat-subtitle">net i/o</span>
<span className="font-mono text-xs tabular-nums text-foreground">{stats?.net ?? '-'}</span>
</div>
<div className="ml-auto h-5 w-16">
<Sparkline points={history?.netIn ?? []} stroke={sparkStroke} fill={sparkStroke} showPeak={false} />
</div>
</div>
</div>
) : null}
</div>
);
})}
</div>
)}
</div>
);
}
export interface StackLogsSectionProps {
stackName: string;
logsMode: 'structured' | 'raw';
setLogsMode: (mode: 'structured' | 'raw') => void;
}
// Logs pane: structured / raw-terminal toggle + the live viewer.
export function StackLogsSection({ stackName, logsMode, setLogsMode }: StackLogsSectionProps) {
return (
<div className="flex-1 min-h-0 flex flex-col gap-2 overflow-hidden">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium text-stat-subtitle">Logs</h3>
<div className="inline-flex rounded-md border border-muted bg-muted/30 p-0.5">
<button
type="button"
onClick={() => setLogsMode('structured')}
className={cn(
'rounded px-2 py-0.5 font-mono text-[10px] uppercase tracking-wide transition-colors',
logsMode === 'structured' ? 'bg-brand/15 text-brand' : 'text-stat-subtitle hover:text-foreground',
)}
>
Structured
</button>
<button
type="button"
onClick={() => setLogsMode('raw')}
className={cn(
'rounded px-2 py-0.5 font-mono text-[10px] uppercase tracking-wide transition-colors',
logsMode === 'raw' ? 'bg-brand/15 text-brand' : 'text-stat-subtitle hover:text-foreground',
)}
>
Raw terminal
</button>
</div>
</div>
{logsMode === 'structured' ? (
<ErrorBoundary>
<StructuredLogViewer stackName={stackName} />
</ErrorBoundary>
) : (
<div className="flex-1 rounded-xl overflow-hidden border border-muted bg-black p-3 shadow-[inset_0_2px_4px_0_oklch(0_0_0/0.4)]">
<div className="h-full">
<ErrorBoundary>
<TerminalComponent stackName={stackName} />
</ErrorBoundary>
</div>
</div>
)}
</div>
);
}
@@ -36,6 +36,11 @@ export function useOverlayState() {
const [pendingUnsavedLoad, setPendingUnsavedLoad] = useState<string | null>(null);
const [pendingUnsavedNode, setPendingUnsavedNode] = useState<Node | null>(null);
// A deferred "leave the dirty editor" navigation (back to the list, Home, a
// bottom-tab / hamburger destination). Wrapped in an object so the state
// setter is not mistaken for a functional update. Runs after the user
// confirms the unsaved-changes dialog. See useStackActions.attemptLeaveEditor.
const [pendingLeaveAction, setPendingLeaveAction] = useState<{ run: () => void } | null>(null);
const [bashModalOpen, setBashModalOpen] = useState(false);
const [selectedContainer, setSelectedContainer] = useState<Container | null>(null);
@@ -93,6 +98,7 @@ export function useOverlayState() {
deleteDialogOpen, stackToDelete, openDeleteDialog, closeDeleteDialog,
pendingUnsavedLoad, setPendingUnsavedLoad,
pendingUnsavedNode, setPendingUnsavedNode,
pendingLeaveAction, setPendingLeaveAction,
bashModalOpen, selectedContainer, openBashModal, closeBashModal,
logViewerOpen, logContainer, openLogViewer, closeLogViewer,
stackMonitor, openAlertSheet, openAutoHeal, closeStackMonitor,
@@ -70,8 +70,10 @@ function makeOverlay(over: Partial<OverlayState> = {}): OverlayState {
return {
setPendingUnsavedLoad: vi.fn(),
setPendingUnsavedNode: vi.fn(),
setPendingLeaveAction: vi.fn(),
pendingUnsavedLoad: null,
pendingUnsavedNode: null,
pendingLeaveAction: null,
policyBlock: null,
setPolicyBlock: vi.fn(),
setPolicyBypassing: vi.fn(),
@@ -300,3 +302,52 @@ describe('useStackActions.bypassPolicyAndRetry', () => {
expect(apiFetch).not.toHaveBeenCalled();
});
});
describe('useStackActions.attemptLeaveEditor (mobile back / nav guard)', () => {
beforeEach(() => {
vi.mocked(apiFetch).mockReset();
});
it('stashes the navigation when the editor is dirty instead of running it', () => {
const perform = vi.fn();
// Default fixture: content !== originalContent and a stack is selected → dirty.
const { result, overlayState } = setup();
result.current.attemptLeaveEditor(perform);
expect(perform).not.toHaveBeenCalled();
expect(overlayState.setPendingLeaveAction).toHaveBeenCalledWith({ run: perform });
});
it('runs the navigation immediately when the editor is clean', () => {
const perform = vi.fn();
const { result, overlayState } = setup({
editorState: { content: 'same', originalContent: 'same' },
});
result.current.attemptLeaveEditor(perform);
expect(perform).toHaveBeenCalledTimes(1);
expect(overlayState.setPendingLeaveAction).not.toHaveBeenCalled();
});
it('runs the stashed leave action and clears it on discardAndLoadPending', () => {
const run = vi.fn();
const { result, overlayState, editorState } = setup({ overlay: { pendingLeaveAction: { run } } });
result.current.discardAndLoadPending();
expect(run).toHaveBeenCalledTimes(1);
expect(overlayState.setPendingLeaveAction).toHaveBeenCalledWith(null);
expect(editorState.setContent).toHaveBeenCalledWith(editorState.originalContent);
});
it('gives a stashed leave action precedence over a coexisting pending load', () => {
const run = vi.fn();
const { result } = setup({ overlay: { pendingLeaveAction: { run }, pendingUnsavedLoad: 'other.yml' } });
result.current.discardAndLoadPending();
expect(run).toHaveBeenCalledTimes(1);
// The leave branch returns before the load branch, so no stack fetch fires.
expect(apiFetch).not.toHaveBeenCalled();
});
it('clears a stashed leave action on cancel', () => {
const { result, overlayState } = setup({ overlay: { pendingLeaveAction: { run: vi.fn() } } });
result.current.cancelPendingUnsavedLoad();
expect(overlayState.setPendingLeaveAction).toHaveBeenCalledWith(null);
});
});
@@ -341,6 +341,10 @@ export function useStackActions(options: UseStackActionsOptions) {
} catch (error) {
if (isAbortError(error) || signal.aborted) return;
console.error('Failed to load file:', error);
// Surface the failure so a tap that cannot load (offline, dead remote
// node, 5xx) is not a silent no-op, especially on mobile where the row
// tap optimistically opens the detail surface.
toast.error(`Could not open "${filename.replace(/\.(ya?ml)$/, '')}". Check your connection and try again.`);
stackListState.setSelectedFile(null);
editorState.setContent('');
editorState.setOriginalContent('');
@@ -890,18 +894,40 @@ export function useStackActions(options: UseStackActionsOptions) {
}
};
// Guard a navigation that would leave (and discard) a dirty editor: back to
// the list, Home, or any bottom-tab / hamburger / command-palette
// destination. When the editor is dirty the navigation is stashed and the
// unsaved-changes dialog opens; discardAndLoadPending runs it on confirm.
// When clean it runs immediately.
const attemptLeaveEditor = (perform: () => void) => {
if (stackListState.selectedFile && hasUnsavedChanges()) {
overlayState.setPendingLeaveAction({ run: perform });
return;
}
perform();
};
const cancelPendingUnsavedLoad = () => {
overlayState.setPendingUnsavedLoad(null);
overlayState.setPendingUnsavedNode(null);
overlayState.setPendingLeaveAction(null);
};
const discardAndLoadPending = () => {
const leave = overlayState.pendingLeaveAction;
const target = overlayState.pendingUnsavedLoad;
const targetNode = overlayState.pendingUnsavedNode;
editorState.setContent(editorState.originalContent);
editorState.setEnvContent(editorState.originalEnvContent);
overlayState.setPendingUnsavedLoad(null);
overlayState.setPendingUnsavedNode(null);
overlayState.setPendingLeaveAction(null);
// A stashed "leave editor" navigation takes precedence; it already knows
// how to tear down editor state (resetEditorState) and move the surface.
if (leave) {
leave.run();
return;
}
if (target === NODE_SWITCH_PENDING_TOKEN) {
if (targetNode) setActiveNode(targetNode);
return;
@@ -1060,6 +1086,7 @@ export function useStackActions(options: UseStackActionsOptions) {
serviceAction,
updateStack,
deleteStack,
attemptLeaveEditor,
cancelPendingUnsavedLoad,
discardAndLoadPending,
requestDeleteStack,
@@ -0,0 +1,44 @@
import { describe, it, expect } from 'vitest';
import { deriveMobileSurface, type MobileSurfaceInput } from './mobile-surface';
const base: MobileSurfaceInput = {
activeView: 'dashboard',
selectedFile: null,
mobileView: 'list',
pendingDetailStack: null,
};
describe('deriveMobileSurface', () => {
it('shows the list when mobileView is list and no detail is open', () => {
expect(deriveMobileSurface(base)).toEqual({ surface: 'list', detailReady: false, detailOpen: false });
});
it('shows content when mobileView is content', () => {
expect(deriveMobileSurface({ ...base, mobileView: 'content', activeView: 'fleet' }).surface).toBe('content');
});
it('shows a ready detail when a stack is selected in editor view', () => {
expect(deriveMobileSurface({ ...base, activeView: 'editor', selectedFile: 'web.yml' })).toEqual({
surface: 'detail',
detailReady: true,
detailOpen: true,
});
});
it('shows the detail optimistically while a tap is pending and not yet ready', () => {
const r = deriveMobileSurface({ ...base, pendingDetailStack: 'web.yml' });
expect(r.surface).toBe('detail');
expect(r.detailOpen).toBe(true);
expect(r.detailReady).toBe(false);
});
it('falls back to the list once a pending tap clears without a selection (load-failed path)', () => {
expect(deriveMobileSurface({ ...base, pendingDetailStack: null, selectedFile: null }).surface).toBe('list');
});
it('gives the detail precedence over a content view', () => {
expect(
deriveMobileSurface({ ...base, mobileView: 'content', activeView: 'editor', selectedFile: 'web.yml' }).surface,
).toBe('detail');
});
});
@@ -0,0 +1,44 @@
import type { ActiveView } from './hooks/useViewNavigationState';
// The top-level mobile surface when no stack detail is open. Kept distinct from
// `activeView` so `dashboard` still maps to HomeDashboard rather than being
// overloaded to mean "the stack list".
export type MobileView = 'list' | 'content';
// The single surface the mobile shell renders at a time.
export type MobileSurface = 'list' | 'content' | 'detail';
export interface MobileSurfaceInput {
activeView: ActiveView;
selectedFile: string | null;
mobileView: MobileView;
/** Set the instant a row is tapped, before loadFile resolves selectedFile. */
pendingDetailStack: string | null;
}
export interface MobileSurfaceState {
surface: MobileSurface;
/** The real EditorView can mount (a stack is selected and editor is active). */
detailReady: boolean;
/** Detail surface should show, including the optimistic pre-fetch window. */
detailOpen: boolean;
}
/**
* Pure derivation of which mobile surface to show. Extracted so the state
* machine can be unit-tested independently of the context-heavy EditorLayout.
*/
export function deriveMobileSurface({
activeView,
selectedFile,
mobileView,
pendingDetailStack,
}: MobileSurfaceInput): MobileSurfaceState {
const detailReady = activeView === 'editor' && !!selectedFile;
const detailOpen = detailReady || !!pendingDetailStack;
let surface: MobileSurface;
if (detailOpen) surface = 'detail';
else if (mobileView === 'list') surface = 'list';
else surface = 'content';
return { surface, detailReady, detailOpen };
}