@hanzo/build 0.2.124 → 0.2.125

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.
@@ -31,6 +31,38 @@ export declare function ports(t: Target, id: string): Promise<Port[]>;
31
31
  * ticket that sets the preview's cookie and lands on its root.
32
32
  */
33
33
  export declare function preview(t: Target, id: string, port: number): Promise<string>;
34
+ /**
35
+ * Where a server started from the Preview keeps its process group and its output:
36
+ * under /tmp, as a run keeps its own files out of the checkout it commits.
37
+ */
38
+ export declare const SERVE_DIR = "/tmp/hanzo-preview";
39
+ /**
40
+ * The shell that starts the app's server for the Preview, detached in a session of
41
+ * its own so it outlives the one command that started it. A server a run starts
42
+ * ends with the run (the agent's harness takes it down), so the Preview starts one
43
+ * again. It runs the codebase's start command when its environment names one ($1),
44
+ * else the package's `dev` script, or `start`, by the package manager its lockfile
45
+ * names, with the environment's secrets sourced as a run sources them (cloud
46
+ * apps/coding envPath). A server this started before is stopped first, its whole
47
+ * group. It prints what it started, or exits 3 saying why nothing could be.
48
+ */
49
+ export declare const SERVE: string;
50
+ /** Whether the server the Preview started still runs (`up` or `down`), then its output's last lines. */
51
+ export declare const SERVED: string;
52
+ /**
53
+ * Start the app's server in the sandbox, detached, and answer the command it runs:
54
+ * `start` when the codebase's environment names one, else its package's dev script.
55
+ * A parked sandbox is resumed first.
56
+ */
57
+ export declare function serve(t: Target, id: string, start?: string): Promise<string>;
58
+ export interface Served {
59
+ /** Whether the server the Preview started still runs. */
60
+ up: boolean;
61
+ /** The last lines it wrote. */
62
+ log: string;
63
+ }
64
+ /** Whether the server the Preview started still runs, and what it last wrote. */
65
+ export declare function served(t: Target, id: string): Promise<Served>;
34
66
  export interface Node {
35
67
  /** The resolved path inside the sandbox. */
36
68
  path: string;
@@ -10,6 +10,7 @@
10
10
  * POST /v1/sandbox/{id}/{screen|terminal}/ticket one ticket, spent when the page's socket opens (30 s)
11
11
  * GET /v1/sandbox/{id}/ports what listens in it, each with its preview host
12
12
  * POST /v1/sandbox/{id}/preview {port} an address that opens that port in a browser
13
+ * POST /v1/sandbox/{id}/exec {argv, timeoutSec} one command in /work: {exitCode, stdout, stderr}
13
14
  * POST /v1/sandbox/read {id, path} a directory's names, or a file's bytes
14
15
  *
15
16
  * A door or a preview asked of a sandbox that stopped as it was asked is 409: it
@@ -111,6 +112,81 @@ export async function preview(t, id, port) {
111
112
  throw new Refusal(502, phrase('The sandbox answered with no address to open'));
112
113
  return url.href;
113
114
  }
115
+ /**
116
+ * Where a server started from the Preview keeps its process group and its output:
117
+ * under /tmp, as a run keeps its own files out of the checkout it commits.
118
+ */
119
+ export const SERVE_DIR = '/tmp/hanzo-preview';
120
+ /**
121
+ * The shell that starts the app's server for the Preview, detached in a session of
122
+ * its own so it outlives the one command that started it. A server a run starts
123
+ * ends with the run (the agent's harness takes it down), so the Preview starts one
124
+ * again. It runs the codebase's start command when its environment names one ($1),
125
+ * else the package's `dev` script, or `start`, by the package manager its lockfile
126
+ * names, with the environment's secrets sourced as a run sources them (cloud
127
+ * apps/coding envPath). A server this started before is stopped first, its whole
128
+ * group. It prints what it started, or exits 3 saying why nothing could be.
129
+ */
130
+ export const SERVE = [
131
+ `d=${SERVE_DIR}`,
132
+ 'mkdir -p "$d"',
133
+ 'if [ -f /tmp/hanzo-run/env ]; then . /tmp/hanzo-run/env; fi',
134
+ 'cmd=$1',
135
+ 'if [ -z "$cmd" ]; then',
136
+ ' [ -f package.json ] || { echo no-package; exit 3; }',
137
+ ' if [ -f pnpm-lock.yaml ]; then pm=pnpm; elif [ -f yarn.lock ]; then pm=yarn; elif [ -f bun.lock ] || [ -f bun.lockb ]; then pm=bun; else pm=npm; fi',
138
+ ` run=$(node -e 'const s=require("./package.json").scripts||{};process.stdout.write(s.dev?"dev":s.start?"start":"")' 2>/dev/null)`,
139
+ ' [ -n "$run" ] || { echo no-script; exit 3; }',
140
+ ' cmd="$pm run $run"',
141
+ 'fi',
142
+ 'old=$(cat "$d/pid" 2>/dev/null)',
143
+ 'if [ -n "$old" ] && kill -0 "$old" 2>/dev/null; then kill -TERM "-$old" 2>/dev/null || kill -TERM "$old" 2>/dev/null; sleep 1; fi',
144
+ 'if command -v setsid >/dev/null 2>&1; then setsid nohup sh -c "$cmd" </dev/null >"$d/log" 2>&1 & else nohup sh -c "$cmd" </dev/null >"$d/log" 2>&1 & fi',
145
+ 'echo $! >"$d/pid"',
146
+ 'printf %s "$cmd"',
147
+ ].join('\n');
148
+ /** Whether the server the Preview started still runs (`up` or `down`), then its output's last lines. */
149
+ export const SERVED = [
150
+ `d=${SERVE_DIR}`,
151
+ 'p=$(cat "$d/pid" 2>/dev/null)',
152
+ 'if [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then echo up; else echo down; fi',
153
+ 'tail -n 40 "$d/log" 2>/dev/null',
154
+ ].join('\n');
155
+ /** Why there was nothing to start, as SERVE says it. */
156
+ const UNSTARTED = {
157
+ 'no-package': phrase('This checkout has no package.json to start. Set a start command in its Environment.'),
158
+ 'no-script': phrase('Its package.json has no dev or start script. Set a start command in its Environment.'),
159
+ };
160
+ /** One command in the sandbox, as an argument vector: its exit code and output. A failed command is an answer, not a refusal. */
161
+ async function exec(t, id, argv, timeoutSec) {
162
+ const r = (await call(t, 'POST', `/v1/sandbox/${seg(id)}/exec`, { argv, timeoutSec })) ?? {};
163
+ return {
164
+ code: typeof r.exitCode === 'number' ? r.exitCode : -1,
165
+ out: typeof r.stdout === 'string' ? r.stdout : '',
166
+ err: typeof r.stderr === 'string' ? r.stderr : '',
167
+ };
168
+ }
169
+ /**
170
+ * Start the app's server in the sandbox, detached, and answer the command it runs:
171
+ * `start` when the codebase's environment names one, else its package's dev script.
172
+ * A parked sandbox is resumed first.
173
+ */
174
+ export async function serve(t, id, start = '') {
175
+ const r = await running(t, id, () => exec(t, id, ['sh', '-c', SERVE, 'sh', start.trim()], 30));
176
+ const said = r.out.trim();
177
+ if (r.code === 0 && said)
178
+ return said;
179
+ const why = UNSTARTED[said];
180
+ if (r.code === 3 && why)
181
+ throw new Refusal(422, why);
182
+ throw new Refusal(502, r.err.trim().split('\n').pop() || phrase('The dev server could not be started.'));
183
+ }
184
+ /** Whether the server the Preview started still runs, and what it last wrote. */
185
+ export async function served(t, id) {
186
+ const r = await exec(t, id, ['sh', '-c', SERVED], 10);
187
+ const [first = '', ...rest] = r.out.split('\n');
188
+ return { up: first.trim() === 'up', log: rest.join('\n').trimEnd() };
189
+ }
114
190
  /** What a file shows at most. */
115
191
  const CAP = 1 << 20;
116
192
  /** One path in the sandbox, relative to its working directory. */
package/lib/desk.js CHANGED
@@ -15,11 +15,12 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
15
15
  import { SizableText, XStack, YStack } from '@hanzo/gui';
16
16
  import { useI18n } from '@hanzo/i18n/react';
17
17
  import { ChevronRight, ExternalLink, Folder, GitBranch, GitPullRequest, Globe, Info, Laptop, Maximize2, MoreHorizontal, RefreshCcw, Square, SquareTerminal, X } from '@hanzogui/lucide-icons-2';
18
- import { Button, DropdownMenu, Input, Switch } from '@hanzo/ui';
18
+ import { Button, DropdownMenu, Switch } from '@hanzo/ui';
19
19
  import { PreviewFrame } from '@hanzo/ui/agents';
20
20
  import { useCallback, useEffect, useRef, useState } from 'react';
21
21
  import { read as readChanges } from './api/changes.js';
22
- import { park, ports as listening, preview, sandbox as look, wake } from './api/sandbox.js';
22
+ import { read as readEnvironment } from './api/environment.js';
23
+ import { park, ports as listening, preview, sandbox as look, serve, served, wake } from './api/sandbox.js';
23
24
  import { cards, failure, shell, steps } from './api/turn.js';
24
25
  import { useKept, useRead } from './data.js';
25
26
  import { Door } from './door.js';
@@ -53,7 +54,12 @@ export function Desk({ id, repo, branch, base, environment, mode, pr, title, pro
53
54
  const held = box.value?.state ?? '';
54
55
  const environ = () => side.open({ kind: 'environment', title: say('Environment') });
55
56
  const kinds = [
56
- { id: 'preview', label: say('Preview'), bleed: true, render: () => _jsx(Browser, { sandbox: sandbox, held: held, site: site, live: live }, published) },
57
+ {
58
+ id: 'preview',
59
+ label: say('Preview'),
60
+ bleed: true,
61
+ render: () => _jsx(Browser, { sandbox: sandbox, held: held, site: site, live: live, repo: repo, onEnvironment: environ }, published),
62
+ },
57
63
  {
58
64
  id: 'artifacts',
59
65
  label: say('Artifacts'),
@@ -176,7 +182,7 @@ const SAYS = {
176
182
  * looking. A preview that lost its sandbox (409) is opened again, at most twice
177
183
  * in a while; any other status is said, and Retry is the person's.
178
184
  */
179
- function Browser({ sandbox, held, site, live }) {
185
+ function Browser({ sandbox, held, site, live, repo, onEnvironment, }) {
180
186
  const { t: say } = useI18n();
181
187
  const t = useTarget();
182
188
  const [open, setOpen] = useState([]);
@@ -184,9 +190,14 @@ function Browser({ sandbox, held, site, live }) {
184
190
  const [src, setSrc] = useState('');
185
191
  const [why, setWhy] = useState('');
186
192
  const [attempt, setAttempt] = useState(0);
193
+ const [serving, setServing] = useState(null);
187
194
  const reopened = useRef([]);
188
195
  const frame = useRef(null);
189
196
  const running = Boolean(sandbox) && held === 'running';
197
+ // A server the run started ended with the run, so once it has, the person can
198
+ // start one again here, in the sandbox kept for its previews — a suspended one
199
+ // is resumed for it. While the run works, its server is the agent's to start.
200
+ const startable = Boolean(sandbox) && !live && (held === 'running' || held === 'parked');
190
201
  // What listens, read again while the sandbox runs: a dev server appears once it listens.
191
202
  useEffect(() => {
192
203
  if (!running) {
@@ -246,34 +257,75 @@ function Browser({ sandbox, held, site, live }) {
246
257
  return () => window.removeEventListener('message', hear);
247
258
  }, [src, port, say]);
248
259
  const tab = () => away(preview(t, sandbox, port)).catch((e) => setWhy(e.message));
249
- const detect = () => {
250
- if (!sandbox)
251
- return;
252
- void listening(t, sandbox).then((ps) => {
253
- setOpen(ps);
254
- setPort((p) => (ps.some((x) => x.port === p) ? p : (ps[0]?.port ?? 0)));
255
- }, () => undefined);
260
+ /**
261
+ * Start the app's server: the codebase's start command when its environment
262
+ * names one, else its package's dev script. The page opens once it listens,
263
+ * because what listens is read every few seconds anyway.
264
+ */
265
+ const start = async () => {
266
+ setServing({ command: '', up: true, log: '', why: '' });
267
+ try {
268
+ const named = repo ? await readEnvironment(t, repo).then((e) => e.start, () => '') : '';
269
+ setServing({ command: await serve(t, sandbox, named), up: true, log: '', why: '' });
270
+ }
271
+ catch (e) {
272
+ setServing({ command: '', up: false, log: '', why: e.message });
273
+ }
256
274
  };
275
+ // While a server started here comes up, whether it is still running and what it
276
+ // says; one that exits says why. Read for a while, never for as long as the page is open.
277
+ const coming = Boolean(serving?.command && serving.up && !port);
278
+ useEffect(() => {
279
+ if (!coming)
280
+ return;
281
+ let gone = false;
282
+ const until = Date.now() + WATCH;
283
+ const check = () => {
284
+ if (Date.now() > until) {
285
+ clearInterval(every);
286
+ setServing((v) => v && { ...v, why: say('It is running, and nothing listens on a port yet.') });
287
+ return;
288
+ }
289
+ served(t, sandbox).then((s) => {
290
+ if (gone)
291
+ return;
292
+ setServing((v) => v && { ...v, up: s.up, log: s.log, why: s.up ? '' : say('The dev server stopped.') });
293
+ }, () => undefined);
294
+ };
295
+ const every = setInterval(check, WATCHING);
296
+ return () => {
297
+ gone = true;
298
+ clearInterval(every);
299
+ };
300
+ }, [t, sandbox, coming, say]);
301
+ const nothing = _jsx(Site, { site: site, live: live, held: held, serving: serving, onStart: startable ? () => void start() : undefined, onEnvironment: repo ? onEnvironment : undefined });
257
302
  if (!running)
258
- return _jsx(Site, { site: site, live: live, held: held, onDetect: detect });
303
+ return nothing;
259
304
  if (!port)
260
- return _jsx(Site, { site: site, live: live, held: held, onDetect: detect });
305
+ return nothing;
261
306
  const host = open.find((p) => p.port === port)?.host ?? '';
262
307
  return (_jsxs(YStack, { flex: 1, minH: 0, children: [_jsxs(XStack, { px: "$2", py: "$1.5", gap: "$1.5", items: "center", borderBottomWidth: 1, borderColor: "$borderColor", children: [_jsx(XStack, { render: "button", "aria-label": say('Reload the page'), onPress: () => setAttempt((a) => a + 1), p: "$1.5", rounded: "$2", hoverStyle: { bg: '$hover' }, children: _jsx(RefreshCcw, { size: 14 }) }), open.length > 1 ? (_jsx(XStack, { gap: "$1", children: open.map((p) => (_jsx(XStack, { render: "button", "aria-label": say('Port {port}', { port: p.port }), onPress: () => setPort(p.port), px: "$2", py: "$1", rounded: "$2", bg: p.port === port ? '$hover' : 'transparent', children: _jsx(SizableText, { size: "$1", color: p.port === port ? '$ink' : '$soft', children: String(p.port) }) }, p.port))) })) : null, _jsx(SizableText, { flex: 1, minW: 0, size: "$1", color: "$soft", numberOfLines: 1, style: mono, children: host || say('port {port}', { port }) }), _jsx(XStack, { render: "button", "aria-label": say('Open in a new tab'), onPress: () => void tab(), p: "$1.5", rounded: "$2", hoverStyle: { bg: '$hover' }, children: _jsx(ExternalLink, { size: 14 }) })] }), why ? (_jsxs(YStack, { flex: 1, items: "center", justify: "center", gap: "$2", p: "$6", children: [_jsx(SizableText, { size: "$2", color: "$soft", style: { textAlign: 'center' }, children: why }), _jsxs(XStack, { gap: "$2", children: [_jsx(Button, { size: "sm", variant: "outline", onPress: () => setAttempt((a) => a + 1), children: say('Retry') }), _jsx(Button, { size: "sm", variant: "outline", onPress: () => void tab(), children: say('Open in a new tab') })] })] })) : src ? (_jsx("iframe", { ref: frame, src: src, title: say('What the run serves on port {port}', { port }), sandbox: "allow-scripts allow-same-origin allow-forms allow-popups", style: { border: 0, width: '100%', height: '100%', display: 'block', background: '#fff' } })) : (_jsx(YStack, { flex: 1, items: "center", justify: "center", children: _jsx(SizableText, { size: "$2", color: "$soft", children: say('Opening port {port}…', { port }) }) }))] }));
263
308
  }
309
+ /** How long, and how often, a server started here is watched while it comes up. */
310
+ const WATCH = 120_000;
311
+ const WATCHING = 3_000;
264
312
  /**
265
313
  * Where the run published its work, framed, with its address, a reload and the
266
- * page in a tab of its own; or what keeps its sandbox from serving.
314
+ * page in a tab of its own; or what keeps its sandbox from serving, and the
315
+ * server the person can start in it.
267
316
  */
268
- function Site({ site, live, held, onDetect }) {
317
+ function Site({ site, live, held, serving, onStart, onEnvironment, }) {
269
318
  const { t } = useI18n();
270
319
  const frame = useRef(null);
271
- const [urlInput, setUrlInput] = useState(site);
272
- return (_jsxs(YStack, { flex: 1, minH: 0, children: [_jsxs(XStack, { px: "$2", py: "$1.5", gap: "$1.5", items: "center", borderBottomWidth: 1, borderColor: "$borderColor", children: [_jsx(XStack, { render: "button", "aria-label": t('Reload the page'), onPress: () => frame.current?.reload(), p: "$1.5", rounded: "$2", hoverStyle: { bg: '$hover' }, children: _jsx(RefreshCcw, { size: 14 }) }), _jsx(SizableText, { flex: 1, minW: 0, size: "$1", color: "$soft", numberOfLines: 1, style: mono, children: site || t('Nothing is serving yet') }), _jsx(Input, { unstyled: true, value: urlInput, onChangeText: setUrlInput, placeholder: t('Type a URL'), "aria-label": t('Type a URL'), style: { width: 120, fontSize: 12, outlineStyle: 'none', background: 'transparent' } }), site ? (_jsx(Out, { href: site, label: t('Open in a new tab'), children: _jsx(XStack, { p: "$1.5", rounded: "$2", hoverStyle: { bg: '$hover' }, children: _jsx(ExternalLink, { size: 14 }) }) })) : null] }), _jsx(PreviewFrame, { ref: frame, src: site, title: t('Where this run is published'), device: "desktop", empty: _jsxs(YStack, { items: "center", gap: "$2.5", p: "$6", children: [_jsx(Globe, { size: 28, opacity: 0.45 }), _jsx(SizableText, { size: "$3", color: "$ink", children: t('Nothing is serving yet') }), _jsx(SizableText, { size: "$2", color: "$soft", style: { textAlign: 'center', maxWidth: 280 }, children: held === 'parked'
320
+ return (_jsxs(YStack, { flex: 1, minH: 0, children: [_jsxs(XStack, { px: "$2", py: "$1.5", gap: "$1.5", items: "center", borderBottomWidth: 1, borderColor: "$borderColor", children: [_jsx(XStack, { render: "button", "aria-label": t('Reload the page'), onPress: () => frame.current?.reload(), p: "$1.5", rounded: "$2", hoverStyle: { bg: '$hover' }, children: _jsx(RefreshCcw, { size: 14 }) }), _jsx(SizableText, { flex: 1, minW: 0, size: "$1", color: "$soft", numberOfLines: 1, style: mono, children: site || t('Nothing is serving yet') }), site ? (_jsx(Out, { href: site, label: t('Open in a new tab'), children: _jsx(XStack, { p: "$1.5", rounded: "$2", hoverStyle: { bg: '$hover' }, children: _jsx(ExternalLink, { size: 14 }) }) })) : null] }), _jsx(PreviewFrame, { ref: frame, src: site, title: t('Where this run is published'), device: "desktop", empty: _jsxs(YStack, { items: "center", gap: "$2.5", p: "$6", children: [_jsx(Globe, { size: 28, opacity: 0.45 }), _jsx(SizableText, { size: "$3", color: "$ink", children: t('Nothing is serving yet') }), _jsx(SizableText, { size: "$2", color: "$soft", style: { textAlign: 'center', maxWidth: 280 }, children: held === 'parked'
273
321
  ? `${t('The run’s sandbox is suspended.')} ${t('Resume it to see what it serves.')}`
274
322
  : live
275
323
  ? t('When the run starts a server in its sandbox, the page opens here.')
276
- : `${t('Nothing listens in this run’s sandbox, and it published no site.')} ${t('Its work is on its branch.')}` }), onDetect ? (_jsxs(XStack, { gap: "$1", items: "center", pt: "$1", flexWrap: "wrap", justify: "center", children: [_jsx(SizableText, { size: "$1", color: "$soft", children: t('Preview your app instead?') }), _jsx(XStack, { render: "button", onPress: onDetect, px: "$1.5", py: "$0.5", rounded: "$2", hoverStyle: { bg: '$hover' }, children: _jsx(SizableText, { size: "$1", color: "$ink", style: { textDecorationLine: 'underline' }, children: t('Detect dev server') }) })] })) : null] }) })] }));
324
+ : `${t('Nothing listens in this run’s sandbox, and it published no site.')} ${t('A server the run started stopped when the run ended.')}` }), serving ? (_jsxs(YStack, { items: "center", gap: "$2", width: "100%", children: [_jsx(SizableText, { size: "$2", color: "$ink", role: "status", style: { textAlign: 'center', maxWidth: 320 }, children: serving.why || (serving.command ? t('Starting {command}…', { command: serving.command }) : t('Starting the dev server…')) }), serving.log ? _jsx(Tail, { log: serving.log }) : null, serving.why ? (_jsxs(XStack, { gap: "$2", flexWrap: "wrap", justify: "center", children: [onStart ? (_jsx(Button, { size: "sm", variant: "outline", onPress: onStart, children: t('Try again') })) : null, onEnvironment ? (_jsx(Button, { size: "sm", variant: "outline", onPress: onEnvironment, children: t('Set a start command') })) : null] })) : null] })) : onStart ? (_jsx(Button, { size: "sm", onPress: onStart, children: t('Start dev server') })) : null] }) })] }));
325
+ }
326
+ /** The last lines a server wrote, as it wrote them. */
327
+ function Tail({ log }) {
328
+ return (_jsx(YStack, { width: "100%", maxW: 460, maxH: 200, overflow: "scroll", rounded: "$2", borderWidth: 1, borderColor: "$borderColor", p: "$2", children: _jsx(SizableText, { size: "$1", color: "$soft", style: { ...mono, whiteSpace: 'pre-wrap', wordBreak: 'break-word' }, children: log.split('\n').slice(-12).join('\n') }) }));
277
329
  }
278
330
  function EnvironmentInspection({ id, repo, name, branch, environment, pr, title, events, live, onOpenEnvironment, onOpenDiff, }) {
279
331
  const { t } = useI18n();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hanzo/build",
3
- "version": "0.2.124",
3
+ "version": "0.2.125",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0 OR MIT",
6
6
  "description": "Hanzo Build — say what you want, watch it built, deployed and running. The builder as a component, mounted by the Hanzo app at hanzo.ai.",