kaizen-agent 1.66.0 → 1.68.0

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.
package/cli/onboarding.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
 
7
- export const STEPS = 3; // default agent, appearance, notifications; adding a project is the last button, not a step
7
+ export const STEPS = 4; // default agent, appearance, notifications, phone; adding a project is the last button, not a step
8
8
  export type Outcome = "done" | "skipped" | "dismissed" | null;
9
9
  export type Saved = { step: number; outcome: Outcome };
10
10
 
@@ -0,0 +1,96 @@
1
+ // Settings → Mobile and the onboarding phone step: what `kaizen setup` does for the phone,
2
+ // as board routes. GET says where this computer stands, POST connects or logs in.
3
+ import { qrMatrix } from "./qr.ts";
4
+ import { addWebHost, webHosts } from "./state.ts";
5
+
6
+ export type PhoneState = {
7
+ state: "missing" | "login" | "ready" | "connected";
8
+ account: string; // the Tailscale login the phone must use too
9
+ url: string; // the phone address, once connected
10
+ phones: { name: string; online: boolean }[];
11
+ qr: string; // svg, once connected
12
+ };
13
+
14
+ // From `tailscale status --json` (null when the command is not there) and the saved board names.
15
+ export function phoneState(json: string | null, hosts: Set<string>): PhoneState {
16
+ const out: PhoneState = { state: "missing", account: "", url: "", phones: [], qr: "" };
17
+ if (json === null) return out;
18
+ let s: any;
19
+ try { s = JSON.parse(json); } catch { return { ...out, state: "login" }; }
20
+ const name = String(s?.Self?.DNSName ?? "").replace(/\.$/, "").toLowerCase();
21
+ out.account = String(s?.User?.[s?.Self?.UserID]?.LoginName ?? "");
22
+ out.phones = Object.values<any>(s?.Peer ?? {})
23
+ .filter((p) => /^(ios|android)$/i.test(p?.OS ?? ""))
24
+ // Android reports "localhost" as its host name: the tailnet's name for it says more.
25
+ .map((p) => ({ name: String(p.HostName && p.HostName !== "localhost" ? p.HostName : String(p.DNSName ?? "").split(".")[0] || "phone"), online: !!p.Online }));
26
+ if (s?.BackendState !== "Running" || !name) return { ...out, state: "login" };
27
+ if (!hosts.has(name)) return { ...out, state: "ready" };
28
+ const url = `https://${name}`;
29
+ let qr = "";
30
+ try { qr = qrSvg(url); } catch { /* a name too long for the code: the address still shows */ }
31
+ return { ...out, state: "connected", url, qr };
32
+ }
33
+
34
+ // Dark modules on white with a four-module quiet zone, so it scans in a dark theme too.
35
+ export function qrSvg(text: string): string {
36
+ const g = qrMatrix(text), q = 4, n = g.length + 2 * q;
37
+ let d = "";
38
+ g.forEach((row, y) => row.forEach((on, x) => { if (on) d += `M${x + q} ${y + q}h1v1h-1z`; }));
39
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${n} ${n}" shape-rendering="crispEdges"><rect width="${n}" height="${n}" fill="#fff"/><path d="${d}" fill="#000"/></svg>`;
40
+ }
41
+
42
+ const OPERATOR = /operator|root|access denied|permission/i;
43
+ const PERMISSION = "Tailscale needs permission once. Run sudo tailscale set --operator=$USER in a terminal, then try again.";
44
+
45
+ type Run = (argv: string[]) => Promise<{ ok: boolean; out: string; err: string }>;
46
+
47
+ const run: Run = async (argv) => {
48
+ try {
49
+ const p = Bun.spawn(argv, { stdout: "pipe", stderr: "pipe", timeout: 10_000, windowsHide: true });
50
+ const [out, err] = [await new Response(p.stdout).text(), await new Response(p.stderr).text()];
51
+ return { ok: (await p.exited) === 0, out, err };
52
+ } catch { return { ok: false, out: "", err: "tailscale is not installed" }; }
53
+ };
54
+
55
+ export async function readPhone(r: Run = run): Promise<PhoneState> {
56
+ const s = await r(["tailscale", "status", "--json"]);
57
+ // Logged out, `status` exits non-zero but still prints JSON; not installed, it prints nothing.
58
+ return phoneState(s.out.trim() ? s.out : s.err === "tailscale is not installed" ? null : "", webHosts());
59
+ }
60
+
61
+ // Shares the board on the tailnet (never funnel) and saves its name, as `kaizen setup` does.
62
+ export async function connectPhone(port: number, r: Run = run): Promise<PhoneState | { error: string }> {
63
+ const now = await readPhone(r);
64
+ if (now.state === "missing" || now.state === "login") return now;
65
+ const s = await r(["tailscale", "serve", "--bg", `127.0.0.1:${port}`]);
66
+ if (!s.ok) {
67
+ const msg = s.err + s.out;
68
+ return { error: OPERATOR.test(msg) ? PERMISSION : msg.trim().split("\n")[0] || "tailscale serve failed" };
69
+ }
70
+ const name = (await r(["tailscale", "status", "--json"])).out;
71
+ try { addWebHost(String(JSON.parse(name).Self.DNSName).replace(/\.$/, "")); } catch { return { error: "Tailscale stopped while connecting" }; }
72
+ return readPhone(r);
73
+ }
74
+
75
+ // `tailscale login` prints the sign-in page and waits for it; the page is all the board needs.
76
+ export async function loginUrl(): Promise<{ url: string } | { error: string }> {
77
+ let p: ReturnType<typeof Bun.spawn>;
78
+ try { p = Bun.spawn(["tailscale", "login"], { stdout: "pipe", stderr: "pipe", windowsHide: true }); }
79
+ catch { return { error: "tailscale is not installed" }; }
80
+ let text = "";
81
+ const page = (s: ReadableStream<Uint8Array>) => (async () => {
82
+ const dec = new TextDecoder();
83
+ for await (const chunk of s) {
84
+ text += dec.decode(chunk);
85
+ const m = /https:\/\/login\.tailscale\.com\/\S+/.exec(text);
86
+ if (m) return m[0];
87
+ }
88
+ return new Promise<string>(() => {}); // this stream ended without one: the other or the timer decides
89
+ })();
90
+ const found = await Promise.race([page(p.stdout as ReadableStream<Uint8Array>), page(p.stderr as ReadableStream<Uint8Array>), new Promise<string>((ok) => setTimeout(() => ok(""), 8000))]);
91
+ // Left running when it printed a page: it finishes the login once the user signs in.
92
+ if (found) return { url: found };
93
+ p.kill();
94
+ if ((await readPhone()).state !== "login") return { url: "" }; // it logged in without a page
95
+ return { error: OPERATOR.test(text) ? PERMISSION : "Open the Tailscale app on this computer and log in there." };
96
+ }
package/cli/pty.ts CHANGED
@@ -141,7 +141,7 @@ export function startPty(key: string, cmd: string[], cwd: string, pidFile?: stri
141
141
  env: { ...colorEnv(), ...opts.env, TERM: "xterm-256color", COLORTERM: "truecolor", KAIZEN_BOARD_PID: String(process.pid) },
142
142
  terminal: { cols: 120, rows: 32, data: (_t, d) => push(dec.decode(d, { stream: true })) },
143
143
  });
144
- if (opts.tmux && cmd[0] === tmuxBin()) p.tmux = opts.tmux;
144
+ if (opts.tmux && tmuxOk()) p.tmux = opts.tmux;
145
145
  ptys.set(key, p);
146
146
  if (pidFile) writeFileSync(pidFile, String(p.proc.pid));
147
147
  // A tmux-kept agent's PID is the pane's, not the client's: the client is gone after a
@@ -274,8 +274,30 @@ export const tmuxOk = () => !!tmuxBin();
274
274
  export const tmuxName = (key: string) => `kz-${key.replace(/[^\w-]/g, "_")}`;
275
275
  // PATH from this board, not the tmux server's own: the server keeps the environment of
276
276
  // whichever board started it.
277
- export const tmuxCmd = (name: string, cmd: string[]) => [tmuxBin()!, ...TMUX, "new-session", "-A", "-s", name, "-x", "120", "-y", "32", "-e", `PATH=${process.env.PATH ?? ""}`, ...cmd,
277
+ // Its own systemd scope where there is a user manager: a board run as a unit (kaizen-web.service)
278
+ // shares that unit's cgroup, and stopping or restarting the unit killed the whole cgroup,
279
+ // tmux server included, so the agents kept for the next board went with it. Probed once;
280
+ // no systemd-run, or no user bus (a container, a bare SSH login), runs tmux as before.
281
+ // It does not outlive logout without lingering (`loginctl enable-linger`): the user
282
+ // manager and all its scopes stop then.
283
+ let scoped: string[] | undefined;
284
+ export const scopeCmd = () => {
285
+ if (scoped) return scoped;
286
+ const run = process.platform === "linux" ? Bun.which("systemd-run") : null;
287
+ const cmd = run ? [run, "--user", "--scope", "--quiet", "--collect"] : [];
288
+ try { scoped = run && Bun.spawnSync([...cmd, "true"], { stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: 3000 }).exitCode === 0 ? cmd : []; } catch { scoped = []; }
289
+ return scoped;
290
+ };
291
+ // tmux draws on the alternate screen, which has no scrollback, so the card could not scroll
292
+ // back and a wheel reached the agent as arrow keys. mouse on: the wheel scrolls tmux's own
293
+ // history (copy-mode) instead, and a plain drag selects into tmux's buffer, so copying to
294
+ // the clipboard takes Shift+drag. Without the alternate screen (smcup@) a burst of output
295
+ // is redrawn as one screen and the lines between were lost, so that was not used.
296
+ // history-limit before new-session: a pane takes the limit it was created with.
297
+ export const tmuxCmd = (name: string, cmd: string[]) => [...scopeCmd(), tmuxBin()!, ...TMUX, "start-server", ";", "set", "-g", "history-limit", "10000",
298
+ ";", "new-session", "-A", "-s", name, "-x", "120", "-y", "32", "-e", `PATH=${process.env.PATH ?? ""}`, ...cmd,
278
299
  ";", "set", "-g", "status", "off", ";", "set", "-g", "prefix", "None", ";", "set", "-g", "escape-time", "0",
300
+ ";", "set", "-g", "mouse", "on", ";", "unbind", "-n", "MouseDown3Pane", ";", "unbind", "-n", "M-MouseDown3Pane",
279
301
  ";", "set", "-as", "terminal-features", ",xterm-256color:RGB"];
280
302
  export const attachCmd = (name: string) => [tmuxBin()!, ...TMUX, "attach-session", "-t", name];
281
303
  const tmux = (...a: string[]) => {
package/cli/settings.ts CHANGED
@@ -112,7 +112,7 @@ const SETTINGS: Setting[] = [
112
112
  { key: "review.executor", label: "Reviewer", group: "Agents", values: ["inline", "subagent", "ask"], help: "subagent: its own cold agent · inline: this session · ask: pick before review", when: ["runner", "lite"] },
113
113
  { key: "agent.default", label: "Default agent", group: "Agents", values: ["auto", "claude", "codex", "agy", "opencode", "gemini"], help: "" },
114
114
  { key: "agent.launch", label: "Where agents run", group: "Agents", values: ["card", "terminal"], help: "" },
115
- { key: "agent.keep_alive", label: "Keep agents through a kaizen restart", group: "Agents", values: ["off", "tmux"], help: "tmux: Linux and macOS with tmux installed", when: ["agent.launch", "card"] },
115
+ { key: "agent.keep_alive", label: "Keep agents through a kaizen restart", group: "Agents", values: ["off", "tmux"], help: "tmux: Linux and macOS with tmux installed. The wheel scrolls tmux history; Shift+drag copies", when: ["agent.launch", "card"] },
116
116
  { key: "agent.keep_awake", label: "Keep computer awake", group: "Board", values: ["off", "auto", "on"], help: "auto: while kaizen runs agents · on: while kaizen is open. Linux and macOS" },
117
117
  { key: "agent.heartbeat_minutes", label: "Agent heartbeat", group: "Board", values: ["2", "5", "10", "30"], help: "Minutes. A card says stale after two quiet intervals" },
118
118
  { key: "subagents.model", label: "Claude Code", group: "Agents", values: ["inherit", "opus", "sonnet", "haiku"], help: "Its stage subagents: planner, builder, reviewer", when: ["runner", "full"] },
package/cli/web.ts CHANGED
@@ -29,6 +29,7 @@ import * as google from "./google.ts";
29
29
  import { writeBacks } from "./writeback.ts";
30
30
  import { postLink, sendReply } from "./browser.ts";
31
31
  import { tailnetName } from "./setup.ts";
32
+ import { connectPhone, loginUrl, readPhone } from "./phone-setup.ts";
32
33
  import { listNotes, saveNote, renameNote, deleteNote, boardIndex, linksTo } from "./notes.ts";
33
34
  import * as video from "./video.ts";
34
35
  import * as auto from "./automations.ts";
@@ -84,6 +85,19 @@ const served = (f: string) => installed() === VERSION && existsSync(f) ? readTex
84
85
  // Loopback hosts only; shared by /open-url and /frameable so the board is never a way to reach other sites.
85
86
  const isLoopback = (u: URL) => ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname);
86
87
 
88
+ // The Preview button: the workspace's own `dev` (or `start`) script from package.json, run with
89
+ // the package manager its lockfile names. Never a command from the page or a run's text.
90
+ export function devCommand(dir: string): string[] | null {
91
+ let scripts: Record<string, unknown> = {};
92
+ try { scripts = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).scripts ?? {}; } catch { return null; }
93
+ const name = ["dev", "start"].find((n) => typeof scripts[n] === "string");
94
+ if (!name) return null;
95
+ const pm = existsSync(join(dir, "bun.lock")) || existsSync(join(dir, "bun.lockb")) ? "bun"
96
+ : existsSync(join(dir, "pnpm-lock.yaml")) ? "pnpm"
97
+ : existsSync(join(dir, "yarn.lock")) ? "yarn" : "npm";
98
+ return [pm, "run", name];
99
+ }
100
+
87
101
  // From `ss -ltnpH`: the ports listened on by a process whose working folder is inside ws.
88
102
  export function devPorts(ss: string, cwdOf: (pid: string) => string, ws: string): number[] {
89
103
  const ports = new Set<number>();
@@ -944,11 +958,24 @@ export async function web(repoDir: string, opts: Opts = {}) {
944
958
  if (typeof body.ws !== "string" || !(known() || (workspacesAge(cwd) > 1000 && (forgetWorkspaces(cwd), known())))) return bad("not a workspace of this project", 400);
945
959
  cwd = body.ws;
946
960
  }
961
+ let dev = false;
962
+ if (body.dev === true) {
963
+ const d = devCommand(cwd);
964
+ if (!d) return bad("no dev or start script in this folder's package.json", 404);
965
+ // Already running from this board in this folder: that terminal, not a second server.
966
+ const up = [...shells.values()].find((x) => x.ws === cwd && x.title === "dev server" && ptyState(x.key)?.alive);
967
+ if (up) return json(up);
968
+ // Through a login shell, so nvm/asdf/bun on the user's PATH resolve as in their terminal.
969
+ // Every word comes from the fixed lists in devCommand(), never from the request.
970
+ cmd = process.platform === "win32" ? ["cmd.exe", "/c", ...d] : [process.env.SHELL || "sh", "-lc", d.join(" ")];
971
+ dev = true;
972
+ }
947
973
  for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
948
974
  if ([...shells.values()].filter((x) => x.dir === dir).length >= SHELL_CAP) return bad(`at most ${SHELL_CAP} terminals per project: close one first`, 429);
949
975
  const key = "sh-" + crypto.randomUUID().slice(0, 8);
950
- const title = agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name + (bypass ? " · bypass" : "") : "shell";
951
- const pid = startPty(key, cmd, cwd, undefined, changed, { env: { KAIZEN_TERM: key } });
976
+ const title = dev ? "dev server" : agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name + (bypass ? " · bypass" : "") : "shell";
977
+ // A dev server it starts lets a phone in: Vite refuses a host it does not know (the tailnet name).
978
+ const pid = startPty(key, cmd, cwd, undefined, changed, { env: { KAIZEN_TERM: key, ...(dev ? { __VITE_ADDITIONAL_SERVER_ALLOWED_HOSTS: ".ts.net" } : {}) } });
952
979
  // The run workspace that opened it (its card key), so each run keeps its own centre.
953
980
  shells.set(key, { key, dir, title, agent, run: runKey, ws: cwd, pid });
954
981
  changed();
@@ -1097,7 +1124,8 @@ export async function web(repoDir: string, opts: Opts = {}) {
1097
1124
  const p = Bun.spawn(["ss", "-ltnpH"], { stdout: "pipe", stderr: "ignore", timeout: 3000 });
1098
1125
  out = await new Response(p.stdout).text();
1099
1126
  } catch { return json([]); }
1100
- return json(devPorts(out, (pid) => { try { return readlinkSync(`/proc/${pid}/cwd`); } catch { return ""; } }, ws));
1127
+ // Never the board itself: `kaizen web` started inside the workspace listens there too.
1128
+ return json(devPorts(out, (pid) => { try { return readlinkSync(`/proc/${pid}/cwd`); } catch { return ""; } }, ws).filter((p) => p !== port));
1101
1129
  }
1102
1130
  // A phone on the tailnet cannot reach this computer's localhost. Serves that loopback port
1103
1131
  // to the tailnet (`tailscale serve --https=<port>`, never funnel) and answers the address
@@ -1121,9 +1149,18 @@ export async function web(repoDir: string, opts: Opts = {}) {
1121
1149
  };
1122
1150
  const name = tailnetName((await run(["tailscale", "status", "--json"])).out);
1123
1151
  if (!name) return json({ ok: false, error: "Tailscale is not running on this computer" });
1124
- const s = await run(["tailscale", "serve", "--bg", `--https=${port}`, `${u.protocol}//127.0.0.1:${port}`]);
1152
+ // Vite and others listen on [::1] only: serve the loopback address that answers.
1153
+ const answers = async (h: string) => { try { await fetch(`${u.protocol}//${h}:${port}/`, { redirect: "manual", signal: AbortSignal.timeout(1500) }); return true; } catch { return false; } };
1154
+ const target = (await answers("127.0.0.1")) ? "127.0.0.1" : (await answers("[::1]")) ? "[::1]" : "127.0.0.1";
1155
+ const s = await run(["tailscale", "serve", "--bg", `--https=${port}`, `${u.protocol}//${target}:${port}`]);
1125
1156
  if (!s.ok) return json({ ok: false, error: /operator|root/i.test(s.err + s.out) ? "Tailscale needs permission once: run sudo tailscale set --operator=$USER on the computer running kaizen" : (s.err || s.out).trim().split("\n")[0] });
1126
- return json({ ok: true, url: `https://${name}:${port}${u.pathname}${u.search}${u.hash}` });
1157
+ // A dev server the agent started itself may still refuse the tailnet name: say how to allow it.
1158
+ let hint = "";
1159
+ try {
1160
+ const r = await fetch(`${u.protocol}//${target}:${port}/`, { headers: { host: `${name}:${port}` }, redirect: "manual", signal: AbortSignal.timeout(3000) });
1161
+ if (r.status === 403 && /allowedHosts|not allowed/i.test(await r.text())) hint = "The dev server refuses this address. Add allowedHosts: [\".ts.net\"] under server in vite.config, or stop it and tap Preview: kaizen starts it allowed.";
1162
+ } catch {}
1163
+ return json({ ok: true, url: `https://${name}:${port}${u.pathname}${u.search}${u.hash}`, hint });
1127
1164
  }
1128
1165
  // Whether a page may be framed: X-Frame-Options or a CSP frame-ancestors that is not
1129
1166
  // "*" says no. The browser hides that behind its own error page, so the localhost tab
@@ -1159,6 +1196,19 @@ export async function web(repoDir: string, opts: Opts = {}) {
1159
1196
  }
1160
1197
  return json(usageCache);
1161
1198
  }
1199
+ // Settings → Mobile and the onboarding phone step: where Tailscale stands, connect, log in.
1200
+ if (path === "/phone/setup") {
1201
+ if (!local(req)) return bad("cross-origin request refused", 403);
1202
+ if (req.method === "GET") return json(await readPhone());
1203
+ if (req.method !== "POST") return bad("method not allowed", 405);
1204
+ const refused = strict(req);
1205
+ if (refused) return refused;
1206
+ let body: any;
1207
+ try { body = await req.json(); } catch { return bad("json body expected"); }
1208
+ if (body?.do === "connect") return json(await connectPhone(port));
1209
+ if (body?.do === "login") return json(await loginUrl());
1210
+ return bad("do: connect or login");
1211
+ }
1162
1212
  if (req.method === "GET" && path === "/phone") {
1163
1213
  // Async: a hung tailscale must not stall every terminal socket on this event loop.
1164
1214
  let out = "";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kaizen-agent",
3
- "version": "1.66.0",
3
+ "version": "1.68.0",
4
4
  "description": "Staged workflow for AI agents — code, writing, research, operations: plan, human approval, build, independent review, bounded fix loop.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -58,6 +58,7 @@
58
58
  "@lezer/highlight": "1.2.5",
59
59
  "@xterm/addon-fit": "0.11.0",
60
60
  "@xterm/addon-search": "0.16.0",
61
+ "@xterm/addon-unicode11": "0.9.0",
61
62
  "@xterm/addon-web-links": "0.12.0",
62
63
  "@xterm/addon-webgl": "0.19.0",
63
64
  "@xterm/xterm": "6.0.0",
@@ -188,6 +188,10 @@ agent:
188
188
  # (tmux -L kaizen, your own sessions untouched) and keep working through
189
189
  # a kaizen restart or crash; the next kaizen shows them again mid-step.
190
190
  # Linux and macOS with tmux installed; elsewhere it acts as off.
191
+ # On Linux with systemd the server gets a scope of its own, so it also
192
+ # outlives a stop or restart of a systemd unit that runs kaizen. Through
193
+ # a logout only with lingering on: loginctl enable-linger.
194
+ # The wheel scrolls tmux's history; Shift+drag selects text to copy.
191
195
  keep_alive: off
192
196
  # Stops idle sleep from kaizen. off | auto (while kaizen runs agents) | on
193
197
  # (while kaizen is open). Linux and macOS; agents in an outside terminal don't count.
@@ -139,7 +139,10 @@ success poisons the review stage, which trusts this report.
139
139
 
140
140
  **A `## Preview` section says how to see the result.** For an app or service: the
141
141
  commands to start it locally and the URL to open, copied from the material's own README
142
- where one exists. For anything else — a document, copy, a runbook, a memo — the path
142
+ where one exists. An app with a dev server: leave it running when the build ends
143
+ (started in the background, its log in a file), and write its full `http://localhost:<port>`
144
+ address here; the board's Browser opens that address on its own, a phone included, and
145
+ its Preview button starts the folder's `dev` script when the server has stopped. For anything else — a document, copy, a runbook, a memo — the path
143
146
  to open, or the result itself when it fits in a screen. The board shows this section on
144
147
  the run's card, so a person can try the work without reading the rest of the report.
145
148
  Every run whose result shows on a screen must put at least one screenshot of it here,
@@ -1,15 +1,16 @@
1
- // First-run onboarding: one panel over the board with three steps (default agent, look,
2
- // notifications), then "Add your first project". Where a user got to is kept by the board in
1
+ // First-run onboarding: one panel over the board with four steps (default agent, look,
2
+ // notifications, phone), then "Add your first project". Where a user got to is kept by the board in
3
3
  // ~/.kaizen/onboarding.json (/onboarding), so a skipped or half-done flow can be continued from the
4
4
  // side menu's Setup row or the "Continue setup?" popup. Existing users, who have a project, never see it.
5
5
  import { html, raw } from "./dom.ts";
6
6
  import { openAdd } from "./add-project.ts";
7
+ import { mountPhone } from "./phone-setup.ts";
7
8
 
8
9
  type Cfg = { show: boolean; resume: boolean; step: number; total: number; default: string; installed: string[]; agents: { cmd: string; name: string }[]; install: Record<string, { command?: string; docs: string }> };
9
10
  // The tools agent.default accepts.
10
11
  const PICKABLE = ["claude", "codex", "agy", "opencode", "gemini"];
11
12
  const MOD = /Mac|iP(hone|ad)/.test(navigator.platform) ? "⌘" : "Ctrl";
12
- const NAMES = ["Default agent", "Appearance", "Notifications"];
13
+ const NAMES = ["Default agent", "Appearance", "Notifications", "Phone"];
13
14
  const ASKED = "kz-onb-asked";
14
15
 
15
16
  async function call(path: string, body?: object) {
@@ -30,7 +31,7 @@ let more = false;
30
31
 
31
32
  // The side menu's Setup row follows what is saved.
32
33
  const row = (s: number, outcome: string | null) =>
33
- (window as any).kzSetupRow?.({ resume: outcome === "skipped" || (outcome === null && s > 0), step: s, total: cfg?.total ?? 3 });
34
+ (window as any).kzSetupRow?.({ resume: outcome === "skipped" || (outcome === null && s > 0), step: s, total: cfg?.total ?? 4 });
34
35
 
35
36
  const save = (patch: { step?: number; outcome?: string | null }) => {
36
37
  row(patch.step ?? step, patch.outcome ?? null);
@@ -89,6 +90,7 @@ const COPY = [
89
90
  { title: "Pick your default agent", sub: "kaizen works with every CLI agent. Choose the one you will reach for most. You can change it any time in Settings.", body: agents },
90
91
  { title: "Choose your look", sub: "Follow your system, or pick light or dark. You can change it any time.", body: looks },
91
92
  { title: "Set up notifications", sub: "kaizen can tell you when a run needs you or an agent is done.", body: alerts },
93
+ { title: "Use kaizen on your phone", sub: "Optional. Check runs and answer agents from your phone. Continue to skip; it is also in Settings → Mobile.", body: () => html`<div class="onb-panel" id="onb-phone"></div>` },
92
94
  ];
93
95
 
94
96
  function draw() {
@@ -102,6 +104,8 @@ function draw() {
102
104
  <div class="onb-prog">${COPY.map((_, i) => html`<button type="button" class="${i === step ? "on" : i < step ? "was" : ""}" data-s="${i}" aria-label="Go to step ${i + 1}: ${NAMES[i]}" title="${NAMES[i]}"></button>`)}<span>${step + 1} of ${c.total}</span></div>
103
105
  <div class="onb-main">${step === 0 ? html`<small class="onb-eb">Welcome to kaizen</small>` : ""}<h2>${s.title}</h2><p class="onb-sub">${s.sub}</p>${s.body()}</div>
104
106
  <div class="onb-ft"><button type="button" class="onb-lnk" data-a="skip">Skip to project setup</button><span></span>${step > 0 ? html`<button type="button" class="btn" data-a="back">‹ Back</button>` : ""}<button type="button" class="btn pri" data-a="next">${last ? "Add your first project" : "Continue"}<kbd>${MOD} ↵</kbd></button></div>`);
107
+ const ph = dlg!.querySelector<HTMLElement>("#onb-phone");
108
+ if (ph) void mountPhone(ph);
105
109
  dlg!.querySelector<HTMLElement>(step === 0 ? ".onb-card[aria-checked=true]" : "[data-a=next]")?.focus();
106
110
  }
107
111
 
@@ -0,0 +1,79 @@
1
+ // The phone card: Settings → Mobile and the onboarding phone step. Walks the user from no
2
+ // Tailscale to a QR the phone scans, through /phone/setup on the board.
3
+ import { html, raw } from "./dom.ts";
4
+
5
+ type State = { state: "missing" | "login" | "ready" | "connected"; account: string; url: string; phones: { name: string; online: boolean }[]; qr: string };
6
+
7
+ const DOWNLOAD = "https://tailscale.com/download";
8
+
9
+ async function call(body?: object) {
10
+ try {
11
+ const r = await fetch("/phone/setup", body ? { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) } : undefined);
12
+ return await r.json();
13
+ } catch {
14
+ return { error: "The board did not answer." };
15
+ }
16
+ }
17
+
18
+ const btn = (a: string, text: string, pri = false) => html`<button type="button" class="btn${pri ? " pri" : ""}" data-ph="${a}">${text}</button>`;
19
+ const ol = (items: unknown[]) => html`<ol class="ph-steps">${items.map((i) => html`<li>${i}</li>`)}</ol>`;
20
+
21
+ function body(s: State, err: string, busy: boolean) {
22
+ const e = err ? html`<p class="ph-err" role="alert">${err}</p>` : "";
23
+ const acct = s.account ? html`<b>${s.account}</b>` : "the same account";
24
+ if (s.state === "missing")
25
+ return html`<p>Your phone reaches this computer through Tailscale, a free private network between your own devices.</p>${ol([
26
+ "Install Tailscale on this computer and log in.",
27
+ "Install it on your phone too and log in with the same account.",
28
+ ])}<div class="ph-row"><a class="btn pri" href="${DOWNLOAD}" target="_blank" rel="noopener">Install Tailscale</a>${btn("check", "Check again")}</div>${e}`;
29
+ if (s.state === "login")
30
+ return html`<p>Tailscale is installed but not logged in on this computer.</p><div class="ph-row">${btn("login", busy ? "Opening…" : "Log in to Tailscale", true)}${btn("check", "Check again")}</div>${e}`;
31
+ if (s.state === "ready")
32
+ return html`<p>Tailscale is running${s.account ? html` as ${acct}` : ""}. Connect to show the code your phone scans.</p><div class="ph-row">${btn("connect", busy ? "Connecting…" : "Connect phone", true)}</div>${e}`;
33
+ const on = s.phones.some((p) => p.online);
34
+ return html`<div class="ph-on">${s.qr ? html`<div class="ph-qr" aria-label="QR code for ${s.url}">${raw(s.qr)}</div>` : ""}<div><p class="ph-h">On your phone</p>${ol([
35
+ html`Install Tailscale from the <a href="${DOWNLOAD}" target="_blank" rel="noopener">App Store or Play Store</a>.`,
36
+ s.account ? html`Log in with ${acct}, the account this computer uses.` : "Log in with the same account as this computer.",
37
+ html`Scan this code with the camera, or open <a href="${s.url}" target="_blank" rel="noopener">${s.url}</a>.`,
38
+ "Choose Add to Home screen so it opens like an app.",
39
+ ])}<p class="ph-st"><i class="ph-dot${on ? " on" : ""}"></i>${on ? `Phone online: ${s.phones.filter((p) => p.online).map((p) => p.name).join(", ")}` : s.phones.length ? "Phone on your tailnet, offline right now" : "No phone on your tailnet yet"}</p></div></div><p class="ph-note">Anyone on your tailnet can use this board. Keep the tailnet to your own devices, or limit it with Tailscale access rules.</p>${e}`;
40
+ }
41
+
42
+ // Draws into `el` and keeps it current while it is on the page.
43
+ export async function mountPhone(el: HTMLElement) {
44
+ let s: State | null = null, err = "", busy = false;
45
+ const draw = () => {
46
+ if (s) el.innerHTML = String(body(s, err, busy));
47
+ };
48
+ const load = async () => {
49
+ const r = await call();
50
+ if (r.error) err = r.error;
51
+ else s = r;
52
+ draw();
53
+ };
54
+ el.innerHTML = `<p class="ph-wait">Checking Tailscale…</p>`;
55
+ el.onclick = async (ev) => {
56
+ const a = (ev.target as HTMLElement).closest<HTMLElement>("[data-ph]")?.dataset.ph;
57
+ if (!a || busy) return;
58
+ err = "";
59
+ if (a === "check") return load();
60
+ busy = true;
61
+ draw();
62
+ const r = await call({ do: a });
63
+ busy = false;
64
+ if (r.error) err = r.error;
65
+ else if (a === "login") {
66
+ if (r.url) window.open(r.url, "_blank", "noopener");
67
+ // The sign-in happens in the browser: look again until Tailscale is running, for two minutes.
68
+ for (let i = 0; i < 40 && el.isConnected && s?.state === "login"; i++) {
69
+ await new Promise((ok) => setTimeout(ok, 3000));
70
+ const n = await call();
71
+ if (!n.error) s = n;
72
+ }
73
+ } else s = r;
74
+ draw();
75
+ };
76
+ await load();
77
+ // The phone's dot follows it joining the tailnet; stops once the card leaves the page.
78
+ const t = setInterval(() => (el.isConnected ? s?.state === "connected" && !busy && void load() : clearInterval(t)), 10_000);
79
+ }
@@ -243,7 +243,7 @@ function draw() {
243
243
  first = item(ids[0]),
244
244
  title = ids.map((id) => item(id).title).join(" + ");
245
245
  return html`<button class="rtab${sc.id === s.on ? " on" : ""}" data-t="${sc.id}" draggable="true" title="${title}">${icon(first)}<span>${title}</span><i data-xs="${sc.id}" role="button" aria-label="Close ${title}" title="Close tab">×</i></button>`;
246
- })}<details class="radd" data-mode="tab"><summary class="rbtn" title="New tab" aria-label="New tab">${ico("plus")}</summary>${menu}</details><span class="sp"></span>${cur ? html`<details class="radd rsplit" data-mode="cols"><summary class="rbtn" title="Split right: add to this tab" aria-label="Split right">${ico("lcols")}</summary>${menu}</details><details class="radd rsplit" data-mode="rows"><summary class="rbtn" title="Split down: add to this tab" aria-label="Split down">${ico("lrows")}</summary>${menu}</details>` : ""}`,
246
+ })}<details class="radd" data-mode="tab"><summary class="rbtn" title="New tab" aria-label="New tab">${ico("plus")}</summary>${menu}</details><button type="button" class="rbtn" data-pv title="Preview: open the app, starting its dev server if it is off" aria-label="Preview">${ico("eye")}</button><span class="sp"></span>${cur ? html`<details class="radd rsplit" data-mode="cols"><summary class="rbtn" title="Split right: add to this tab" aria-label="Split right">${ico("lcols")}</summary>${menu}</details><details class="radd rsplit" data-mode="rows"><summary class="rbtn" title="Split down: add to this tab" aria-label="Split down">${ico("lrows")}</summary>${menu}</details>` : ""}`,
247
247
  );
248
248
  $("rside").setAttribute("aria-pressed", String(document.body.classList.contains("rflip")));
249
249
  $("rtabs").querySelector(".rtab.on")?.scrollIntoView({ block: "nearest", inline: "nearest" });
@@ -498,7 +498,8 @@ function browser(el: HTMLElement) {
498
498
  .then((j) => {
499
499
  if (url !== u) return;
500
500
  if (!j.ok) return void (note.textContent = `${far} (${j.error})`);
501
- note.hidden = true;
501
+ note.hidden = !j.hint;
502
+ note.textContent = j.hint || "";
502
503
  frame.hidden = false;
503
504
  frame.src = j.url;
504
505
  if (ext) ext.href = j.url;
@@ -630,6 +631,64 @@ async function newPty(agent?: string) {
630
631
  show("sh:" + sh.key);
631
632
  }
632
633
 
634
+ // The Preview button: the workspace's app in the Browser tab. A dev server already listening
635
+ // opens at once; otherwise the board starts the folder's dev script in a terminal here, waits
636
+ // for its port, then opens it. No dev script: the run's Preview (report and screenshots).
637
+ let starting = false;
638
+ async function previewApp() {
639
+ if (!ctx || starting) return;
640
+ const c = ctx;
641
+ const ports = async (): Promise<number[]> => {
642
+ try {
643
+ return await (await fetch("/devports?ws=" + encodeURIComponent(c.ws))).json();
644
+ } catch {
645
+ return [];
646
+ }
647
+ };
648
+ // The newest run here names the page to open (its ## Preview), when it has one.
649
+ const card = store.S.cards.filter((x) => x.state === c.dir && wsOfCard(x) === c.ws && x.id).sort((a, b) => String(b.id).localeCompare(String(a.id)))[0];
650
+ let pv = "";
651
+ try {
652
+ if (card) pv = preview((await (await fetch(`/run/${encodeURIComponent(card.id)}?dir=${encodeURIComponent(c.dir)}`)).json()).impl) ?? "";
653
+ } catch {}
654
+ const openAt = (u: string) => {
655
+ try {
656
+ localStorage.setItem("kz-browse:" + c.k, u);
657
+ } catch {}
658
+ addTab({ id: "local", kind: "local", title: "Browser" });
659
+ (panes.get("local")?.el as any)?.browseTo?.(u);
660
+ };
661
+ const now = await ports();
662
+ if (now.length) return openAt(devUrl(pv, now)!);
663
+ const u = devUrl(pv, []);
664
+ const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ dir: c.dir, ws: c.ws, run: c.k, dev: true }) }).catch(() => null);
665
+ if (!r?.ok) {
666
+ let why = "";
667
+ try {
668
+ why = (await r!.json()).error;
669
+ } catch {}
670
+ toast(why ? `Preview: ${why}` : "Preview: the dev server did not start");
671
+ return openPreview();
672
+ }
673
+ const sh = await r.json();
674
+ if (!shells.some((x) => x.key === sh.key)) shells.push(sh);
675
+ draw();
676
+ starting = true;
677
+ toast("Starting the app…");
678
+ try {
679
+ // Up to a minute for the first port; Linux only reads ports, elsewhere the run's address after a pause.
680
+ for (let i = 0; i < 40 && ctx?.k === c.k; i++) {
681
+ await new Promise((ok) => setTimeout(ok, 1500));
682
+ const p = await ports();
683
+ if (p.length) return openAt(devUrl(pv, p)!);
684
+ if (i === 5 && u && !navigator.platform.startsWith("Linux")) return openAt(u);
685
+ }
686
+ if (ctx?.k === c.k) toast("The app did not open a port. Its terminal tab shows why.");
687
+ } finally {
688
+ starting = false;
689
+ }
690
+ }
691
+
633
692
  async function closeTab(id: string) {
634
693
  const s = saved();
635
694
  if (id.startsWith("sh:")) {
@@ -685,6 +744,7 @@ function wire() {
685
744
  save();
686
745
  return draw();
687
746
  }
747
+ if (t.closest("[data-pv]")) return void previewApp();
688
748
  const n = t.closest<HTMLElement>("[data-n]")?.dataset.n;
689
749
  if (n) {
690
750
  const d = t.closest<HTMLDetailsElement>(".radd")!;
@@ -11,6 +11,7 @@ import { modelInput, modelLabel, orchestrationRows } from "./settings-orchestrat
11
11
  import { cleanupRows, wireCleanup } from "./settings-cleanup.ts";
12
12
  import { automationRows, wireAutomations } from "./settings-automations.ts";
13
13
  import { skillRows, wireSkills } from "./settings-skills.ts";
14
+ import { mountPhone } from "./phone-setup.ts";
14
15
  import { fillMics, micRow } from "./settings-voice.ts";
15
16
  import { placeOf, SETTINGS_NAV } from "./settings-pages.ts";
16
17
  import { askNotify, notifyOn, playSound, soundPick, SOUNDS, toast } from "./toast.ts";
@@ -160,7 +161,7 @@ export async function openSettings() {
160
161
  }
161
162
  }
162
163
  put("voice", "Dictation", row("Microphone", micRow(), "Used by this browser. Names appear after you first allow the microphone. Ctrl+Alt+D dictates into the focused terminal.", "v-mic", "microphone input device mic dictation shortcut"));
163
- put("mobile", "Phone", row("Phone address", cfg?.phoneUrls?.length ? html`<span class="phoneurls">${cfg.phoneUrls.map((url) => html`<a href="${url}" target="_blank" rel="noopener">${url}</a>`)}</span>` : html`<span>Not set</span>`, cfg?.phoneUrls?.length ? "Configured address; Tailscale must be running on both devices." : "Run kaizen setup on this PC to connect your phone.", "phone-url", "phone address url tailscale setup"));
164
+ put("mobile", "Phone", html`<div class="srow ph-card" data-q="phone mobile tailscale qr connect address setup"><div id="phset"></div></div>`);
164
165
  put("integrations", "Google", row("OAuth client id", html`<input class="sel" id="gg-id" placeholder="${gg.hasClient ? "Saved. Paste a new one to replace it" : "Desktop app client id from Google Cloud"}" spellcheck="false" autocomplete="off">`, "", "gg-id", "google oauth client id sheets write back"));
165
166
  put("integrations", "Google", row("OAuth client secret", html`<span class="fpick"><input class="sel" id="gg-secret" type="password" placeholder="${gg.hasClient ? "Saved. Paste a new one to replace it" : ""}" spellcheck="false" autocomplete="off"><button class="btn" id="gg-save" type="button">Save</button></span>`, "", "gg-secret", "google oauth client secret"));
166
167
  let hapton = true;
@@ -260,6 +261,7 @@ export async function openSettings() {
260
261
  if (cl) wireCleanup(cl, openSettings);
261
262
  fillMics();
262
263
  if (ac) wireAccounts(openSettings);
264
+ if ($("phset")) void mountPhone($("phset"));
263
265
  filter();
264
266
  $("smain").scrollTop = top;
265
267
  if (hadFocus) {