mirror of
https://github.com/hanzo-inc/tabs.git
synced 2026-11-22 10:01:17 +00:00
Depends on #4 (0.1.18): this branch is stacked on it, so merge #4 first. Cause - A pane's come-up was spread over timers and flags: a frame mounted again loaded a ticket an earlier frame had already spent, a machine still pending read as offline, and a failed address fetch could wait for ever. - A cloud computer started on one press with no question, a host had no way to answer for its own menu, and closing the last pane left a machine running without saying so. - files in package.json listed modules by name, so lib/comeup.ts and lib/start.ts would be left out of the pack. Change - lib/comeup.ts is one pure state machine on one clock: a fresh ticket and a fresh attempt number per ask, nothing minted while the list says pending, a bounded few retries, and every state but ready ends failed with Reconnect and Stop. One revive() brings a saved layout back. The fleet list is read every 5 s only while a pane on screen waits and the tab is visible. - lib/start.ts is the one start path: a new cloud computer asks first through the host's `confirmLease` (what it is, its cost, whether its files are kept), with Don't ask again kept per account and per class of machine, undone by the toolbar's Ask before starting again. A confirm that throws or answers anything but true starts nothing. `StartAsk.expires` carries the deadline the workspace enforces. Closing the last pane, or one still starting, and stopping a temporary machine ask whether to keep it or stop it. - Every question is the stack's AlertDialog: focus opens on the safe answer, Escape cancels, Tab stays inside, focus returns to the opener. - package.json `files` ships components/*.tsx and lib/*.ts by pattern; a test packs it and checks every import resolves inside the pack. CI refuses to publish an export that carries the e2e host page. The README states the host contract (confirmLease, onLaunch, onStop). 0.1.18 -> 0.1.19. Testing - tsc --noEmit: clean. - jest (whole suite): 11 suites, 325 tests passed; tests/package.test.ts runs `pnpm pack` and passed with a writable pnpm home. - Not run: the Playwright e2e specs (e2e/, app/e2e), and the change in a browser. Risk - Large (27 files). The commits were interleaved, so this is one squash of the whole topic, not separable pieces.
409 lines
17 KiB
TypeScript
409 lines
17 KiB
TypeScript
/**
|
|
* The control plane, read from the browser.
|
|
*
|
|
* Tabs has no backend of its own — deliberately. The machines are already
|
|
* registered with api.hanzo.ai by `hanzo link`, and the terminals are already
|
|
* served by those machines over their own tunnels. A server here would be a third
|
|
* party to a conversation that has two, and one more thing to keep running.
|
|
*/
|
|
|
|
/**
|
|
* Where the control plane answers.
|
|
*
|
|
* A DEFAULT, not a constant, because this module is read by two hosts now: the
|
|
* web app at tabs.hanzo.ai, and the desktop shell, which points at whichever
|
|
* cloud its identity belongs to. Every function here already takes a token, so
|
|
* it takes the origin the same way — a parameter with this as its default,
|
|
* rather than module state a second host would have to remember to set before
|
|
* the first call.
|
|
*
|
|
* `process.env` is read defensively: a bundler that does not define it leaves
|
|
* the identifier undefined rather than an empty object, and reading a property
|
|
* off that throws at module load.
|
|
*/
|
|
export const API =
|
|
(typeof process !== 'undefined' ? process.env?.NEXT_PUBLIC_HANZO_API : undefined) ??
|
|
'https://api.hanzo.ai';
|
|
|
|
export interface Machine {
|
|
id: string;
|
|
label: string;
|
|
host?: string;
|
|
status: string;
|
|
capacity?: string;
|
|
}
|
|
|
|
export interface Session {
|
|
id: string;
|
|
host?: string;
|
|
status: string;
|
|
terminal?: string;
|
|
cwd?: string;
|
|
agent?: string;
|
|
updatedAt?: string;
|
|
}
|
|
|
|
/**
|
|
* A refusal, carrying the platform's own word for it.
|
|
*
|
|
* `code` is what the caller can BRANCH on — being out of credit wants a
|
|
* different answer from a full node, and telling them apart by reading the
|
|
* sentence would break the first time the sentence is reworded.
|
|
*/
|
|
export class Refusal extends Error {
|
|
constructor(
|
|
readonly status: number,
|
|
readonly code: string,
|
|
message: string,
|
|
) {
|
|
super(message);
|
|
this.name = 'Refusal';
|
|
}
|
|
}
|
|
|
|
/** Who a token belongs to: its `sub`, read and NOT verified. It only keys
|
|
* what this browser remembers for that person, so a forged one changes
|
|
* nothing but which questions are asked in a browser that already holds it. */
|
|
export function subject(token: string | null): string | null {
|
|
const part = token?.split('.')[1];
|
|
if (!part) return null;
|
|
try {
|
|
const json = atob(part.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(part.length / 4) * 4, '='));
|
|
const sub = (JSON.parse(json) as { sub?: unknown }).sub;
|
|
return typeof sub === 'string' && sub ? sub : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Out of credit, or past the org's spend cap. Both are answered the same way —
|
|
* put money on it, or bring a machine of your own — so they are one question. */
|
|
export const unfunded = (e: unknown): boolean =>
|
|
e instanceof Refusal && (e.status === 402 || e.code === 'insufficient_balance' || e.code === 'spend_cap_exceeded');
|
|
|
|
/**
|
|
* Read a refusal off a response, in EITHER shape the fleet sends.
|
|
*
|
|
* The money wire answers `{error:{code,message}}` — an OBJECT — while other
|
|
* endpoints answer `{error:"..."}`. Reading only the flat one coerced the nested
|
|
* object into a string, so the one refusal a person can actually act on
|
|
* rendered as `[object Object]` beside a button that had just failed.
|
|
*/
|
|
async function refusal(res: Response, fallback: string): Promise<Refusal> {
|
|
const body = (await res.json().catch(() => null)) as
|
|
| { error?: string | { code?: string; message?: string } }
|
|
| null;
|
|
const e = body?.error;
|
|
if (typeof e === 'string') return new Refusal(res.status, '', e || fallback);
|
|
return new Refusal(res.status, e?.code ?? '', e?.message || fallback);
|
|
}
|
|
|
|
/** How long a registry read may take. A request that never answers would
|
|
* otherwise hold the workspace on its loading skeleton for good; past this it
|
|
* fails, and `useFleet` reports it as the error with its retry. Well over the
|
|
* plane's normal answer, so a slow read is not mistaken for a dead one. */
|
|
export const READ_TIMEOUT = 15_000;
|
|
|
|
async function read<T>(path: string, token: string, origin = API): Promise<T> {
|
|
const res = await fetch(`${origin}${path}`, {
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
cache: 'no-store',
|
|
signal: AbortSignal.timeout(READ_TIMEOUT),
|
|
});
|
|
if (!res.ok) throw new Error(`${path} → ${res.status}`);
|
|
return (await res.json()) as T;
|
|
}
|
|
|
|
export const machines = (token: string, origin = API) =>
|
|
read<{ targets: Machine[] }>('/v1/agents/targets', token, origin).then((r) => r.targets ?? []);
|
|
|
|
export const sessions = (token: string, origin = API) =>
|
|
read<{ sessions: Session[] }>('/v1/agents/sessions?limit=200', token, origin).then(
|
|
(r) => r.sessions ?? [],
|
|
);
|
|
|
|
/**
|
|
* Sandboxes — the machines we start for you, rather than the ones you linked.
|
|
*
|
|
* The builder's pods (hanzo.app, console.hanzo.ai) serve the same framed
|
|
* terminal every other surface uses: cloud hosts the whole emulator page at
|
|
* /v1/sandboxes/:id/terminal, and the URL's only credential is a single-use,
|
|
* thirty-second ticket. So a sandbox joins this workspace with no new pane
|
|
* kind — it is a machine whose terminal URL is MINTED per open instead of
|
|
* published by `hanzo link`, and `?arg=` names the tmux session exactly as a
|
|
* linked machine's ttyd does.
|
|
*
|
|
* It is the SAME plane as the registry above, which is why there is no second
|
|
* base URL here. A cloud machine used to be a DigitalOcean droplet ordered
|
|
* through visor: a second provisioning plane, a second failure mode, and a
|
|
* minute of boot and `hanzo link` before it could serve a shell. A sandbox is a
|
|
* pod, so the request that asks for one comes back when it is already running.
|
|
*/
|
|
export interface SandboxMachine {
|
|
id: string;
|
|
status: string;
|
|
project?: string;
|
|
/** `dev` shells; `desktop` also has an X server, so it has a SCREEN to watch.
|
|
* It is the machine's own answer and not a guess from its name. */
|
|
class?: string;
|
|
}
|
|
|
|
/** The sandboxes to show: running, and pending — one still starting is a
|
|
* machine the person asked for and is paying for, and leaving it out drew
|
|
* its pane as offline with nothing to stop. */
|
|
export const sandboxes = (token: string, origin = API) =>
|
|
listed(token, origin).then((all) => all.filter((s) => s.status === 'running' || s.status === 'pending'));
|
|
|
|
/** Every sandbox the account has, in any state: the ONE read of the list, which
|
|
* what is shown and which names are taken are both filters of. */
|
|
const listed = (token: string, origin = API) =>
|
|
read<{ sandboxes?: SandboxMachine[] }>('/v1/sandboxes', token, origin).then((r) => r.sandboxes ?? []);
|
|
|
|
/** How a sandbox names itself in the workspace. Its project is what its DISK is
|
|
* keyed on, so it is the name that means the same box tomorrow. */
|
|
export const machineName = (s: SandboxMachine) => s.project || `cloud-${s.id.slice(0, 6)}`;
|
|
|
|
/** The states in which a sandbox still holds its project's disk. The server
|
|
* refuses a second lease on a project while one of these holds it (cloud
|
|
* apps/sandbox `room`), and a PARKED one holds it too: a desktop that ran out
|
|
* its lease keeps its disk, and is not in the running list. */
|
|
const HOLDS = new Set(['running', 'pending', 'parked']);
|
|
|
|
/** The names a new machine may not take: every project still held, not only the
|
|
* ones running, or the press after a desktop parks asks for its name and is
|
|
* refused every time. */
|
|
const held = (token: string, origin = API) =>
|
|
listed(token, origin).then((all) => new Set(all.filter((s) => HOLDS.has(s.status)).map(machineName)));
|
|
|
|
/** What a machine of each class is called, before its number. It says what the
|
|
* machine IS — one you shell into, one with a screen — where the name used to
|
|
* say which product opened it, so a workspace of three read `tabs`, `tabs-2`,
|
|
* `tabs-3` and told you nothing.
|
|
*
|
|
* Two stems, not one, because the project keys the DISK and machines are
|
|
* counted against the ones holding a disk now: an ended `cloud-2` still owns its disk, so
|
|
* a desktop later handed that name would mount a shell machine's home and call
|
|
* it a screen. */
|
|
const STEM: Record<Class, string> = { dev: 'cloud', desktop: 'desk', browser: 'web' };
|
|
|
|
/** The two machines tabs starts. `dev` is the one you shell into — a toolchain,
|
|
* a home, and a disk that outlives the lease; `desktop` is that plus an X
|
|
* server, a window manager and a VNC server, so it has a screen; is
|
|
* that with Chromium open full screen and DevTools on loopback, so the page on
|
|
* the screen is a real browser a person watches and an agent drives. None is
|
|
* `exec`, the code interpreter's scratch pod, which tabs never opens. */
|
|
export type Class = 'dev' | 'desktop' | 'browser';
|
|
|
|
/**
|
|
* Start one, and answer it once it is RUNNING.
|
|
*
|
|
* A sandbox is named by its project, and the project is what the disk is keyed
|
|
* on: one sandbox per project is the server's rule, so the name is picked
|
|
* against what already holds one (`held`) rather than made up. That is what makes a second
|
|
* press a second machine instead of a second attempt at the first one.
|
|
*
|
|
* The lease is the server's to set. Tabs has no opinion about how long a machine
|
|
* should live, and a `ttlSec` here would be a second answer to drift from the one
|
|
* in the class table.
|
|
*/
|
|
export const createSandbox = async (
|
|
token: string,
|
|
kind: Class = 'dev',
|
|
origin = API,
|
|
/** A machine with no project, so no disk that outlives it: its files are
|
|
* gone when it stops. Only ever asked for by a person who chose it in those
|
|
* words, never as a quiet stand-in for the machine they asked for. */
|
|
temporary = false,
|
|
): Promise<SandboxMachine> => {
|
|
let body: { class: Class; project?: string } = { class: kind };
|
|
if (!temporary) {
|
|
const taken = await held(token, origin);
|
|
// Every machine carries its number, the first one included: `cloud` beside
|
|
// `cloud-2` reads as a different kind of thing rather than the one before it.
|
|
// The bound is the pigeonhole — among n machines, one of n+1 names is free.
|
|
const stem = STEM[kind];
|
|
let project = `${stem}-1`;
|
|
for (let n = 2; taken.has(project); n++) project = `${stem}-${n}`;
|
|
body = { class: kind, project };
|
|
}
|
|
const res = await fetch(`${origin}/v1/sandboxes`, {
|
|
method: 'POST',
|
|
headers: { Authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
|
body: JSON.stringify(body),
|
|
cache: 'no-store',
|
|
});
|
|
// Starting a machine fails for reasons a person can act on — no credit, an
|
|
// image that will not pull, a project already held, an org at its ceiling —
|
|
// and the server says which. A bare status code next to the button would name
|
|
// none of them, and the CODE is what lets the pane offer the right remedy.
|
|
//
|
|
// Out of credit is reported, never answered with a temporary machine in its
|
|
// place: that one keeps no files, and a person who was not told would lose
|
|
// their work when it stopped. The pane offers it as a choice instead.
|
|
if (!res.ok) throw await refusal(res, `new machine → ${res.status}`);
|
|
return (await res.json()) as SandboxMachine;
|
|
};
|
|
|
|
/**
|
|
* Park a running sandbox: it stops running (and being billed) and keeps its
|
|
* disk. The same call @hanzo/app's `parkComputer` makes for a desktop.
|
|
*/
|
|
export const pause = async (token: string, id: string, origin = API): Promise<void> => {
|
|
const res = await fetch(`${origin}/v1/sandbox/${encodeURIComponent(id)}/pause`, {
|
|
method: 'POST',
|
|
headers: { Authorization: `Bearer ${token}`, 'content-type': 'application/json' },
|
|
body: '{}',
|
|
cache: 'no-store',
|
|
signal: AbortSignal.timeout(READ_TIMEOUT),
|
|
});
|
|
if (!res.ok) throw new Error(`stop machine → ${res.status}`);
|
|
};
|
|
|
|
/**
|
|
* Hand a linked machine's tunnel the identity this browser already holds.
|
|
*
|
|
* A published terminal is a shell, so `hanzo link` puts its tunnel behind the
|
|
* org's identity provider. The tunnel used to learn who you are the only way it
|
|
* could — by redirecting to hanzo.id — and hanzo.id will not be framed, quite
|
|
* rightly, because a login page inside someone else's document is clickjacking.
|
|
* So a pane could not open the terminal of a machine belonging to the very
|
|
* person looking at it: the redirect had to leave the frame, and the answer was
|
|
* a second sign-in for a session that already existed.
|
|
*
|
|
* This is that redirect, skipped. The tunnel is asked once, with the token this
|
|
* page is already using to read the registry, and answers with the session it
|
|
* would have set at the end of the round trip. One identity, one sign-in, no
|
|
* tab. The bearer stays in this module; what the workspace gets is a URL.
|
|
*
|
|
* `credentials: 'include'` because the whole point is the cookie that comes
|
|
* back, and `share.hanzo.ai` is a sibling of this page, not a third party.
|
|
*/
|
|
export const grant = async (token: string, base: string): Promise<void> => {
|
|
const res = await fetch(new URL('/.well-known/zrok/session', base).toString(), {
|
|
method: 'POST',
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
credentials: 'include',
|
|
// Never chase it: a tunnel that answers with a redirect is one that does not
|
|
// know how to be asked, and following it lands on the sign-in page whose
|
|
// absence is the point.
|
|
redirect: 'manual',
|
|
cache: 'no-store',
|
|
});
|
|
if (res.ok) return;
|
|
// A sign-in is a Refusal with its own code, because it is the one answer
|
|
// here a person can fix, by signing in to the machine in their browser.
|
|
if (res.type === 'opaqueredirect') {
|
|
throw new Refusal(res.status, SIGN_IN, 'terminal grant → the tunnel asked for a sign-in');
|
|
}
|
|
throw new Error(`terminal grant → ${res.status}`);
|
|
};
|
|
|
|
const SIGN_IN = 'sign_in';
|
|
|
|
/** Whether a mint failed because the machine's tunnel wants a sign-in first. */
|
|
export const signIn = (e: unknown): boolean => e instanceof Refusal && e.code === SIGN_IN;
|
|
|
|
/** The two ways to look at a machine: its shell, or its screen. Same sandbox,
|
|
* same credential, two pages — see cloud's apps/sandbox. */
|
|
export type Door = 'terminal' | 'screen';
|
|
|
|
/**
|
|
* Mint a single-use ticket and answer the page to frame.
|
|
*
|
|
* The URL is the SERVER'S, not composed here: the mint answers the path its own
|
|
* ticket opens, so a client cannot spell the address wrong or send a
|
|
* ticket somewhere it does not work. All this adds is the host it was already
|
|
* talking to, and `arg` — the tmux session a terminal attaches to, which a
|
|
* screen has no use for because a machine has one display.
|
|
*
|
|
* The ticket is spent by the first load and lasts thirty seconds, so this is
|
|
* called once per pane per connection, never per render. The bearer never
|
|
* leaves this module: what the workspace holds is the minted URL.
|
|
*/
|
|
export const frameUrl = async (
|
|
token: string,
|
|
id: string,
|
|
door: Door,
|
|
arg?: string,
|
|
origin = API,
|
|
): Promise<string> => {
|
|
const res = await fetch(`${origin}/v1/sandboxes/${encodeURIComponent(id)}/${door}/ticket`, {
|
|
method: 'POST',
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
cache: 'no-store',
|
|
});
|
|
if (!res.ok) throw new Error(`${door} ticket → ${res.status}`);
|
|
const body = (await res.json()) as { url?: string };
|
|
if (!body.url) throw new Error(`${door} ticket → empty answer`);
|
|
// Parsed, not concatenated: `&arg=` on an address with no `?` lands in the
|
|
// path. `set` also keeps it to ONE arg, which a shell needs (see shellUrl).
|
|
const u = new URL(`${origin}${body.url}`);
|
|
if (arg) u.searchParams.set('arg', arg);
|
|
return u.toString();
|
|
};
|
|
|
|
/** One step of a sandbox agent's turn, as the stream says it (cloud apps/sandbox agent.go). */
|
|
export interface AgentFrame {
|
|
type: 'say' | 'act' | 'result' | 'error' | 'end';
|
|
text?: string;
|
|
tool?: string;
|
|
args?: unknown;
|
|
ok?: boolean;
|
|
rounds?: number;
|
|
}
|
|
|
|
/** One earlier turn of the conversation: what the person said, and what the AI answered. */
|
|
export interface AgentTurn {
|
|
role: 'user' | 'assistant';
|
|
text: string;
|
|
}
|
|
|
|
/**
|
|
* Have the AI work a sandbox, and hand each step to onFrame as it happens. The
|
|
* answer is an event stream; this reads it to the end, or until signal aborts it.
|
|
*/
|
|
export const agentTurn = async (
|
|
token: string,
|
|
id: string,
|
|
body: { message: string; history: AgentTurn[] },
|
|
onFrame: (f: AgentFrame) => void,
|
|
signal: AbortSignal,
|
|
origin = API,
|
|
): Promise<void> => {
|
|
const res = await fetch(`${origin}/v1/sandbox/${encodeURIComponent(id)}/agent`, {
|
|
method: 'POST',
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
'content-type': 'application/json',
|
|
accept: 'text/event-stream',
|
|
},
|
|
body: JSON.stringify(body),
|
|
cache: 'no-store',
|
|
signal,
|
|
});
|
|
if (!res.ok || !res.body) throw await refusal(res, `agent → ${res.status}`);
|
|
const reader = res.body.getReader();
|
|
const dec = new TextDecoder();
|
|
let buf = '';
|
|
for (;;) {
|
|
const { value, done } = await reader.read();
|
|
if (done) break;
|
|
buf += dec.decode(value, { stream: true });
|
|
for (let i = buf.indexOf('\n\n'); i >= 0; i = buf.indexOf('\n\n')) {
|
|
const chunk = buf.slice(0, i);
|
|
buf = buf.slice(i + 2);
|
|
const data = chunk
|
|
.split('\n')
|
|
.filter((l) => l.startsWith('data:'))
|
|
.map((l) => l.slice(5).trimStart())
|
|
.join('\n');
|
|
if (!data) continue;
|
|
try {
|
|
onFrame(JSON.parse(data) as AgentFrame);
|
|
} catch {
|
|
// a frame that is not JSON is one this client does not read
|
|
}
|
|
}
|
|
}
|
|
};
|