@mgamadeus/ddd-agent-sandbox 0.0.0-stage → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1053 @@
1
+ 'use client';
2
+
3
+ // src/screen/format.ts
4
+ import { Archive, CircleCheck, CircleDot, CircleX, Clock, Moon, Play, ShieldAlert } from "lucide-react";
5
+ import { formatUiNumber } from "@mgamadeus/ddd-admin-ui/i18n";
6
+ import { m } from "@mgamadeus/ddd-admin-ui/i18n";
7
+ import { defineStatusMap } from "@mgamadeus/ddd-admin-ui/logic";
8
+ var SANDBOX_STATE = defineStatusMap({
9
+ RUNNING: {
10
+ label: m("Running", { context: "sandbox-state" }),
11
+ tone: "success",
12
+ icon: Play,
13
+ description: m("A session is open: commands run and files live on the runner", { context: "sandbox-state" })
14
+ },
15
+ IDLE: {
16
+ label: m("Idle", { context: "sandbox-state" }),
17
+ tone: "info",
18
+ icon: Moon,
19
+ description: m("The session is open but nothing ran for a while", { context: "sandbox-state" })
20
+ },
21
+ OFFLOADED: {
22
+ label: m("Offloaded", { context: "sandbox-state" }),
23
+ tone: "neutral",
24
+ icon: Archive,
25
+ description: m("No session: the workspace is saved and starts again on the next command", { context: "sandbox-state" })
26
+ }
27
+ }, { context: "sandbox-state" });
28
+ var SANDBOX_ACTION_OUTCOME = defineStatusMap({
29
+ SUCCEEDED: { label: m("Done", { context: "sandbox-action-outcome" }), tone: "success", icon: CircleCheck },
30
+ REFUSED: {
31
+ label: m("Refused", { context: "sandbox-action-outcome" }),
32
+ tone: "warning",
33
+ icon: ShieldAlert,
34
+ description: m("Not run: a turn was running, a confirmation or a reason was missing", { context: "sandbox-action-outcome" })
35
+ },
36
+ FAILED: { label: m("Failed", { context: "sandbox-action-outcome" }), tone: "danger", icon: CircleX }
37
+ }, { context: "sandbox-action-outcome" });
38
+ var sandboxCommandStateOf = (command) => {
39
+ if (command.status) return command.status;
40
+ return command.exitCode === null || command.exitCode === void 0 ? "UNKNOWN" : "EXITED";
41
+ };
42
+ var SANDBOX_COMMAND_STATE = defineStatusMap({
43
+ RUNNING: { label: m("Running", { context: "sandbox-command-state" }), tone: "info", icon: Play },
44
+ EXITED: { label: m("Exited", { context: "sandbox-command-state" }), tone: "neutral", icon: CircleCheck },
45
+ KILLED: {
46
+ label: m("Killed", { context: "sandbox-command-state" }),
47
+ tone: "warning",
48
+ icon: CircleX,
49
+ description: m("The command was stopped: its job was killed, the session ended or a limit was hit", { context: "sandbox-command-state" })
50
+ },
51
+ TIMED_OUT: {
52
+ label: m("Timed out", { context: "sandbox-command-state" }),
53
+ tone: "danger",
54
+ icon: Clock,
55
+ description: m("The runner stopped the command at its time limit", { context: "sandbox-command-state" })
56
+ },
57
+ UNKNOWN: {
58
+ label: m("State unknown", { context: "sandbox-command-state" }),
59
+ tone: "neutral",
60
+ icon: CircleDot,
61
+ description: m("The server reports no state and no exit code for this command", { context: "sandbox-command-state" })
62
+ }
63
+ }, { context: "sandbox-command-state" });
64
+ var SANDBOX_ACTION_LABEL_CONTEXT = "sandbox-action";
65
+ var SANDBOX_CHANGE_LABEL_CONTEXT = "sandbox-change";
66
+ var SANDBOX_ACTION_LABELS = {
67
+ START: m("Start session", { context: "sandbox-action" }),
68
+ OFFLOAD: m("Offload", { context: "sandbox-action" }),
69
+ KILL_JOB: m("Kill job", { context: "sandbox-action" }),
70
+ END: m("End session", { context: "sandbox-action" }),
71
+ RESET: m("Reset workspace", { context: "sandbox-action" })
72
+ };
73
+ var SANDBOX_CHANGE_LABELS = {
74
+ ADDED: m("Added", { context: "sandbox-change" }),
75
+ MODIFIED: m("Changed", { context: "sandbox-change" }),
76
+ DELETED: m("Deleted", { context: "sandbox-change" }),
77
+ RENAMED: m("Renamed", { context: "sandbox-change" })
78
+ };
79
+ var sessionEventIconOf = (type) => /EXCEEDED|DENIED|TIMEOUT|OOM|KILLED/i.test(type) ? ShieldAlert : CircleDot;
80
+ var formatSandboxBytes = (bytes) => {
81
+ if (bytes === null || bytes === void 0 || !Number.isFinite(bytes)) return "\u2014";
82
+ const units = ["B", "KB", "MB", "GB", "TB"];
83
+ let value = bytes;
84
+ let unit = 0;
85
+ while (value >= 1024 && unit < units.length - 1) {
86
+ value /= 1024;
87
+ unit += 1;
88
+ }
89
+ return `${formatUiNumber(value, { maximumFractionDigits: unit === 0 || value >= 100 ? 0 : 1 })} ${units[unit]}`;
90
+ };
91
+ var formatSandboxDuration = (milliseconds) => {
92
+ if (milliseconds === null || milliseconds === void 0 || !Number.isFinite(milliseconds)) return "\u2014";
93
+ if (milliseconds < 1e3) return `${formatUiNumber(Math.round(milliseconds))} ms`;
94
+ const seconds = milliseconds / 1e3;
95
+ if (seconds < 60) return `${formatUiNumber(seconds, { maximumFractionDigits: 1 })} s`;
96
+ const minutes = Math.floor(seconds / 60);
97
+ return `${formatUiNumber(minutes)} min ${formatUiNumber(Math.round(seconds - minutes * 60))} s`;
98
+ };
99
+ var usagePercentOf = (used, limit) => used === null || used === void 0 || !limit || limit <= 0 ? null : Math.min(100, Math.max(0, Math.round(used / limit * 100)));
100
+ var sandboxNameOf = (workspace) => workspace.displayName?.trim() ? workspace.displayName : workspace.workspaceKey;
101
+ var sandboxResetPhraseOf = (workspace) => sandboxNameOf(workspace);
102
+ var isSandboxTurnRunningRefusal = (error) => error?.status === 409;
103
+ var sandboxParentPathOf = (path) => {
104
+ const trimmed = path.replace(/\/+$/, "");
105
+ const index = trimmed.lastIndexOf("/");
106
+ return index <= 0 ? "" : trimmed.slice(0, index);
107
+ };
108
+ var sandboxPathCrumbs = (path) => {
109
+ const parts = path.split("/").filter((part) => part !== "");
110
+ return parts.map((name, index) => ({ name, path: parts.slice(0, index + 1).join("/") }));
111
+ };
112
+ var sandboxPreviewKindOf = (contentType) => {
113
+ const type = contentType.split(";")[0]?.trim().toLowerCase() ?? "";
114
+ if (type === "image/jpeg" || type === "image/png" || type === "image/gif" || type === "image/webp") return "image";
115
+ if (type === "application/pdf") return "pdf";
116
+ if (type === "text/plain") return "text";
117
+ return "none";
118
+ };
119
+ var SANDBOX_TEXT_PREVIEW_BYTES = 256 * 1024;
120
+
121
+ // src/screen/SandboxesScreen.tsx
122
+ import { normalizeDddError as normalizeDddError2 } from "@mgamadeus/ddd-web/contract";
123
+ import { Activity, Archive as Archive2, MoreHorizontal, Play as Play2, Power, RefreshCw } from "lucide-react";
124
+ import { useMemo, useState as useState2 } from "react";
125
+ import { m as m2 } from "@mgamadeus/ddd-admin-ui/i18n";
126
+ import { useTranslate as useTranslate2 } from "@mgamadeus/ddd-admin-ui/i18n";
127
+ import { DateCell } from "@mgamadeus/ddd-admin-ui/list";
128
+ import { EmptyValue } from "@mgamadeus/ddd-admin-ui/list";
129
+ import { EntityListBody } from "@mgamadeus/ddd-admin-ui/list";
130
+ import { EntityListCard } from "@mgamadeus/ddd-admin-ui/list";
131
+ import { EntityListToolbar } from "@mgamadeus/ddd-admin-ui/list";
132
+ import { StatusBadge } from "@mgamadeus/ddd-admin-ui/list";
133
+ import { PageHeader } from "@mgamadeus/ddd-admin-ui/page";
134
+ import { StatusCallout } from "@mgamadeus/ddd-admin-ui/page";
135
+ import { Badge } from "@mgamadeus/ddd-admin-ui/primitives";
136
+ import { Button } from "@mgamadeus/ddd-admin-ui/primitives";
137
+ import { cn } from "@mgamadeus/ddd-admin-ui/primitives";
138
+ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@mgamadeus/ddd-admin-ui/primitives";
139
+
140
+ // src/screen/useSandboxActions.tsx
141
+ import { normalizeDddError } from "@mgamadeus/ddd-web/contract";
142
+ import { useCallback, useState } from "react";
143
+ import { FormDialog } from "@mgamadeus/ddd-admin-ui/form";
144
+ import { useTranslate } from "@mgamadeus/ddd-admin-ui/i18n";
145
+ import { notify } from "@mgamadeus/ddd-admin-ui/logic";
146
+ import { useConfirm } from "@mgamadeus/ddd-admin-ui/logic";
147
+ import { Label } from "@mgamadeus/ddd-admin-ui/primitives";
148
+ import { Textarea } from "@mgamadeus/ddd-admin-ui/primitives";
149
+ import { jsx, jsxs } from "react/jsx-runtime";
150
+ var MIN_REASON_LENGTH = 3;
151
+ var useSandboxActions = (api) => {
152
+ const { t } = useTranslate();
153
+ const confirm = useConfirm();
154
+ const [runAction, actionState] = api.useSandboxActionMutation();
155
+ const [killJob, killState] = api.useKillSandboxJobMutation();
156
+ const [forceRequest, setForceRequest] = useState(null);
157
+ const [reason, setReason] = useState("");
158
+ const [forcing, setForcing] = useState(false);
159
+ const labelOf = useCallback(
160
+ (request) => {
161
+ switch (request.kind) {
162
+ case "start":
163
+ return t("Start session", { context: "sandbox-action" });
164
+ case "offload":
165
+ return t("Offload", { context: "sandbox-action" });
166
+ case "end":
167
+ return t("End session", { context: "sandbox-action" });
168
+ case "reset":
169
+ return t("Reset workspace", { context: "sandbox-action" });
170
+ case "kill":
171
+ return t("Kill job", { context: "sandbox-action" });
172
+ }
173
+ },
174
+ [t]
175
+ );
176
+ const send = useCallback(
177
+ async (request, body) => request.kind === "kill" ? killJob({ workspaceKey: request.workspace.workspaceKey, jobId: request.jobId, ...body }).unwrap() : runAction({ workspaceKey: request.workspace.workspaceKey, action: request.kind, ...body }).unwrap(),
178
+ [killJob, runAction]
179
+ );
180
+ const report = useCallback(
181
+ (request, response) => {
182
+ const { actionResult } = response;
183
+ const name = sandboxNameOf(request.workspace);
184
+ if (actionResult.outcome !== "SUCCEEDED") {
185
+ notify.error(t("%action% did not run for %name%.", { replacements: { action: labelOf(request), name } }));
186
+ return false;
187
+ }
188
+ const offload = actionResult.offloadResult;
189
+ notify.success(
190
+ offload ? t("%name% offloaded: %count% changes saved to the drive.", { replacements: { name, count: offload.committedChangeCount } }) : t("%action%: done for %name%.", { replacements: { action: labelOf(request), name } })
191
+ );
192
+ return true;
193
+ },
194
+ [t, labelOf]
195
+ );
196
+ const attempt = useCallback(
197
+ async (request, body) => {
198
+ try {
199
+ return report(request, await send(request, body));
200
+ } catch (error) {
201
+ if (!body.force && isSandboxTurnRunningRefusal(error)) {
202
+ setReason("");
203
+ setForceRequest({ request, extra: body });
204
+ return false;
205
+ }
206
+ notify.error(normalizeDddError(error, t("%action% failed.", { replacements: { action: labelOf(request) } })).message);
207
+ return false;
208
+ }
209
+ },
210
+ [send, report, t, labelOf]
211
+ );
212
+ const run = useCallback(
213
+ async (request) => {
214
+ const name = sandboxNameOf(request.workspace);
215
+ const extra = {};
216
+ if (request.kind === "reset") {
217
+ const phrase = sandboxResetPhraseOf(request.workspace);
218
+ const confirmed = await confirm({
219
+ title: t("Reset the workspace of %name%?", { replacements: { name } }),
220
+ description: t(
221
+ "Everything on the runner is wiped: local files, installed packages, unsaved changes. Files in the drive stay. The agent starts from an empty workspace next time."
222
+ ),
223
+ confirmLabel: t("Reset workspace", { context: "sandbox-action" }),
224
+ confirmVariant: "destructive",
225
+ requirePhrase: phrase
226
+ });
227
+ if (!confirmed) return false;
228
+ extra.confirmation = phrase;
229
+ } else if (request.kind === "offload" || request.kind === "end" || request.kind === "kill") {
230
+ const jobId = request.kind === "kill" ? request.jobId : "";
231
+ const confirmed = await confirm({
232
+ title: request.kind === "offload" ? t("Offload %name%?", { replacements: { name } }) : request.kind === "end" ? t("End the session of %name%?", { replacements: { name } }) : t("Kill the job %job%?", { replacements: { job: jobId } }),
233
+ description: request.kind === "offload" ? t("Unsaved changes are written to the drive, then the session is released. The workspace stays and starts again on the next command.") : request.kind === "end" ? t("The session stops now, with every running command. The saved workspace stays; changes not yet in the drive can be lost \u2014 offload first to keep them.") : t("The job stops at once; its output so far stays in the command history."),
234
+ confirmLabel: labelOf(request),
235
+ confirmVariant: request.kind === "offload" ? "default" : "destructive"
236
+ });
237
+ if (!confirmed) return false;
238
+ }
239
+ if (request.workspace.hasLiveTurn) {
240
+ setReason("");
241
+ setForceRequest({ request, extra });
242
+ return false;
243
+ }
244
+ return attempt(request, extra);
245
+ },
246
+ [confirm, t, labelOf, attempt]
247
+ );
248
+ const dialog = /* @__PURE__ */ jsx(
249
+ FormDialog,
250
+ {
251
+ open: forceRequest !== null,
252
+ onOpenChange: (open) => !open && setForceRequest(null),
253
+ title: forceRequest ? t("%action% while a turn is running?", { replacements: { action: labelOf(forceRequest.request) } }) : "",
254
+ description: t(
255
+ "An agent conversation of this space is working right now; the action can break its turn. Say why it must run now \u2014 the reason is kept in the audit."
256
+ ),
257
+ submitLabel: t("Run anyway"),
258
+ pendingLabel: t("Running\u2026"),
259
+ submitVariant: "destructive",
260
+ isPending: forcing,
261
+ submitDisabled: reason.trim().length < MIN_REASON_LENGTH,
262
+ onSubmit: async (event) => {
263
+ event.preventDefault();
264
+ if (!forceRequest) return;
265
+ setForcing(true);
266
+ try {
267
+ const ok = await attempt(forceRequest.request, { ...forceRequest.extra, force: true, reason: reason.trim() });
268
+ if (ok) setForceRequest(null);
269
+ } finally {
270
+ setForcing(false);
271
+ }
272
+ },
273
+ children: /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
274
+ /* @__PURE__ */ jsx(Label, { htmlFor: "sandbox-force-reason", children: t("Reason", { context: "sandbox-force" }) }),
275
+ /* @__PURE__ */ jsx(Textarea, { id: "sandbox-force-reason", value: reason, onChange: (event) => setReason(event.target.value), rows: 3, maxLength: 500 })
276
+ ] })
277
+ }
278
+ );
279
+ return { run, isPending: actionState.isLoading || killState.isLoading || forcing, dialog };
280
+ };
281
+
282
+ // src/screen/SandboxesScreen.tsx
283
+ import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
284
+ var SandboxUsageBar = ({ used, limit, peak }) => {
285
+ const { t } = useTranslate2();
286
+ const percent = usagePercentOf(used, limit);
287
+ const peakPercent = usagePercentOf(peak, limit);
288
+ if (used === null || used === void 0) return /* @__PURE__ */ jsx2(EmptyValue, {});
289
+ return /* @__PURE__ */ jsxs2("div", { className: "min-w-28 space-y-1", children: [
290
+ /* @__PURE__ */ jsxs2("p", { className: "text-[12.5px] tabular-nums", children: [
291
+ formatSandboxBytes(used),
292
+ limit ? /* @__PURE__ */ jsxs2("span", { className: "text-muted-foreground", children: [
293
+ " / ",
294
+ formatSandboxBytes(limit)
295
+ ] }) : null,
296
+ peak !== void 0 && peak !== null && /* @__PURE__ */ jsx2("span", { className: "block text-xs text-muted-foreground", children: t("Peak %size%", { replacements: { size: formatSandboxBytes(peak) } }) })
297
+ ] }),
298
+ percent !== null && /* @__PURE__ */ jsxs2("div", { className: "relative h-1.5 w-full overflow-hidden rounded-full bg-muted", role: "presentation", children: [
299
+ /* @__PURE__ */ jsx2(
300
+ "div",
301
+ {
302
+ className: cn("h-full rounded-full", percent >= 90 ? "bg-destructive" : percent >= 75 ? "bg-warning" : "bg-primary"),
303
+ style: { width: `${percent}%` }
304
+ }
305
+ ),
306
+ peakPercent !== null && peakPercent > percent && /* @__PURE__ */ jsx2("div", { className: "absolute top-0 h-full w-0.5 bg-foreground/50", style: { left: `calc(${peakPercent}% - 1px)` } })
307
+ ] })
308
+ ] });
309
+ };
310
+ var SandboxMountMode = ({ workspace }) => {
311
+ if (!workspace.mountMode) return /* @__PURE__ */ jsx2(EmptyValue, {});
312
+ return /* @__PURE__ */ jsxs2("span", { className: "text-[12.5px]", children: [
313
+ /* @__PURE__ */ jsx2(Badge, { variant: "outline", className: "font-mono", children: workspace.mountMode }),
314
+ workspace.mountModeReason && /* @__PURE__ */ jsx2("span", { className: "mt-0.5 block max-w-56 truncate text-xs text-muted-foreground", title: workspace.mountModeReason, children: workspace.mountModeReason })
315
+ ] });
316
+ };
317
+ var SandboxActionsMenu = ({
318
+ workspace,
319
+ onAction,
320
+ disabled = false
321
+ }) => {
322
+ const { t } = useTranslate2();
323
+ const hasSession = workspace.state !== "OFFLOADED";
324
+ return /* @__PURE__ */ jsxs2(DropdownMenu, { children: [
325
+ /* @__PURE__ */ jsx2(DropdownMenuTrigger, { asChild: true, children: /* @__PURE__ */ jsx2(
326
+ Button,
327
+ {
328
+ type: "button",
329
+ variant: "ghost",
330
+ size: "icon-sm",
331
+ "data-row-action-ignore": true,
332
+ disabled,
333
+ "aria-label": t("Actions for %name%", { replacements: { name: sandboxNameOf(workspace) } }),
334
+ children: /* @__PURE__ */ jsx2(MoreHorizontal, {})
335
+ }
336
+ ) }),
337
+ /* @__PURE__ */ jsxs2(DropdownMenuContent, { align: "end", className: "w-48", children: [
338
+ /* @__PURE__ */ jsxs2(DropdownMenuItem, { onSelect: () => onAction("start"), children: [
339
+ /* @__PURE__ */ jsx2(Play2, {}),
340
+ hasSession ? t("Warm up session") : t("Start session", { context: "sandbox-action" })
341
+ ] }),
342
+ /* @__PURE__ */ jsxs2(DropdownMenuItem, { disabled: !hasSession, onSelect: () => onAction("offload"), children: [
343
+ /* @__PURE__ */ jsx2(Archive2, {}),
344
+ t("Offload", { context: "sandbox-action" })
345
+ ] }),
346
+ /* @__PURE__ */ jsx2(DropdownMenuSeparator, {}),
347
+ /* @__PURE__ */ jsxs2(DropdownMenuItem, { variant: "destructive", disabled: !hasSession, onSelect: () => onAction("end"), children: [
348
+ /* @__PURE__ */ jsx2(Power, {}),
349
+ t("End session", { context: "sandbox-action" })
350
+ ] })
351
+ ] })
352
+ ] });
353
+ };
354
+ var SEARCH_KEYS = ["displayName", "workspaceKey", "ownerDisplayName", "runnerPod"];
355
+ var SandboxesScreen = ({ api, title, description, headerActions, onOpenWorkspace }) => {
356
+ const { t } = useTranslate2();
357
+ const listQuery = api.useSandboxesListQuery();
358
+ const actions = useSandboxActions(api);
359
+ const [search, setSearch] = useState2("");
360
+ const workspaces = useMemo(() => listQuery.data?.workspaces?.elements ?? [], [listQuery.data]);
361
+ const needle = search.trim().toLocaleLowerCase();
362
+ const shown = useMemo(
363
+ () => needle === "" ? workspaces : workspaces.filter((workspace) => SEARCH_KEYS.some((key) => String(workspace[key] ?? "").toLocaleLowerCase().includes(needle))),
364
+ [workspaces, needle]
365
+ );
366
+ const runningCount = workspaces.filter((workspace) => workspace.state === "RUNNING").length;
367
+ const columns = [
368
+ {
369
+ id: "name",
370
+ header: t("Workspace", { context: "sandbox" }),
371
+ width: "2fr",
372
+ cell: (workspace) => /* @__PURE__ */ jsxs2("span", { className: "min-w-0", children: [
373
+ /* @__PURE__ */ jsx2("span", { className: "block truncate font-semibold", children: sandboxNameOf(workspace) }),
374
+ /* @__PURE__ */ jsx2("span", { className: "block truncate font-mono text-xs text-muted-foreground", children: workspace.workspaceKey })
375
+ ] })
376
+ },
377
+ {
378
+ id: "state",
379
+ header: t("State", { context: "sandbox" }),
380
+ width: "content",
381
+ cell: (workspace) => /* @__PURE__ */ jsxs2("span", { className: "flex flex-col items-start gap-1", children: [
382
+ /* @__PURE__ */ jsx2(StatusBadge, { value: workspace.state, map: SANDBOX_STATE }),
383
+ workspace.hasLiveTurn && /* @__PURE__ */ jsxs2("span", { className: "flex items-center gap-1 text-xs text-warning", children: [
384
+ /* @__PURE__ */ jsx2(Activity, { className: "size-3" }),
385
+ t("Turn running")
386
+ ] })
387
+ ] })
388
+ },
389
+ { id: "activity", header: t("Last activity"), width: "content", cell: (workspace) => /* @__PURE__ */ jsx2(DateCell, { value: workspace.lastActivityAt }) },
390
+ { id: "disk", header: t("Disk", { context: "sandbox" }), cell: (workspace) => /* @__PURE__ */ jsx2(SandboxUsageBar, { used: workspace.diskUsedBytes, limit: workspace.diskQuotaBytes }) },
391
+ {
392
+ id: "memory",
393
+ header: t("Memory", { context: "sandbox" }),
394
+ cell: (workspace) => /* @__PURE__ */ jsx2(SandboxUsageBar, { used: workspace.memoryBytes, limit: workspace.memoryLimitBytes, peak: workspace.memoryPeakBytes })
395
+ },
396
+ { id: "mount", header: t("Mount", { context: "sandbox" }), cell: (workspace) => /* @__PURE__ */ jsx2(SandboxMountMode, { workspace }) },
397
+ {
398
+ id: "pod",
399
+ header: t("Runner", { context: "sandbox" }),
400
+ cell: (workspace) => workspace.runnerPod ? /* @__PURE__ */ jsx2("span", { className: "font-mono text-xs", children: workspace.runnerPod }) : /* @__PURE__ */ jsx2(EmptyValue, {})
401
+ },
402
+ { id: "owner", header: t("Owner", { context: "sandbox" }), cell: (workspace) => workspace.ownerDisplayName ?? /* @__PURE__ */ jsx2(EmptyValue, {}) },
403
+ {
404
+ id: "conversations",
405
+ header: t("Conversations"),
406
+ width: "content",
407
+ align: "end",
408
+ cell: (workspace) => /* @__PURE__ */ jsx2("span", { className: "tabular-nums", children: workspace.conversationCount ?? "\u2014" })
409
+ },
410
+ {
411
+ id: "actions",
412
+ header: /* @__PURE__ */ jsx2("span", { className: "sr-only", children: t("Actions", { context: "table-column" }) }),
413
+ width: "content",
414
+ pin: "end",
415
+ cell: (workspace) => /* @__PURE__ */ jsx2(SandboxActionsMenu, { workspace, disabled: actions.isPending, onAction: (kind) => void actions.run({ kind, workspace }) })
416
+ }
417
+ ];
418
+ return /* @__PURE__ */ jsxs2("div", { className: "space-y-6", children: [
419
+ /* @__PURE__ */ jsx2(
420
+ PageHeader,
421
+ {
422
+ title: title ?? t("Sandboxes"),
423
+ description: description ?? t("The agents\u2019 workspaces: one per agent space. Files and command output are shown as untrusted text, never run."),
424
+ actions: /* @__PURE__ */ jsxs2("div", { className: "flex flex-wrap items-center gap-2", children: [
425
+ headerActions,
426
+ /* @__PURE__ */ jsxs2(Button, { type: "button", variant: "outline", onClick: () => void listQuery.refetch?.(), disabled: listQuery.isFetching, children: [
427
+ /* @__PURE__ */ jsx2(RefreshCw, { className: cn(listQuery.isFetching && "animate-spin") }),
428
+ t("Refresh")
429
+ ] })
430
+ ] })
431
+ }
432
+ ),
433
+ listQuery.data && !listQuery.data.isConfigured ? /* @__PURE__ */ jsx2(
434
+ StatusCallout,
435
+ {
436
+ tone: "info",
437
+ title: t("Sandboxes are not set up"),
438
+ description: t("No sandbox runner is configured in this application (AI.Sandbox.runner.host), so there is nothing to show.")
439
+ }
440
+ ) : /* @__PURE__ */ jsx2(
441
+ EntityListCard,
442
+ {
443
+ label: m2("Sandboxes"),
444
+ isRefetching: listQuery.isFetching && !listQuery.isLoading,
445
+ toolbar: /* @__PURE__ */ jsx2(
446
+ EntityListToolbar,
447
+ {
448
+ search: { value: search, onChange: setSearch, placeholder: t("Search name, key, owner or runner\u2026"), "aria-label": t("Search sandboxes") },
449
+ trailing: workspaces.length > 0 ? /* @__PURE__ */ jsxs2("span", { className: "text-[12.5px] font-bold text-muted-foreground", children: [
450
+ t("{count, plural, one {# running} other {# running}}", { count: runningCount }),
451
+ " \xB7",
452
+ " ",
453
+ t("{count, plural, one {# workspace} other {# workspaces}}", { count: workspaces.length })
454
+ ] }) : void 0
455
+ }
456
+ ),
457
+ children: /* @__PURE__ */ jsx2(
458
+ EntityListBody,
459
+ {
460
+ displayMode: "table",
461
+ columns,
462
+ items: shown,
463
+ getRowKey: (workspace) => workspace.workspaceKey,
464
+ rowAction: onOpenWorkspace ? (workspace) => () => onOpenWorkspace(workspace.workspaceKey) : void 0,
465
+ isLoading: listQuery.isLoading,
466
+ emptyMessage: t("No workspace yet: a workspace appears with the first command of an agent space."),
467
+ noResultsMessage: t("No workspace matches the search."),
468
+ isSearchActive: needle !== "",
469
+ onClearSearch: () => setSearch(""),
470
+ loadingMessage: t("Loading the sandboxes"),
471
+ error: listQuery.isError ? normalizeDddError2(listQuery.error, t("The sandboxes could not be loaded.")).message : void 0
472
+ }
473
+ )
474
+ }
475
+ ),
476
+ actions.dialog
477
+ ] });
478
+ };
479
+
480
+ // src/screen/SandboxDetailScreen.tsx
481
+ import { normalizeDddError as normalizeDddError4 } from "@mgamadeus/ddd-web/contract";
482
+ import { Archive as Archive3, ChevronRight, File, Folder, Link2, OctagonX, Play as Play3, Power as Power2, RefreshCw as RefreshCw2, RotateCcw } from "lucide-react";
483
+ import { useState as useState4 } from "react";
484
+ import { m as m3 } from "@mgamadeus/ddd-admin-ui/i18n";
485
+ import { useTranslate as useTranslate4 } from "@mgamadeus/ddd-admin-ui/i18n";
486
+ import { DateCell as DateCell2 } from "@mgamadeus/ddd-admin-ui/list";
487
+ import { EmptyValue as EmptyValue2 } from "@mgamadeus/ddd-admin-ui/list";
488
+ import { EntityListBody as EntityListBody2 } from "@mgamadeus/ddd-admin-ui/list";
489
+ import { EntityListCard as EntityListCard2 } from "@mgamadeus/ddd-admin-ui/list";
490
+ import { StatusBadge as StatusBadge2 } from "@mgamadeus/ddd-admin-ui/list";
491
+ import { DefinitionList } from "@mgamadeus/ddd-admin-ui/page";
492
+ import { PageHeader as PageHeader2 } from "@mgamadeus/ddd-admin-ui/page";
493
+ import { SectionHeader } from "@mgamadeus/ddd-admin-ui/page";
494
+ import { StatusCallout as StatusCallout2 } from "@mgamadeus/ddd-admin-ui/page";
495
+ import { Badge as Badge2 } from "@mgamadeus/ddd-admin-ui/primitives";
496
+ import { Button as Button3 } from "@mgamadeus/ddd-admin-ui/primitives";
497
+ import { Card, CardContent } from "@mgamadeus/ddd-admin-ui/primitives";
498
+ import { cn as cn2 } from "@mgamadeus/ddd-admin-ui/primitives";
499
+ import { useLinkComponent } from "@mgamadeus/ddd-admin-ui/primitives";
500
+ import { Skeleton as Skeleton2 } from "@mgamadeus/ddd-admin-ui/primitives";
501
+
502
+ // src/screen/SandboxFilePreview.tsx
503
+ import { normalizeDddError as normalizeDddError3 } from "@mgamadeus/ddd-web/contract";
504
+ import { Download } from "lucide-react";
505
+ import { useEffect, useState as useState3 } from "react";
506
+ import { PdfPreview } from "@mgamadeus/ddd-admin-ui/files";
507
+ import { TextPreview } from "@mgamadeus/ddd-admin-ui/files";
508
+ import { useTranslate as useTranslate3 } from "@mgamadeus/ddd-admin-ui/i18n";
509
+ import { notify as notify2 } from "@mgamadeus/ddd-admin-ui/logic";
510
+ import { Button as Button2 } from "@mgamadeus/ddd-admin-ui/primitives";
511
+ import { Skeleton } from "@mgamadeus/ddd-admin-ui/primitives";
512
+ import { Fragment, jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
513
+ var saveBlob = (blob, fileName) => {
514
+ const url = URL.createObjectURL(blob);
515
+ const link = document.createElement("a");
516
+ link.href = url;
517
+ link.download = fileName;
518
+ link.rel = "noopener";
519
+ document.body.append(link);
520
+ link.click();
521
+ link.remove();
522
+ setTimeout(() => URL.revokeObjectURL(url), 1e4);
523
+ };
524
+ var SandboxFilePreview = ({ api, workspaceKey, file, loadPdfJs }) => {
525
+ const { t } = useTranslate3();
526
+ const [requestContent] = api.useSandboxFileContentMutation();
527
+ const [preview, setPreview] = useState3(null);
528
+ const [failed, setFailed] = useState3(null);
529
+ const [downloading, setDownloading] = useState3(false);
530
+ useEffect(() => {
531
+ let cancelled = false;
532
+ let objectUrl = null;
533
+ setPreview(null);
534
+ setFailed(null);
535
+ void requestContent({ workspaceKey, path: file.path, disposition: "inline" }).unwrap().then((content) => {
536
+ if (cancelled) return;
537
+ objectUrl = URL.createObjectURL(content.blob);
538
+ setPreview({ url: objectUrl, kind: sandboxPreviewKindOf(content.contentType || content.blob.type), size: content.blob.size });
539
+ }).catch((error) => {
540
+ if (!cancelled) setFailed(normalizeDddError3(error, t("The file could not be loaded.")).message);
541
+ });
542
+ return () => {
543
+ cancelled = true;
544
+ if (objectUrl) URL.revokeObjectURL(objectUrl);
545
+ };
546
+ }, [requestContent, workspaceKey, file.path, t]);
547
+ const download = async () => {
548
+ setDownloading(true);
549
+ try {
550
+ const content = await requestContent({ workspaceKey, path: file.path, disposition: "attachment" }).unwrap();
551
+ saveBlob(content.blob, content.filename ?? file.name);
552
+ } catch (error) {
553
+ notify2.error(normalizeDddError3(error, t("%name% could not be downloaded", { replacements: { name: file.name } })).message);
554
+ } finally {
555
+ setDownloading(false);
556
+ }
557
+ };
558
+ return /* @__PURE__ */ jsxs3("div", { className: "space-y-3", children: [
559
+ /* @__PURE__ */ jsxs3("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
560
+ /* @__PURE__ */ jsx3("p", { className: "min-w-0 truncate font-mono text-[13px]", title: file.path, children: file.path }),
561
+ /* @__PURE__ */ jsxs3(Button2, { type: "button", variant: "outline", size: "sm", onClick: () => void download(), disabled: downloading, children: [
562
+ /* @__PURE__ */ jsx3(Download, {}),
563
+ t("Download", { context: "action" })
564
+ ] })
565
+ ] }),
566
+ failed ? /* @__PURE__ */ jsx3("p", { className: "text-[13px] text-muted-foreground", children: failed }) : !preview ? /* @__PURE__ */ jsx3(Skeleton, { className: "h-48 w-full rounded-xl" }) : preview.kind === "image" ? /* @__PURE__ */ jsx3("img", { src: preview.url, alt: file.name, className: "max-h-[60vh] max-w-full rounded-lg border object-contain" }) : preview.kind === "pdf" && loadPdfJs ? /* @__PURE__ */ jsx3(PdfPreview, { url: preview.url, fileName: file.name, loadPdfJs }) : preview.kind === "text" ? /* @__PURE__ */ jsxs3(Fragment, { children: [
567
+ /* @__PURE__ */ jsx3(TextPreview, { url: preview.url, fileName: file.name }),
568
+ preview.size >= SANDBOX_TEXT_PREVIEW_BYTES && /* @__PURE__ */ jsx3("p", { className: "text-xs text-muted-foreground", children: t("Only the beginning of the file is shown; download it for the rest.") })
569
+ ] }) : /* @__PURE__ */ jsx3("p", { className: "text-[13px] text-muted-foreground", children: t("No preview for this type (%size%): download it to open it.", { replacements: { size: formatSandboxBytes(file.sizeBytes ?? preview.size) } }) })
570
+ ] });
571
+ };
572
+
573
+ // src/screen/SandboxDetailScreen.tsx
574
+ import { Fragment as Fragment2, jsx as jsx4, jsxs as jsxs4 } from "react/jsx-runtime";
575
+ var SANDBOX_DETAIL_TABS = [
576
+ { id: "files", label: m3("Files", { context: "sandbox-tab" }), context: "sandbox-tab" },
577
+ { id: "changes", label: m3("Unsaved changes", { context: "sandbox-tab" }), context: "sandbox-tab" },
578
+ { id: "processes", label: m3("Processes & jobs", { context: "sandbox-tab" }), context: "sandbox-tab" },
579
+ { id: "commands", label: m3("Commands", { context: "sandbox-tab" }), context: "sandbox-tab" },
580
+ { id: "conversations", label: m3("Conversations", { context: "sandbox-tab" }), context: "sandbox-tab" },
581
+ { id: "events", label: m3("Session log", { context: "sandbox-tab" }), context: "sandbox-tab" },
582
+ { id: "audit", label: m3("Audit", { context: "sandbox-tab" }), context: "sandbox-tab" }
583
+ ];
584
+ var COMMAND_LIMIT = 50;
585
+ var LOG_LIMIT = 100;
586
+ var errorText = (error, fallback) => normalizeDddError4(error, fallback).message;
587
+ var UntrustedText = ({ text, className }) => text ? /* @__PURE__ */ jsx4("pre", { className: cn2("max-h-64 overflow-auto rounded-lg bg-muted p-3 font-mono text-xs whitespace-pre-wrap break-all", className), children: text }) : null;
588
+ var FilesTab = ({ api, workspaceKey, loadPdfJs }) => {
589
+ const { t } = useTranslate4();
590
+ const [directory, setDirectory] = useState4("");
591
+ const [openFile, setOpenFile] = useState4(null);
592
+ const filesQuery = api.useSandboxFilesQuery({ workspaceKey, path: directory });
593
+ const entries = [...filesQuery.data?.entries?.elements ?? []].sort(
594
+ (a, b) => a.type === b.type ? a.name.localeCompare(b.name) : a.type === "DIRECTORY" ? -1 : b.type === "DIRECTORY" ? 1 : 0
595
+ );
596
+ const columns = [
597
+ {
598
+ id: "name",
599
+ header: t("Name", { context: "sandbox-file" }),
600
+ width: "3fr",
601
+ cell: (entry) => /* @__PURE__ */ jsxs4("span", { className: "flex min-w-0 items-center gap-2", children: [
602
+ entry.type === "DIRECTORY" ? /* @__PURE__ */ jsx4(Folder, { className: "size-4 shrink-0 text-muted-foreground" }) : /* @__PURE__ */ jsx4(File, { className: "size-4 shrink-0 text-muted-foreground" }),
603
+ /* @__PURE__ */ jsx4("span", { className: "truncate font-mono text-[13px]", children: entry.name }),
604
+ entry.type === "SYMLINK" && /* @__PURE__ */ jsx4(Badge2, { variant: "outline", children: t("Link", { context: "sandbox-file" }) })
605
+ ] })
606
+ },
607
+ { id: "size", header: t("Size", { context: "sandbox-file" }), width: "content", align: "end", cell: (entry) => entry.type === "DIRECTORY" ? /* @__PURE__ */ jsx4(EmptyValue2, {}) : formatSandboxBytes(entry.sizeBytes) },
608
+ { id: "modified", header: t("Modified", { context: "sandbox-file" }), width: "content", cell: (entry) => /* @__PURE__ */ jsx4(DateCell2, { value: entry.modifiedAt }) }
609
+ ];
610
+ return /* @__PURE__ */ jsxs4("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]", children: [
611
+ /* @__PURE__ */ jsx4(
612
+ EntityListCard2,
613
+ {
614
+ label: m3("Files", { context: "sandbox-tab" }),
615
+ labelContext: "sandbox-tab",
616
+ toolbar: /* @__PURE__ */ jsxs4("nav", { "aria-label": t("Folder path"), className: "flex min-w-0 flex-wrap items-center gap-1 px-1 text-[13px]", children: [
617
+ /* @__PURE__ */ jsx4("button", { type: "button", className: "rounded px-1 font-semibold hover:bg-muted", onClick: () => setDirectory(""), children: t("Workspace", { context: "sandbox" }) }),
618
+ sandboxPathCrumbs(directory).map((crumb) => /* @__PURE__ */ jsxs4("span", { className: "flex items-center gap-1", children: [
619
+ /* @__PURE__ */ jsx4(ChevronRight, { className: "size-3.5 text-muted-foreground" }),
620
+ /* @__PURE__ */ jsx4("button", { type: "button", className: "rounded px-1 font-mono hover:bg-muted", onClick: () => setDirectory(crumb.path), children: crumb.name })
621
+ ] }, crumb.path))
622
+ ] }),
623
+ children: /* @__PURE__ */ jsx4(
624
+ EntityListBody2,
625
+ {
626
+ displayMode: "table",
627
+ columns,
628
+ items: directory === "" ? entries : [{ name: "..", path: sandboxParentPathOf(directory), type: "DIRECTORY" }, ...entries],
629
+ getRowKey: (entry) => `${entry.type}:${entry.path}:${entry.name}`,
630
+ rowAction: (entry) => () => {
631
+ if (entry.type === "DIRECTORY") {
632
+ setDirectory(entry.path);
633
+ setOpenFile(null);
634
+ } else {
635
+ setOpenFile(entry);
636
+ }
637
+ },
638
+ isLoading: filesQuery.isLoading,
639
+ emptyMessage: t("This folder is empty."),
640
+ loadingMessage: t("Loading files"),
641
+ error: filesQuery.isError ? errorText(filesQuery.error, t("The files could not be loaded.")) : void 0
642
+ }
643
+ )
644
+ }
645
+ ),
646
+ /* @__PURE__ */ jsx4(Card, { children: /* @__PURE__ */ jsx4(CardContent, { className: "pt-6", children: openFile ? /* @__PURE__ */ jsx4(SandboxFilePreview, { api, workspaceKey, file: openFile, loadPdfJs }) : /* @__PURE__ */ jsx4("p", { className: "py-10 text-center text-[13px] text-muted-foreground", children: t("Pick a file to see it. Files are shown read only.") }) }) })
647
+ ] });
648
+ };
649
+ var ChangesTab = ({ api, workspaceKey }) => {
650
+ const { t } = useTranslate4();
651
+ const statusQuery = api.useSandboxDriveStatusQuery({ workspaceKey });
652
+ const status = statusQuery.data?.driveStatus;
653
+ const columns = [
654
+ {
655
+ id: "type",
656
+ header: t("Change", { context: "sandbox-change" }),
657
+ width: "content",
658
+ cell: (change) => /* @__PURE__ */ jsx4(Badge2, { variant: "outline", children: SANDBOX_CHANGE_LABELS[change.changeType] ? t(SANDBOX_CHANGE_LABELS[change.changeType] ?? "", { context: "sandbox-change" }) : change.changeType })
659
+ },
660
+ {
661
+ id: "path",
662
+ header: t("Path", { context: "sandbox-change" }),
663
+ width: "3fr",
664
+ cell: (change) => /* @__PURE__ */ jsxs4("span", { className: "min-w-0 font-mono text-[13px]", children: [
665
+ change.previousPath && /* @__PURE__ */ jsxs4("span", { className: "block truncate text-muted-foreground", children: [
666
+ change.previousPath,
667
+ " \u2192"
668
+ ] }),
669
+ /* @__PURE__ */ jsx4("span", { className: "block truncate", children: change.path })
670
+ ] })
671
+ },
672
+ { id: "size", header: t("Size", { context: "sandbox-file" }), width: "content", align: "end", cell: (change) => formatSandboxBytes(change.sizeBytes) }
673
+ ];
674
+ if (status && !status.isDriveWorkspace) {
675
+ return /* @__PURE__ */ jsx4(StatusCallout2, { tone: "info", title: t("No drive in this workspace"), description: t("Its files are not synced with a drive, so nothing is pending.") });
676
+ }
677
+ return /* @__PURE__ */ jsx4(
678
+ EntityListCard2,
679
+ {
680
+ label: m3("Unsaved changes", { context: "sandbox-tab" }),
681
+ labelContext: "sandbox-tab",
682
+ toolbar: status ? /* @__PURE__ */ jsxs4("p", { className: "px-1 text-[12.5px] text-muted-foreground", children: [
683
+ t("{count, plural, one {# change not yet in the drive} other {# changes not yet in the drive}}", { count: status.pendingChangeCount }),
684
+ status.lastCommittedAt && /* @__PURE__ */ jsxs4(Fragment2, { children: [
685
+ " \xB7 ",
686
+ t("Last saved"),
687
+ " ",
688
+ /* @__PURE__ */ jsx4(DateCell2, { value: status.lastCommittedAt })
689
+ ] })
690
+ ] }) : void 0,
691
+ children: /* @__PURE__ */ jsx4(
692
+ EntityListBody2,
693
+ {
694
+ displayMode: "table",
695
+ columns,
696
+ items: status?.changes?.elements ?? [],
697
+ getRowKey: (change) => `${change.changeType}:${change.previousPath ?? ""}:${change.path}`,
698
+ isLoading: statusQuery.isLoading,
699
+ emptyMessage: t("Everything is saved in the drive."),
700
+ loadingMessage: t("Loading the changes"),
701
+ error: statusQuery.isError ? errorText(statusQuery.error, t("The changes could not be loaded.")) : void 0
702
+ }
703
+ )
704
+ }
705
+ );
706
+ };
707
+ var ProcessesTab = ({
708
+ api,
709
+ workspace,
710
+ onKill,
711
+ killDisabled
712
+ }) => {
713
+ const { t } = useTranslate4();
714
+ const processesQuery = api.useSandboxProcessesQuery({ workspaceKey: workspace.workspaceKey });
715
+ const columns = [
716
+ { id: "pid", header: "PID", width: "content", cell: (process) => /* @__PURE__ */ jsx4("span", { className: "font-mono text-xs", children: process.pid }) },
717
+ { id: "command", header: t("Command", { context: "sandbox" }), width: "3fr", cell: (process) => /* @__PURE__ */ jsx4("span", { className: "block truncate font-mono text-xs", title: process.command, children: process.command }) },
718
+ { id: "job", header: t("Job", { context: "sandbox" }), width: "content", cell: (process) => process.jobId ? /* @__PURE__ */ jsx4("span", { className: "font-mono text-xs", children: process.jobId }) : /* @__PURE__ */ jsx4(EmptyValue2, {}) },
719
+ { id: "started", header: t("Started", { context: "sandbox" }), width: "content", cell: (process) => /* @__PURE__ */ jsx4(DateCell2, { value: process.startedAt }) },
720
+ { id: "cpu", header: "CPU", width: "content", align: "end", cell: (process) => formatSandboxDuration(process.cpuSeconds === null || process.cpuSeconds === void 0 ? null : process.cpuSeconds * 1e3) },
721
+ { id: "memory", header: t("Memory", { context: "sandbox" }), width: "content", align: "end", cell: (process) => formatSandboxBytes(process.rssBytes) },
722
+ {
723
+ id: "actions",
724
+ header: /* @__PURE__ */ jsx4("span", { className: "sr-only", children: t("Actions", { context: "table-column" }) }),
725
+ width: "content",
726
+ pin: "end",
727
+ cell: (process) => process.jobId ? /* @__PURE__ */ jsxs4(
728
+ Button3,
729
+ {
730
+ type: "button",
731
+ variant: "ghost",
732
+ size: "sm",
733
+ className: "text-destructive hover:text-destructive",
734
+ disabled: killDisabled,
735
+ onClick: () => process.jobId && onKill(process.jobId),
736
+ children: [
737
+ /* @__PURE__ */ jsx4(OctagonX, {}),
738
+ t("Kill job", { context: "sandbox-action" })
739
+ ]
740
+ }
741
+ ) : null
742
+ }
743
+ ];
744
+ return /* @__PURE__ */ jsx4(EntityListCard2, { label: m3("Processes & jobs", { context: "sandbox-tab" }), labelContext: "sandbox-tab", children: /* @__PURE__ */ jsx4(
745
+ EntityListBody2,
746
+ {
747
+ displayMode: "table",
748
+ columns,
749
+ items: processesQuery.data?.processes?.elements ?? [],
750
+ getRowKey: (process) => String(process.pid),
751
+ isLoading: processesQuery.isLoading,
752
+ emptyMessage: workspace.state === "OFFLOADED" ? t("No session: nothing runs.") : t("Nothing is running."),
753
+ loadingMessage: t("Loading the processes"),
754
+ error: processesQuery.isError ? errorText(processesQuery.error, t("The processes could not be loaded.")) : void 0
755
+ }
756
+ ) });
757
+ };
758
+ var CommandsTab = ({ api, workspaceKey }) => {
759
+ const { t } = useTranslate4();
760
+ const commandsQuery = api.useSandboxCommandsQuery({ workspaceKey, limit: COMMAND_LIMIT });
761
+ const commands = commandsQuery.data?.commands?.elements ?? [];
762
+ if (commandsQuery.isLoading) return /* @__PURE__ */ jsx4(Skeleton2, { className: "h-48 w-full rounded-xl" });
763
+ if (commandsQuery.isError) return /* @__PURE__ */ jsx4(StatusCallout2, { tone: "destructive", title: t("The commands could not be loaded."), description: errorText(commandsQuery.error, "") });
764
+ if (commands.length === 0) return /* @__PURE__ */ jsx4("p", { className: "py-10 text-center text-[13px] text-muted-foreground", children: t("No command ran in this session yet.") });
765
+ return /* @__PURE__ */ jsx4("ol", { className: "space-y-3", children: commands.map((command) => /* @__PURE__ */ jsxs4("li", { className: "surface space-y-2 rounded-2xl p-4", children: [
766
+ /* @__PURE__ */ jsxs4("div", { className: "flex flex-wrap items-center gap-2 text-[12.5px]", children: [
767
+ /* @__PURE__ */ jsx4(StatusBadge2, { value: sandboxCommandStateOf(command), map: SANDBOX_COMMAND_STATE }),
768
+ sandboxCommandStateOf(command) === "EXITED" && command.exitCode !== null && command.exitCode !== void 0 && /* @__PURE__ */ jsx4(Badge2, { variant: command.exitCode === 0 ? "outline" : "destructive", className: "font-mono", children: t("exit %code%", { context: "sandbox-command", replacements: { code: String(command.exitCode) } }) }),
769
+ /* @__PURE__ */ jsxs4("span", { className: "text-muted-foreground", children: [
770
+ "#",
771
+ command.seq
772
+ ] }),
773
+ /* @__PURE__ */ jsx4(DateCell2, { value: command.startedAt }),
774
+ /* @__PURE__ */ jsx4("span", { className: "text-muted-foreground", children: formatSandboxDuration(command.durationMs) }),
775
+ command.jobId && /* @__PURE__ */ jsx4("span", { className: "font-mono text-xs text-muted-foreground", children: t("job %id%", { replacements: { id: command.jobId } }) }),
776
+ command.isTruncated && /* @__PURE__ */ jsx4(Badge2, { variant: "outline", children: t("Output cut", { context: "sandbox-command" }) })
777
+ ] }),
778
+ /* @__PURE__ */ jsx4(UntrustedText, { text: command.command, className: "bg-card" }),
779
+ command.stdoutTail && /* @__PURE__ */ jsxs4("details", { children: [
780
+ /* @__PURE__ */ jsx4("summary", { className: "cursor-pointer text-xs font-semibold text-muted-foreground", children: t("Output", { context: "sandbox-command" }) }),
781
+ /* @__PURE__ */ jsx4(UntrustedText, { text: command.stdoutTail, className: "mt-1" })
782
+ ] }),
783
+ command.stderrTail && /* @__PURE__ */ jsxs4("details", { open: command.exitCode !== null && command.exitCode !== void 0 && command.exitCode !== 0, children: [
784
+ /* @__PURE__ */ jsx4("summary", { className: "cursor-pointer text-xs font-semibold text-destructive", children: t("Errors", { context: "sandbox-command" }) }),
785
+ /* @__PURE__ */ jsx4(UntrustedText, { text: command.stderrTail, className: "mt-1" })
786
+ ] })
787
+ ] }, command.seq)) });
788
+ };
789
+ var ConversationsTab = ({
790
+ api,
791
+ workspaceKey,
792
+ buildConversationHref
793
+ }) => {
794
+ const { t } = useTranslate4();
795
+ const Link = useLinkComponent();
796
+ const conversationsQuery = api.useSandboxConversationsQuery({ workspaceKey, limit: LOG_LIMIT });
797
+ const columns = [
798
+ {
799
+ id: "id",
800
+ header: t("Conversation"),
801
+ width: "content",
802
+ cell: (conversation) => {
803
+ const href = buildConversationHref?.(conversation) ?? null;
804
+ return href ? /* @__PURE__ */ jsxs4(Link, { href, className: "flex items-center gap-1 font-mono text-[13px] text-primary-emphasis underline-offset-2 hover:underline", children: [
805
+ /* @__PURE__ */ jsx4(Link2, { className: "size-3.5" }),
806
+ "#",
807
+ conversation.conversationId
808
+ ] }) : /* @__PURE__ */ jsxs4("span", { className: "font-mono text-[13px]", children: [
809
+ "#",
810
+ conversation.conversationId
811
+ ] });
812
+ }
813
+ },
814
+ { id: "purpose", header: t("Purpose", { context: "sandbox-conversation" }), width: "2fr", cell: (conversation) => conversation.purposeName ?? /* @__PURE__ */ jsx4(EmptyValue2, {}) },
815
+ { id: "state", header: t("State", { context: "sandbox" }), width: "content", cell: (conversation) => conversation.runState ? /* @__PURE__ */ jsx4(Badge2, { variant: "outline", children: conversation.runState }) : /* @__PURE__ */ jsx4(EmptyValue2, {}) },
816
+ { id: "updated", header: t("Last change"), width: "content", cell: (conversation) => /* @__PURE__ */ jsx4(DateCell2, { value: conversation.updatedAt }) }
817
+ ];
818
+ return /* @__PURE__ */ jsx4(EntityListCard2, { label: m3("Conversations", { context: "sandbox-tab" }), labelContext: "sandbox-tab", children: /* @__PURE__ */ jsx4(
819
+ EntityListBody2,
820
+ {
821
+ displayMode: "table",
822
+ columns,
823
+ items: conversationsQuery.data?.conversations?.elements ?? [],
824
+ getRowKey: (conversation) => String(conversation.conversationId),
825
+ isLoading: conversationsQuery.isLoading,
826
+ emptyMessage: t("No conversation used this workspace yet."),
827
+ loadingMessage: t("Loading the conversations"),
828
+ error: conversationsQuery.isError ? errorText(conversationsQuery.error, t("The conversations could not be loaded.")) : void 0
829
+ }
830
+ ) });
831
+ };
832
+ var EventsTab = ({ api, workspaceKey }) => {
833
+ const { t } = useTranslate4();
834
+ const eventsQuery = api.useSandboxSessionEventsQuery({ workspaceKey, limit: LOG_LIMIT });
835
+ const events = eventsQuery.data?.sessionEvents?.elements ?? [];
836
+ if (eventsQuery.isLoading) return /* @__PURE__ */ jsx4(Skeleton2, { className: "h-40 w-full rounded-xl" });
837
+ if (eventsQuery.isError) return /* @__PURE__ */ jsx4(StatusCallout2, { tone: "destructive", title: t("The session log could not be loaded."), description: errorText(eventsQuery.error, "") });
838
+ if (events.length === 0) return /* @__PURE__ */ jsx4("p", { className: "py-10 text-center text-[13px] text-muted-foreground", children: t("The session log is empty.") });
839
+ return /* @__PURE__ */ jsx4("ol", { className: "surface space-y-3 rounded-2xl p-4", children: events.map((event, index) => {
840
+ const Icon = sessionEventIconOf(event.type);
841
+ return /* @__PURE__ */ jsxs4("li", { className: "flex gap-3 text-[13px]", children: [
842
+ /* @__PURE__ */ jsx4(Icon, { className: "mt-0.5 size-4 shrink-0 text-muted-foreground" }),
843
+ /* @__PURE__ */ jsxs4("div", { className: "min-w-0", children: [
844
+ /* @__PURE__ */ jsxs4("p", { children: [
845
+ /* @__PURE__ */ jsx4("span", { className: "font-mono font-semibold", children: event.type }),
846
+ " \xB7 ",
847
+ /* @__PURE__ */ jsx4(DateCell2, { value: event.occurredAt })
848
+ ] }),
849
+ event.detail && /* @__PURE__ */ jsx4("p", { className: "break-words text-muted-foreground", children: event.detail })
850
+ ] })
851
+ ] }, `${event.occurredAt ?? ""}-${index}`);
852
+ }) });
853
+ };
854
+ var AuditTab = ({ api, workspaceKey }) => {
855
+ const { t } = useTranslate4();
856
+ const auditQuery = api.useSandboxActionLogQuery({ workspaceKey, limit: LOG_LIMIT });
857
+ const columns = [
858
+ { id: "time", header: t("When", { context: "sandbox-audit" }), width: "content", cell: (entry) => /* @__PURE__ */ jsx4(DateCell2, { value: entry.changeHistory?.createdTime ?? null }) },
859
+ {
860
+ id: "action",
861
+ header: t("Action", { context: "sandbox-audit" }),
862
+ width: "content",
863
+ cell: (entry) => /* @__PURE__ */ jsx4("span", { children: entry.action === "KILL_JOB" && entry.jobId ? t("Kill job %id%", { context: "sandbox-action", replacements: { id: entry.jobId } }) : entry.action && SANDBOX_ACTION_LABELS[entry.action] ? t(SANDBOX_ACTION_LABELS[entry.action] ?? "", { context: "sandbox-action" }) : entry.action ?? "\u2014" })
864
+ },
865
+ { id: "outcome", header: t("Outcome", { context: "sandbox-audit" }), width: "content", cell: (entry) => /* @__PURE__ */ jsx4(StatusBadge2, { value: entry.outcome ?? null, map: SANDBOX_ACTION_OUTCOME }) },
866
+ { id: "actor", header: t("By", { context: "sandbox-audit" }), width: "content", cell: (entry) => entry.actorAccountId ? `#${entry.actorAccountId}` : /* @__PURE__ */ jsx4(EmptyValue2, {}) },
867
+ {
868
+ id: "reason",
869
+ header: t("Reason", { context: "sandbox-force" }),
870
+ width: "2fr",
871
+ cell: (entry) => /* @__PURE__ */ jsxs4("span", { className: "min-w-0 text-[13px]", children: [
872
+ entry.forced && /* @__PURE__ */ jsx4(Badge2, { variant: "destructive", className: "mr-1", children: t("Forced", { context: "sandbox-audit" }) }),
873
+ entry.reason ?? (entry.forced ? "" : /* @__PURE__ */ jsx4(EmptyValue2, {})),
874
+ entry.outcomeDetail && /* @__PURE__ */ jsx4("span", { className: "block truncate text-xs text-muted-foreground", title: entry.outcomeDetail, children: entry.outcomeDetail })
875
+ ] })
876
+ }
877
+ ];
878
+ return /* @__PURE__ */ jsx4(EntityListCard2, { label: m3("Audit", { context: "sandbox-tab" }), labelContext: "sandbox-tab", children: /* @__PURE__ */ jsx4(
879
+ EntityListBody2,
880
+ {
881
+ displayMode: "table",
882
+ columns,
883
+ items: auditQuery.data?.actionLogEntries?.elements ?? [],
884
+ getRowKey: (entry) => String(entry.id ?? `${entry.action}-${entry.changeHistory?.createdTime}`),
885
+ isLoading: auditQuery.isLoading,
886
+ emptyMessage: t("No action on this workspace yet."),
887
+ loadingMessage: t("Loading the audit"),
888
+ error: auditQuery.isError ? errorText(auditQuery.error, t("The audit could not be loaded.")) : void 0
889
+ }
890
+ ) });
891
+ };
892
+ var SandboxDetailScreen = ({
893
+ api,
894
+ workspaceKey,
895
+ tab: controlledTab,
896
+ onTabChange,
897
+ backLink,
898
+ headerActions,
899
+ buildConversationHref,
900
+ loadPdfJs
901
+ }) => {
902
+ const { t } = useTranslate4();
903
+ const workspaceQuery = api.useSandboxQuery({ workspaceKey });
904
+ const actions = useSandboxActions(api);
905
+ const [ownTab, setOwnTab] = useState4("files");
906
+ const tab = controlledTab ?? ownTab;
907
+ const selectTab = (next) => {
908
+ if (onTabChange) onTabChange(next);
909
+ else setOwnTab(next);
910
+ };
911
+ const workspace = workspaceQuery.data?.workspace;
912
+ if (workspaceQuery.isLoading) {
913
+ return /* @__PURE__ */ jsxs4("div", { className: "space-y-4", children: [
914
+ /* @__PURE__ */ jsx4(Skeleton2, { className: "h-12 w-80" }),
915
+ /* @__PURE__ */ jsx4(Skeleton2, { className: "h-32 w-full rounded-2xl" })
916
+ ] });
917
+ }
918
+ if (!workspace) {
919
+ return /* @__PURE__ */ jsxs4("div", { className: "space-y-4", children: [
920
+ /* @__PURE__ */ jsx4(PageHeader2, { title: workspaceKey, leading: backLink }),
921
+ /* @__PURE__ */ jsx4(
922
+ StatusCallout2,
923
+ {
924
+ tone: "destructive",
925
+ title: t("This workspace was not found."),
926
+ description: workspaceQuery.isError ? errorText(workspaceQuery.error, t("The workspace could not be loaded.")) : void 0
927
+ }
928
+ )
929
+ ] });
930
+ }
931
+ const hasSession = workspace.state !== "OFFLOADED";
932
+ const busy = actions.isPending;
933
+ return /* @__PURE__ */ jsxs4("div", { className: "space-y-6", children: [
934
+ /* @__PURE__ */ jsx4(
935
+ PageHeader2,
936
+ {
937
+ leading: backLink,
938
+ title: sandboxNameOf(workspace),
939
+ description: /* @__PURE__ */ jsx4("span", { className: "font-mono text-xs", children: workspace.workspaceKey }),
940
+ actions: /* @__PURE__ */ jsxs4("div", { className: "flex flex-wrap items-center gap-2", children: [
941
+ headerActions,
942
+ /* @__PURE__ */ jsxs4(Button3, { type: "button", variant: "outline", onClick: () => void workspaceQuery.refetch?.(), disabled: workspaceQuery.isFetching, children: [
943
+ /* @__PURE__ */ jsx4(RefreshCw2, { className: cn2(workspaceQuery.isFetching && "animate-spin") }),
944
+ t("Refresh")
945
+ ] }),
946
+ /* @__PURE__ */ jsxs4(Button3, { type: "button", variant: "outline", disabled: busy, onClick: () => void actions.run({ kind: "start", workspace }), children: [
947
+ /* @__PURE__ */ jsx4(Play3, {}),
948
+ hasSession ? t("Warm up session") : t("Start session", { context: "sandbox-action" })
949
+ ] }),
950
+ /* @__PURE__ */ jsxs4(Button3, { type: "button", variant: "outline", disabled: busy || !hasSession, onClick: () => void actions.run({ kind: "offload", workspace }), children: [
951
+ /* @__PURE__ */ jsx4(Archive3, {}),
952
+ t("Offload", { context: "sandbox-action" })
953
+ ] }),
954
+ /* @__PURE__ */ jsxs4(Button3, { type: "button", variant: "outline", disabled: busy || !hasSession, onClick: () => void actions.run({ kind: "end", workspace }), children: [
955
+ /* @__PURE__ */ jsx4(Power2, {}),
956
+ t("End session", { context: "sandbox-action" })
957
+ ] }),
958
+ /* @__PURE__ */ jsxs4(
959
+ Button3,
960
+ {
961
+ type: "button",
962
+ variant: "outline",
963
+ className: "border-destructive/40 text-destructive hover:bg-destructive/10 hover:text-destructive",
964
+ disabled: busy,
965
+ onClick: () => void actions.run({ kind: "reset", workspace }),
966
+ children: [
967
+ /* @__PURE__ */ jsx4(RotateCcw, {}),
968
+ t("Reset workspace", { context: "sandbox-action" })
969
+ ]
970
+ }
971
+ )
972
+ ] })
973
+ }
974
+ ),
975
+ workspace.hasLiveTurn && /* @__PURE__ */ jsx4(
976
+ StatusCallout2,
977
+ {
978
+ tone: "warning",
979
+ title: t("A turn is running on this space"),
980
+ description: t("Actions now can break the agent\u2019s work; each asks for a reason, which is kept in the audit.")
981
+ }
982
+ ),
983
+ /* @__PURE__ */ jsx4(Card, { children: /* @__PURE__ */ jsx4(CardContent, { className: "pt-6", children: /* @__PURE__ */ jsx4(
984
+ DefinitionList,
985
+ {
986
+ items: [
987
+ { id: "state", label: t("State", { context: "sandbox" }), value: /* @__PURE__ */ jsx4(StatusBadge2, { value: workspace.state, map: SANDBOX_STATE }) },
988
+ { id: "activity", label: t("Last activity"), value: /* @__PURE__ */ jsx4(DateCell2, { value: workspace.lastActivityAt }) },
989
+ { id: "disk", label: t("Disk", { context: "sandbox" }), value: /* @__PURE__ */ jsx4(SandboxUsageBar, { used: workspace.diskUsedBytes, limit: workspace.diskQuotaBytes }) },
990
+ {
991
+ id: "memory",
992
+ label: t("Memory", { context: "sandbox" }),
993
+ value: /* @__PURE__ */ jsx4(SandboxUsageBar, { used: workspace.memoryBytes, limit: workspace.memoryLimitBytes, peak: workspace.memoryPeakBytes })
994
+ },
995
+ { id: "mount", label: t("Mount", { context: "sandbox" }), value: /* @__PURE__ */ jsx4(SandboxMountMode, { workspace }) },
996
+ { id: "pod", label: t("Runner", { context: "sandbox" }), value: workspace.runnerPod ? /* @__PURE__ */ jsx4("span", { className: "font-mono text-xs", children: workspace.runnerPod }) : null },
997
+ { id: "owner", label: t("Owner", { context: "sandbox" }), value: workspace.ownerDisplayName },
998
+ { id: "jobs", label: t("Running jobs"), value: workspace.runningJobCount ?? null },
999
+ { id: "conversations", label: t("Conversations"), value: workspace.conversationCount ?? null }
1000
+ ]
1001
+ }
1002
+ ) }) }),
1003
+ /* @__PURE__ */ jsxs4("section", { className: "space-y-4", children: [
1004
+ /* @__PURE__ */ jsx4(
1005
+ SectionHeader,
1006
+ {
1007
+ title: t(SANDBOX_DETAIL_TABS.find((item) => item.id === tab)?.label ?? "", { context: "sandbox-tab" }),
1008
+ tabs: SANDBOX_DETAIL_TABS,
1009
+ activeTab: tab,
1010
+ onTabSelect: (id) => selectTab(id),
1011
+ tabsLabel: t("Workspace views")
1012
+ }
1013
+ ),
1014
+ tab === "files" && /* @__PURE__ */ jsx4(FilesTab, { api, workspaceKey, loadPdfJs }),
1015
+ tab === "changes" && /* @__PURE__ */ jsx4(ChangesTab, { api, workspaceKey }),
1016
+ tab === "processes" && /* @__PURE__ */ jsx4(ProcessesTab, { api, workspace, killDisabled: busy, onKill: (jobId) => void actions.run({ kind: "kill", workspace, jobId }) }),
1017
+ tab === "commands" && /* @__PURE__ */ jsx4(CommandsTab, { api, workspaceKey }),
1018
+ tab === "conversations" && /* @__PURE__ */ jsx4(ConversationsTab, { api, workspaceKey, buildConversationHref }),
1019
+ tab === "events" && /* @__PURE__ */ jsx4(EventsTab, { api, workspaceKey }),
1020
+ tab === "audit" && /* @__PURE__ */ jsx4(AuditTab, { api, workspaceKey })
1021
+ ] }),
1022
+ actions.dialog
1023
+ ] });
1024
+ };
1025
+ export {
1026
+ SANDBOX_ACTION_LABELS,
1027
+ SANDBOX_ACTION_LABEL_CONTEXT,
1028
+ SANDBOX_ACTION_OUTCOME,
1029
+ SANDBOX_CHANGE_LABELS,
1030
+ SANDBOX_CHANGE_LABEL_CONTEXT,
1031
+ SANDBOX_COMMAND_STATE,
1032
+ SANDBOX_DETAIL_TABS,
1033
+ SANDBOX_STATE,
1034
+ SANDBOX_TEXT_PREVIEW_BYTES,
1035
+ SandboxActionsMenu,
1036
+ SandboxDetailScreen,
1037
+ SandboxFilePreview,
1038
+ SandboxMountMode,
1039
+ SandboxUsageBar,
1040
+ SandboxesScreen,
1041
+ formatSandboxBytes,
1042
+ formatSandboxDuration,
1043
+ isSandboxTurnRunningRefusal,
1044
+ sandboxCommandStateOf,
1045
+ sandboxNameOf,
1046
+ sandboxParentPathOf,
1047
+ sandboxPathCrumbs,
1048
+ sandboxPreviewKindOf,
1049
+ sandboxResetPhraseOf,
1050
+ usagePercentOf,
1051
+ useSandboxActions
1052
+ };
1053
+ //# sourceMappingURL=index.js.map