feat(web): /machine dev-box page with status, terminal, and home file browser
This commit is contained in:
@@ -0,0 +1,5 @@
|
|||||||
|
import { MachineShell } from '@/components/machine/machine-shell';
|
||||||
|
|
||||||
|
const MachinePage = () => <MachineShell />;
|
||||||
|
|
||||||
|
export default MachinePage;
|
||||||
@@ -75,12 +75,14 @@ export const XtermSession = ({
|
|||||||
sessionKey,
|
sessionKey,
|
||||||
waitingLabel,
|
waitingLabel,
|
||||||
copyOnSelect,
|
copyOnSelect,
|
||||||
|
label = 'workspace shell',
|
||||||
}: {
|
}: {
|
||||||
active: boolean;
|
active: boolean;
|
||||||
tokenUrl: string;
|
tokenUrl: string;
|
||||||
sessionKey: string;
|
sessionKey: string;
|
||||||
waitingLabel?: string;
|
waitingLabel?: string;
|
||||||
copyOnSelect?: boolean;
|
copyOnSelect?: boolean;
|
||||||
|
label?: string;
|
||||||
}) => {
|
}) => {
|
||||||
const containerRef = useRef<HTMLDivElement>(null);
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
const termRef = useRef<Terminal | null>(null);
|
const termRef = useRef<Terminal | null>(null);
|
||||||
@@ -183,11 +185,9 @@ export const XtermSession = ({
|
|||||||
sendResize,
|
sendResize,
|
||||||
fontsReady: document.fonts.ready,
|
fontsReady: document.fonts.ready,
|
||||||
loadNerdFont: () =>
|
loadNerdFont: () =>
|
||||||
document.fonts
|
document.fonts.load("16px 'Symbols Nerd Font Mono'", '').then(() => {
|
||||||
.load("16px 'Symbols Nerd Font Mono'", '')
|
if (!isAborted()) term.refresh(0, term.rows - 1);
|
||||||
.then(() => {
|
}),
|
||||||
if (!isAborted()) term.refresh(0, term.rows - 1);
|
|
||||||
}),
|
|
||||||
raf: (cb) => requestAnimationFrame(cb),
|
raf: (cb) => requestAnimationFrame(cb),
|
||||||
isAborted,
|
isAborted,
|
||||||
});
|
});
|
||||||
@@ -243,7 +243,7 @@ export const XtermSession = ({
|
|||||||
<div className='border-border flex h-10 flex-none items-center justify-between gap-3 border-b px-3'>
|
<div className='border-border flex h-10 flex-none items-center justify-between gap-3 border-b px-3'>
|
||||||
<p className='text-muted-foreground text-xs'>
|
<p className='text-muted-foreground text-xs'>
|
||||||
{status === 'connected'
|
{status === 'connected'
|
||||||
? 'Connected · workspace shell'
|
? `Connected · ${label}`
|
||||||
: status === 'connecting'
|
: status === 'connecting'
|
||||||
? 'Connecting…'
|
? 'Connecting…'
|
||||||
: status === 'closed'
|
: status === 'closed'
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import {
|
|||||||
GitBranch,
|
GitBranch,
|
||||||
LayoutDashboard,
|
LayoutDashboard,
|
||||||
MessagesSquare,
|
MessagesSquare,
|
||||||
|
Server,
|
||||||
Settings,
|
Settings,
|
||||||
ShieldCheck,
|
ShieldCheck,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
@@ -37,6 +38,11 @@ const Header = (headerProps: ComponentProps<'header'>) => {
|
|||||||
icon: MessagesSquare,
|
icon: MessagesSquare,
|
||||||
label: 'Threads',
|
label: 'Threads',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
href: '/machine',
|
||||||
|
icon: Server,
|
||||||
|
label: 'Machine',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
href: '/settings/profile',
|
href: '/settings/profile',
|
||||||
icon: Settings,
|
icon: Settings,
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { Loader2, Play, RotateCw, Server, Square } from 'lucide-react';
|
||||||
|
|
||||||
|
import {
|
||||||
|
Badge,
|
||||||
|
Button,
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from '@spoon/ui';
|
||||||
|
|
||||||
|
export type BoxStatus = {
|
||||||
|
running: boolean;
|
||||||
|
image: string | null;
|
||||||
|
startedAt: string | null;
|
||||||
|
memoryLimitBytes: number | null;
|
||||||
|
containerName: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type LifecycleAction = 'start' | 'stop' | 'restart';
|
||||||
|
|
||||||
|
const formatUptime = (startedAt: string | null): string => {
|
||||||
|
if (!startedAt) return '—';
|
||||||
|
const started = new Date(startedAt).getTime();
|
||||||
|
if (Number.isNaN(started)) return '—';
|
||||||
|
const seconds = Math.max(0, Math.floor((Date.now() - started) / 1000));
|
||||||
|
const days = Math.floor(seconds / 86_400);
|
||||||
|
const hours = Math.floor((seconds % 86_400) / 3_600);
|
||||||
|
const minutes = Math.floor((seconds % 3_600) / 60);
|
||||||
|
if (days > 0) return `${days}d ${hours}h`;
|
||||||
|
if (hours > 0) return `${hours}h ${minutes}m`;
|
||||||
|
if (minutes > 0) return `${minutes}m`;
|
||||||
|
return `${seconds}s`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatMemory = (bytes: number | null): string => {
|
||||||
|
if (bytes === null) return 'Unlimited';
|
||||||
|
const gib = bytes / 1024 ** 3;
|
||||||
|
return `${gib.toFixed(gib < 10 ? 1 : 0)} GiB`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const Detail = ({ label, value }: { label: string; value: string }) => (
|
||||||
|
<div className='min-w-0'>
|
||||||
|
<p className='text-muted-foreground text-[11px] font-medium tracking-wide uppercase'>
|
||||||
|
{label}
|
||||||
|
</p>
|
||||||
|
<p className='truncate font-mono text-sm'>{value}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
export const BoxStatusCard = ({
|
||||||
|
status,
|
||||||
|
pendingAction,
|
||||||
|
onAction,
|
||||||
|
}: {
|
||||||
|
status: BoxStatus | null | undefined;
|
||||||
|
pendingAction: LifecycleAction | null;
|
||||||
|
onAction: (action: LifecycleAction) => void;
|
||||||
|
}) => {
|
||||||
|
const loading = status === undefined;
|
||||||
|
const running = Boolean(status?.running);
|
||||||
|
const busy = pendingAction !== null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card className='shadow-none'>
|
||||||
|
<CardHeader className='flex flex-row items-center justify-between gap-4 space-y-0'>
|
||||||
|
<CardTitle className='flex items-center gap-2 text-base'>
|
||||||
|
<Server className='size-4' />
|
||||||
|
My Machine
|
||||||
|
</CardTitle>
|
||||||
|
{loading ? (
|
||||||
|
<Badge variant='outline' className='gap-1'>
|
||||||
|
<Loader2 className='size-3 animate-spin' />
|
||||||
|
Checking…
|
||||||
|
</Badge>
|
||||||
|
) : running ? (
|
||||||
|
<Badge className='gap-1'>Running</Badge>
|
||||||
|
) : (
|
||||||
|
<Badge variant='secondary'>Stopped</Badge>
|
||||||
|
)}
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className='space-y-4'>
|
||||||
|
<div className='grid grid-cols-2 gap-4 sm:grid-cols-3'>
|
||||||
|
<Detail label='Image' value={status?.image ?? '—'} />
|
||||||
|
<Detail
|
||||||
|
label='Uptime'
|
||||||
|
value={running ? formatUptime(status?.startedAt ?? null) : '—'}
|
||||||
|
/>
|
||||||
|
<Detail
|
||||||
|
label='Memory'
|
||||||
|
value={formatMemory(status?.memoryLimitBytes ?? null)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className='flex flex-wrap gap-2'>
|
||||||
|
{running ? (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='outline'
|
||||||
|
size='sm'
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => onAction('stop')}
|
||||||
|
>
|
||||||
|
{pendingAction === 'stop' ? (
|
||||||
|
<Loader2 className='size-4 animate-spin' />
|
||||||
|
) : (
|
||||||
|
<Square className='size-4' />
|
||||||
|
)}
|
||||||
|
Stop
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
variant='outline'
|
||||||
|
size='sm'
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() => onAction('restart')}
|
||||||
|
>
|
||||||
|
{pendingAction === 'restart' ? (
|
||||||
|
<Loader2 className='size-4 animate-spin' />
|
||||||
|
) : (
|
||||||
|
<RotateCw className='size-4' />
|
||||||
|
)}
|
||||||
|
Restart
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
type='button'
|
||||||
|
size='sm'
|
||||||
|
disabled={busy || loading}
|
||||||
|
onClick={() => onAction('start')}
|
||||||
|
>
|
||||||
|
{pendingAction === 'start' ? (
|
||||||
|
<Loader2 className='size-4 animate-spin' />
|
||||||
|
) : (
|
||||||
|
<Play className='size-4' />
|
||||||
|
)}
|
||||||
|
Start
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,351 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import type {
|
||||||
|
FileResponse,
|
||||||
|
FileTreeNode,
|
||||||
|
} from '@/components/agent-workspace/types';
|
||||||
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
import { CodeEditor } from '@/components/agent-workspace/code-editor';
|
||||||
|
import { FileTabs } from '@/components/agent-workspace/file-tabs';
|
||||||
|
import { FileTree } from '@/components/agent-workspace/file-tree';
|
||||||
|
import { XtermSession } from '@/components/agent-workspace/xterm-session';
|
||||||
|
import { useQuery } from 'convex/react';
|
||||||
|
import { FolderTree, SquareTerminal } from 'lucide-react';
|
||||||
|
import { toast } from 'sonner';
|
||||||
|
|
||||||
|
import { api } from '@spoon/backend/convex/_generated/api.js';
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@spoon/ui';
|
||||||
|
|
||||||
|
import type { BoxStatus, LifecycleAction } from './box-status-card';
|
||||||
|
import { BoxStatusCard } from './box-status-card';
|
||||||
|
|
||||||
|
const STATUS_POLL_MS = 10_000;
|
||||||
|
|
||||||
|
type OpenFileState = {
|
||||||
|
path: string;
|
||||||
|
content: string;
|
||||||
|
savedContent: string;
|
||||||
|
loading: boolean;
|
||||||
|
saving: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const MachineShell = () => {
|
||||||
|
const environment = useQuery(api.userEnvironment.getMine, {});
|
||||||
|
const username = environment?.username ?? '';
|
||||||
|
const firstName = environment?.firstName;
|
||||||
|
|
||||||
|
const [status, setStatus] = useState<BoxStatus | null | undefined>(undefined);
|
||||||
|
const [pendingAction, setPendingAction] = useState<LifecycleAction | null>(
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
const [tree, setTree] = useState<FileTreeNode | null>(null);
|
||||||
|
const [files, setFiles] = useState<Record<string, OpenFileState>>({});
|
||||||
|
const [openFilePaths, setOpenFilePaths] = useState<string[]>([]);
|
||||||
|
const [activeFilePath, setActiveFilePath] = useState<string>();
|
||||||
|
const [expandedDirectoryPaths, setExpandedDirectoryPaths] = useState<
|
||||||
|
string[]
|
||||||
|
>([]);
|
||||||
|
const [vimEnabled, setVimEnabled] = useState(false);
|
||||||
|
const [activeTab, setActiveTab] = useState<'files' | 'terminal'>('files');
|
||||||
|
|
||||||
|
const refreshStatus = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/box/status');
|
||||||
|
if (!response.ok) throw new Error(await response.text());
|
||||||
|
const data = (await response.json()) as { status: BoxStatus };
|
||||||
|
setStatus(data.status);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
setStatus((current) => current ?? null);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const loadTree = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/box/tree');
|
||||||
|
if (!response.ok) throw new Error(await response.text());
|
||||||
|
const data = (await response.json()) as { tree: FileTreeNode | null };
|
||||||
|
setTree(data.tree);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void refreshStatus();
|
||||||
|
void loadTree();
|
||||||
|
const interval = window.setInterval(() => {
|
||||||
|
void refreshStatus();
|
||||||
|
}, STATUS_POLL_MS);
|
||||||
|
return () => window.clearInterval(interval);
|
||||||
|
}, [refreshStatus, loadTree]);
|
||||||
|
|
||||||
|
const runLifecycle = useCallback(
|
||||||
|
(action: LifecycleAction) => {
|
||||||
|
if (pendingAction) return;
|
||||||
|
setPendingAction(action);
|
||||||
|
void (async () => {
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/box/lifecycle', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ action }),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error(await response.text());
|
||||||
|
const data = (await response.json()) as { status: BoxStatus };
|
||||||
|
setStatus(data.status);
|
||||||
|
toast.success(
|
||||||
|
action === 'stop'
|
||||||
|
? 'Machine stopped.'
|
||||||
|
: action === 'restart'
|
||||||
|
? 'Machine restarted.'
|
||||||
|
: 'Machine started.',
|
||||||
|
);
|
||||||
|
void loadTree();
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
toast.error(`Could not ${action} your machine.`);
|
||||||
|
void refreshStatus();
|
||||||
|
} finally {
|
||||||
|
setPendingAction(null);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
},
|
||||||
|
[pendingAction, loadTree, refreshStatus],
|
||||||
|
);
|
||||||
|
|
||||||
|
const loadFile = useCallback(async (path: string) => {
|
||||||
|
setFiles((current) => ({
|
||||||
|
...current,
|
||||||
|
[path]: current[path] ?? {
|
||||||
|
path,
|
||||||
|
content: '',
|
||||||
|
savedContent: '',
|
||||||
|
loading: true,
|
||||||
|
saving: false,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/box/file?path=${encodeURIComponent(path)}`,
|
||||||
|
);
|
||||||
|
if (!response.ok) throw new Error(await response.text());
|
||||||
|
const data = (await response.json()) as FileResponse;
|
||||||
|
setFiles((current) => ({
|
||||||
|
...current,
|
||||||
|
[data.path]: {
|
||||||
|
path: data.path,
|
||||||
|
content: data.content,
|
||||||
|
savedContent: data.content,
|
||||||
|
loading: false,
|
||||||
|
saving: false,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const openFile = useCallback(
|
||||||
|
(path: string) => {
|
||||||
|
setOpenFilePaths((current) =>
|
||||||
|
current.includes(path) ? current : [...current, path],
|
||||||
|
);
|
||||||
|
setActiveFilePath(path);
|
||||||
|
if (!files[path]) {
|
||||||
|
void loadFile(path).catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
setFiles((current) => {
|
||||||
|
const next = { ...current };
|
||||||
|
delete next[path];
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
setOpenFilePaths((current) =>
|
||||||
|
current.filter((filePath) => filePath !== path),
|
||||||
|
);
|
||||||
|
toast.error('Could not load file.');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[files, loadFile],
|
||||||
|
);
|
||||||
|
|
||||||
|
const writeFileContent = async (path: string, content: string) => {
|
||||||
|
setFiles((current) => ({
|
||||||
|
...current,
|
||||||
|
[path]: {
|
||||||
|
...(current[path] ?? { path, savedContent: '', loading: false }),
|
||||||
|
content,
|
||||||
|
saving: true,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
const response = await fetch('/api/box/file', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ path, content }),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
setFiles((current) => ({
|
||||||
|
...current,
|
||||||
|
[path]: {
|
||||||
|
...(current[path] ?? {
|
||||||
|
path,
|
||||||
|
content,
|
||||||
|
savedContent: '',
|
||||||
|
loading: false,
|
||||||
|
}),
|
||||||
|
saving: false,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
toast.error('Could not save file.');
|
||||||
|
throw new Error(await response.text());
|
||||||
|
}
|
||||||
|
setFiles((current) => ({
|
||||||
|
...current,
|
||||||
|
[path]: {
|
||||||
|
...(current[path] ?? { path, loading: false }),
|
||||||
|
content,
|
||||||
|
savedContent: content,
|
||||||
|
saving: false,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
toast.success('File saved.');
|
||||||
|
};
|
||||||
|
|
||||||
|
const saveFile = async (content: string) => {
|
||||||
|
if (!activeFilePath) return;
|
||||||
|
await writeFileContent(activeFilePath, content);
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeFile = (path: string) => {
|
||||||
|
const index = openFilePaths.indexOf(path);
|
||||||
|
const nextOpen = openFilePaths.filter((filePath) => filePath !== path);
|
||||||
|
setOpenFilePaths(nextOpen);
|
||||||
|
setFiles((current) => {
|
||||||
|
const next = { ...current };
|
||||||
|
delete next[path];
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
if (activeFilePath === path) {
|
||||||
|
setActiveFilePath(nextOpen[index - 1] ?? nextOpen[index] ?? undefined);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleDirectory = (path: string) => {
|
||||||
|
setExpandedDirectoryPaths((current) =>
|
||||||
|
current.includes(path)
|
||||||
|
? current.filter((directoryPath) => directoryPath !== path)
|
||||||
|
: [...current, path],
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const activeFile = activeFilePath ? files[activeFilePath] : undefined;
|
||||||
|
const running = Boolean(status?.running);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className='space-y-6'>
|
||||||
|
<div>
|
||||||
|
<h1 className='text-3xl font-semibold tracking-normal'>
|
||||||
|
{firstName ? `${firstName}'s Machine` : 'My Machine'}
|
||||||
|
</h1>
|
||||||
|
<p className='text-muted-foreground mt-2'>
|
||||||
|
Your always-available dev box — a persistent home, a terminal, and a
|
||||||
|
file browser rooted at <code className='font-mono'>~</code>.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<BoxStatusCard
|
||||||
|
status={status}
|
||||||
|
pendingAction={pendingAction}
|
||||||
|
onAction={runLifecycle}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Tabs
|
||||||
|
value={activeTab}
|
||||||
|
onValueChange={(value) => setActiveTab(value as 'files' | 'terminal')}
|
||||||
|
className='border-border bg-muted/20 flex h-[calc(100vh-8.5rem)] min-h-[600px] flex-col overflow-hidden rounded-md border'
|
||||||
|
>
|
||||||
|
<TabsList className='border-border bg-muted/30 h-12 flex-none justify-start rounded-none border-b px-3'>
|
||||||
|
<TabsTrigger
|
||||||
|
value='files'
|
||||||
|
className='data-active:bg-background data-active:text-foreground data-active:shadow-sm'
|
||||||
|
>
|
||||||
|
<FolderTree className='size-4' />
|
||||||
|
Files
|
||||||
|
</TabsTrigger>
|
||||||
|
<TabsTrigger
|
||||||
|
value='terminal'
|
||||||
|
className='data-active:bg-background data-active:text-foreground data-active:shadow-sm'
|
||||||
|
>
|
||||||
|
<SquareTerminal className='size-4' />
|
||||||
|
Terminal
|
||||||
|
</TabsTrigger>
|
||||||
|
</TabsList>
|
||||||
|
<TabsContent
|
||||||
|
value='files'
|
||||||
|
className='m-0 grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-[280px_minmax(0,1fr)]'
|
||||||
|
>
|
||||||
|
<aside className='border-border bg-background min-h-0 border-r'>
|
||||||
|
<div className='border-border border-b p-3'>
|
||||||
|
<h2 className='text-sm font-semibold'>Home</h2>
|
||||||
|
<p className='text-muted-foreground text-xs'>
|
||||||
|
Files in your persistent home
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<FileTree
|
||||||
|
tree={tree}
|
||||||
|
selectedPath={activeFilePath}
|
||||||
|
expandedPaths={expandedDirectoryPaths}
|
||||||
|
onSelect={openFile}
|
||||||
|
onToggleDirectory={toggleDirectory}
|
||||||
|
/>
|
||||||
|
</aside>
|
||||||
|
<section className='bg-background flex min-w-0 flex-col overflow-hidden'>
|
||||||
|
<FileTabs
|
||||||
|
tabs={openFilePaths.map((path) => ({
|
||||||
|
path,
|
||||||
|
dirty: files[path]
|
||||||
|
? files[path].content !== files[path].savedContent
|
||||||
|
: false,
|
||||||
|
}))}
|
||||||
|
activePath={activeFilePath}
|
||||||
|
onActivate={setActiveFilePath}
|
||||||
|
onClose={closeFile}
|
||||||
|
/>
|
||||||
|
<CodeEditor
|
||||||
|
path={activeFilePath}
|
||||||
|
content={activeFile?.content ?? ''}
|
||||||
|
savedContent={activeFile?.savedContent ?? ''}
|
||||||
|
readOnly={false}
|
||||||
|
vimEnabled={vimEnabled}
|
||||||
|
onSave={saveFile}
|
||||||
|
onVimEnabledChange={setVimEnabled}
|
||||||
|
onChange={(content) => {
|
||||||
|
if (!activeFilePath) return;
|
||||||
|
setFiles((current) => ({
|
||||||
|
...current,
|
||||||
|
[activeFilePath]: {
|
||||||
|
...(current[activeFilePath] ?? {
|
||||||
|
path: activeFilePath,
|
||||||
|
savedContent: '',
|
||||||
|
loading: false,
|
||||||
|
saving: false,
|
||||||
|
}),
|
||||||
|
content,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
</TabsContent>
|
||||||
|
<TabsContent
|
||||||
|
value='terminal'
|
||||||
|
forceMount
|
||||||
|
className='m-0 min-h-0 flex-1 overflow-hidden data-[state=inactive]:hidden'
|
||||||
|
>
|
||||||
|
<XtermSession
|
||||||
|
active={running}
|
||||||
|
tokenUrl='/api/box/terminal-token'
|
||||||
|
sessionKey={username}
|
||||||
|
waitingLabel='Starting your machine…'
|
||||||
|
label='your machine'
|
||||||
|
/>
|
||||||
|
</TabsContent>
|
||||||
|
</Tabs>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import {
|
||||||
|
cleanup,
|
||||||
|
fireEvent,
|
||||||
|
render,
|
||||||
|
screen,
|
||||||
|
waitFor,
|
||||||
|
} from '@testing-library/react';
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
|
||||||
|
import { MachineShell } from '../../src/components/machine/machine-shell';
|
||||||
|
|
||||||
|
const { mockUseQuery, fetchSpy } = vi.hoisted(() => ({
|
||||||
|
mockUseQuery: vi.fn(),
|
||||||
|
fetchSpy: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('convex/react', () => ({
|
||||||
|
useQuery: mockUseQuery,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('next/navigation', () => ({
|
||||||
|
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('sonner', () => ({
|
||||||
|
toast: { error: vi.fn(), success: vi.fn() },
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@/components/agent-workspace/xterm-session', () => ({
|
||||||
|
XtermSession: () => <div>terminal</div>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@/components/agent-workspace/code-editor', () => ({
|
||||||
|
CodeEditor: () => <div>editor</div>,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const stoppedStatus = {
|
||||||
|
running: false,
|
||||||
|
image: 'spoon/devbox:latest',
|
||||||
|
startedAt: null,
|
||||||
|
memoryLimitBytes: null,
|
||||||
|
containerName: 'spoon-home-gib',
|
||||||
|
};
|
||||||
|
|
||||||
|
const tree = {
|
||||||
|
name: '',
|
||||||
|
path: '',
|
||||||
|
type: 'directory',
|
||||||
|
children: [{ name: 'README.md', path: 'README.md', type: 'file' }],
|
||||||
|
};
|
||||||
|
|
||||||
|
const jsonResponse = (body: unknown) => ({
|
||||||
|
ok: true,
|
||||||
|
json: () => Promise.resolve(body),
|
||||||
|
text: () => Promise.resolve(JSON.stringify(body)),
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockUseQuery.mockReturnValue({
|
||||||
|
username: 'gib',
|
||||||
|
firstName: 'Gib',
|
||||||
|
enabled: true,
|
||||||
|
});
|
||||||
|
fetchSpy.mockImplementation((input: RequestInfo | URL) => {
|
||||||
|
const url =
|
||||||
|
typeof input === 'string'
|
||||||
|
? input
|
||||||
|
: input instanceof URL
|
||||||
|
? input.href
|
||||||
|
: input.url;
|
||||||
|
if (url.startsWith('/api/box/status')) {
|
||||||
|
return Promise.resolve(jsonResponse({ status: stoppedStatus }));
|
||||||
|
}
|
||||||
|
if (url.startsWith('/api/box/tree')) {
|
||||||
|
return Promise.resolve(jsonResponse({ tree }));
|
||||||
|
}
|
||||||
|
if (url.startsWith('/api/box/lifecycle')) {
|
||||||
|
return Promise.resolve(
|
||||||
|
jsonResponse({
|
||||||
|
status: {
|
||||||
|
...stoppedStatus,
|
||||||
|
running: true,
|
||||||
|
startedAt: new Date().toISOString(),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Promise.resolve(jsonResponse({}));
|
||||||
|
});
|
||||||
|
vi.stubGlobal('fetch', fetchSpy);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('MachineShell', () => {
|
||||||
|
it('renders a stopped status card with a Start button', async () => {
|
||||||
|
render(<MachineShell />);
|
||||||
|
expect(await screen.findByText('Stopped')).toBeInTheDocument();
|
||||||
|
expect(screen.getByRole('button', { name: 'Start' })).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('starts the box when Start is clicked', async () => {
|
||||||
|
render(<MachineShell />);
|
||||||
|
const startButton = await screen.findByRole('button', { name: 'Start' });
|
||||||
|
fireEvent.click(startButton);
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(fetchSpy).toHaveBeenCalledWith(
|
||||||
|
'/api/box/lifecycle',
|
||||||
|
expect.objectContaining({
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ action: 'start' }),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders the home file tree', async () => {
|
||||||
|
render(<MachineShell />);
|
||||||
|
expect(await screen.findByText('README.md')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders the terminal', async () => {
|
||||||
|
render(<MachineShell />);
|
||||||
|
expect(await screen.findByText('terminal')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user