@k-electron/k-bench 0.0.0 → 0.1.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.
@@ -0,0 +1,217 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { statSync } from "node:fs";
3
+ import { basename, resolve } from "node:path";
4
+ import { availableName } from "./naming.js";
5
+ import { Reconciler } from "./reconciler.js";
6
+ /** A failure the HTTP layer maps to a status code. */
7
+ export class ServiceError extends Error {
8
+ kind;
9
+ constructor(kind, message) {
10
+ super(message);
11
+ this.kind = kind;
12
+ }
13
+ }
14
+ function isDirectory(path) {
15
+ try {
16
+ return statSync(path).isDirectory();
17
+ }
18
+ catch {
19
+ return false;
20
+ }
21
+ }
22
+ /** The domain operations. The store holds what the owner chose; tmux says what is alive. */
23
+ export class Service {
24
+ store;
25
+ tmux;
26
+ sessionCreations = Promise.resolve();
27
+ reconciler;
28
+ restarts = new Map();
29
+ constructor(store, tmux) {
30
+ this.store = store;
31
+ this.tmux = tmux;
32
+ this.reconciler = new Reconciler(store, tmux);
33
+ }
34
+ /** Kills tmux sessions that have no store record. Runs at startup and on every state read. */
35
+ async reconcile() {
36
+ await this.reconciler.reconcile();
37
+ }
38
+ createWorkspace(input) {
39
+ const folder = resolve(input.folder);
40
+ if (!isDirectory(folder)) {
41
+ throw new ServiceError("invalid", `Folder does not exist: ${folder}`);
42
+ }
43
+ const explicit = input.name?.trim();
44
+ if (explicit)
45
+ this.assertWorkspaceNameFree(explicit);
46
+ const name = explicit || availableName(basename(folder), this.workspaceNames());
47
+ const { id } = this.store.addWorkspace({ name, folder });
48
+ return { id, name, folder };
49
+ }
50
+ /** Renames and/or re-folders a Workspace; both changes are checked before either is made. */
51
+ updateWorkspace(id, changes) {
52
+ const workspace = this.store.getWorkspace(id);
53
+ if (!workspace)
54
+ throw new ServiceError("not_found", "Unknown Workspace");
55
+ const update = {};
56
+ if (changes.name !== undefined) {
57
+ const name = changes.name.trim();
58
+ if (!name)
59
+ throw new ServiceError("invalid", "name must not be blank");
60
+ this.assertWorkspaceNameFree(name, id);
61
+ update.name = name;
62
+ }
63
+ if (changes.folder !== undefined) {
64
+ const folder = resolve(changes.folder);
65
+ if (!isDirectory(folder)) {
66
+ throw new ServiceError("invalid", `Folder does not exist: ${folder}`);
67
+ }
68
+ update.folder = folder;
69
+ }
70
+ this.store.updateWorkspace(id, update);
71
+ return { ...workspace, ...update };
72
+ }
73
+ /** `ids` must be every Workspace exactly once, in the order the owner wants. */
74
+ reorderWorkspaces(ids) {
75
+ const known = this.store.listWorkspaces().map((w) => w.id);
76
+ if (ids.length !== known.length || !known.every((id) => ids.includes(id))) {
77
+ throw new ServiceError("invalid", "ids must list every Workspace exactly once");
78
+ }
79
+ this.store.setWorkspaceOrder(ids);
80
+ }
81
+ /** Ends the Workspace's shells first, then forgets it. The folder on disk is never touched. */
82
+ async deleteWorkspace(id) {
83
+ if (!this.store.getWorkspace(id))
84
+ throw new ServiceError("not_found", "Unknown Workspace");
85
+ const ids = this.store.listSessions(id).map((session) => session.id);
86
+ // Every shell gets its kill, even if one fails; a failure keeps the Workspace so the
87
+ // owner can retry (killing is idempotent), instead of leaving a half-killed one.
88
+ const kills = await Promise.allSettled(ids.map((sessionId) => this.tmux.killSession(sessionId)));
89
+ const failed = kills.find((kill) => kill.status === "rejected");
90
+ if (failed)
91
+ throw failed.reason;
92
+ this.store.deleteWorkspace(id);
93
+ }
94
+ workspaceNames(exceptId) {
95
+ return new Set(this.store
96
+ .listWorkspaces()
97
+ .filter((w) => w.id !== exceptId)
98
+ .map((w) => w.name));
99
+ }
100
+ /** Workspace names are unique. Renaming reuses this, passing the Workspace being renamed. */
101
+ assertWorkspaceNameFree(name, exceptId) {
102
+ if (this.workspaceNames(exceptId).has(name)) {
103
+ throw new ServiceError("conflict", `A Workspace named "${name}" already exists`);
104
+ }
105
+ }
106
+ /**
107
+ * One at a time: choosing the name and storing the Session are separated by starting
108
+ * the shell, so overlapping creations would otherwise pick the same default name.
109
+ */
110
+ createSession(workspaceId, requestedName) {
111
+ const result = this.sessionCreations.then(() => this.createSessionNow(workspaceId, requestedName));
112
+ this.sessionCreations = result.catch(() => undefined);
113
+ return result;
114
+ }
115
+ async createSessionNow(workspaceId, requestedName) {
116
+ const workspace = this.store.getWorkspace(workspaceId);
117
+ if (!workspace)
118
+ throw new ServiceError("not_found", "Unknown Workspace");
119
+ if (!isDirectory(workspace.folder)) {
120
+ throw new ServiceError("invalid", `Folder does not exist: ${workspace.folder}`);
121
+ }
122
+ const taken = new Set(this.store.listSessions(workspaceId).map((s) => s.name));
123
+ let name = requestedName?.trim();
124
+ if (!name) {
125
+ let n = 1;
126
+ while (taken.has(`session ${n}`))
127
+ n++;
128
+ name = `session ${n}`;
129
+ }
130
+ else if (taken.has(name)) {
131
+ throw new ServiceError("conflict", `A Session named "${name}" already exists`);
132
+ }
133
+ const id = randomUUID();
134
+ await this.reconciler.whileStarting(id, async () => {
135
+ await this.tmux.createSession(id, workspace.folder);
136
+ try {
137
+ this.store.addSession({ id, workspaceId, name });
138
+ }
139
+ catch (error) {
140
+ await this.tmux.killSession(id);
141
+ throw error;
142
+ }
143
+ });
144
+ return { id, name };
145
+ }
146
+ renameSession(sessionId, requestedName) {
147
+ const session = this.store.getSession(sessionId);
148
+ if (!session)
149
+ throw new ServiceError("not_found", "Unknown Session");
150
+ const name = requestedName.trim();
151
+ if (!name)
152
+ throw new ServiceError("invalid", "name is required");
153
+ const clash = this.store
154
+ .listSessions(session.workspaceId)
155
+ .some((other) => other.id !== sessionId && other.name === name);
156
+ if (clash) {
157
+ throw new ServiceError("conflict", `A Session named "${name}" already exists`);
158
+ }
159
+ this.store.renameSession(sessionId, name);
160
+ return { id: sessionId, name };
161
+ }
162
+ /** Ends the Session's shell and everything in it, then forgets the Session. */
163
+ async deleteSession(sessionId) {
164
+ if (!this.store.getSession(sessionId)) {
165
+ throw new ServiceError("not_found", "Unknown Session");
166
+ }
167
+ await this.tmux.killSession(sessionId);
168
+ this.store.deleteSession(sessionId);
169
+ }
170
+ async getState() {
171
+ const live = await this.reconciler.reconcile();
172
+ return {
173
+ workspaces: this.store.listWorkspaces().map((workspace) => ({
174
+ ...workspace,
175
+ missing: !isDirectory(workspace.folder),
176
+ sessions: this.store.listSessions(workspace.id).map((session) => ({
177
+ id: session.id,
178
+ name: session.name,
179
+ status: live.has(session.id) ? "running" : "stopped",
180
+ bell: live.get(session.id)?.bell ?? false,
181
+ })),
182
+ })),
183
+ };
184
+ }
185
+ /**
186
+ * Gives a Stopped Session a fresh shell in its Workspace folder, keeping its id and name.
187
+ * A Session that is already running is left alone.
188
+ */
189
+ async restartSession(sessionId) {
190
+ const session = this.store.getSession(sessionId);
191
+ if (!session)
192
+ throw new ServiceError("not_found", "Unknown Session");
193
+ // Two restarts of the same Session (a double click) share one start.
194
+ let restart = this.restarts.get(sessionId);
195
+ if (!restart) {
196
+ restart = this.startStopped(session).finally(() => this.restarts.delete(sessionId));
197
+ this.restarts.set(sessionId, restart);
198
+ }
199
+ await restart;
200
+ return { id: session.id, name: session.name };
201
+ }
202
+ async startStopped(session) {
203
+ if ((await this.tmux.listSessions()).some((live) => live.id === session.id))
204
+ return;
205
+ if (!isDirectory(session.folder)) {
206
+ throw new ServiceError("invalid", `Folder does not exist: ${session.folder}`);
207
+ }
208
+ await this.reconciler.whileStarting(session.id, () => this.tmux.createSession(session.id, session.folder));
209
+ }
210
+ /** Whether the terminal WebSocket has a shell to attach to: a known Session that is running. */
211
+ async hasRunningShell(sessionId) {
212
+ if (!this.store.getSession(sessionId))
213
+ return false;
214
+ const live = await this.tmux.listSessions();
215
+ return live.some((s) => s.id === sessionId);
216
+ }
217
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Change detection for the events WebSocket. It reads the state, and whenever the result
3
+ * differs from the last one sent, pushes the fresh snapshot to every subscriber.
4
+ *
5
+ * Two things trigger a read: `notify()`, which the HTTP layer calls after a mutation and the
6
+ * Bell watch calls when a Bell changes, and a short-interval poll, which notices what nothing
7
+ * announces (a shell exiting). The poll only runs while someone is subscribed.
8
+ *
9
+ * Every snapshot carries a `revision`: the number of `notify()` calls made before its read
10
+ * began. So a snapshot at revision `n` or later shows every change announced by the `n`th
11
+ * `notify()`, which returns `n`. A client that made a change waits for that revision, rather
12
+ * than for the change itself. A notify that turns out to change nothing still gets a
13
+ * snapshot carrying its revision, so nobody waits for one that never comes. Revisions start
14
+ * again from 0 when the server restarts.
15
+ */
16
+ export class StateFeed {
17
+ read;
18
+ intervalMs;
19
+ listeners = new Set();
20
+ /** Subscribers that have not been sent anything yet: they get the snapshot unchanged or not. */
21
+ fresh = new Set();
22
+ last;
23
+ /** How many times `notify()` has been called. */
24
+ revision = 0;
25
+ /** The revision of the last snapshot sent to every subscriber. */
26
+ sentRevision = 0;
27
+ timer;
28
+ reading;
29
+ dirty = false;
30
+ constructor(read, options = {}) {
31
+ this.read = read;
32
+ this.intervalMs = options.intervalMs ?? 400;
33
+ }
34
+ /** Subscribes to snapshots, starting with the current one. Returns the unsubscribe function. */
35
+ subscribe(listener) {
36
+ this.listeners.add(listener);
37
+ this.fresh.add(listener);
38
+ if (!this.timer) {
39
+ this.timer = setInterval(() => void this.refresh(), this.intervalMs);
40
+ this.timer.unref();
41
+ }
42
+ void this.refresh();
43
+ return () => {
44
+ this.listeners.delete(listener);
45
+ this.fresh.delete(listener);
46
+ if (this.listeners.size === 0)
47
+ this.stop();
48
+ };
49
+ }
50
+ /**
51
+ * Something may have changed: re-read now rather than at the next poll. Returns the
52
+ * revision from which snapshots show the change.
53
+ */
54
+ notify() {
55
+ this.revision++;
56
+ if (this.listeners.size > 0)
57
+ void this.refresh();
58
+ return this.revision;
59
+ }
60
+ /** Stops polling and drops every subscriber. */
61
+ stop() {
62
+ if (this.timer)
63
+ clearInterval(this.timer);
64
+ this.timer = undefined;
65
+ this.listeners.clear();
66
+ this.fresh.clear();
67
+ this.last = undefined;
68
+ this.dirty = false;
69
+ }
70
+ /** Stops, then waits for a read that is still running, so nothing reads afterwards. */
71
+ async close() {
72
+ this.stop();
73
+ await this.reading;
74
+ }
75
+ /** One read at a time; a request that arrives during a read triggers another straight after. */
76
+ refresh() {
77
+ if (this.reading) {
78
+ this.dirty = true;
79
+ return this.reading;
80
+ }
81
+ this.reading = (async () => {
82
+ try {
83
+ do {
84
+ this.dirty = false;
85
+ await this.readOnce();
86
+ } while (this.dirty);
87
+ }
88
+ finally {
89
+ this.reading = undefined;
90
+ }
91
+ })();
92
+ return this.reading;
93
+ }
94
+ async readOnce() {
95
+ // Taken before the read starts, so the state read is at least this fresh.
96
+ const revision = this.revision;
97
+ let state;
98
+ try {
99
+ state = await this.read();
100
+ }
101
+ catch (error) {
102
+ console.error("state feed could not read the state", error);
103
+ return;
104
+ }
105
+ const body = JSON.stringify(state);
106
+ const changed = body !== this.last || revision !== this.sentRevision;
107
+ this.last = body;
108
+ this.sentRevision = revision;
109
+ const snapshot = JSON.stringify({ revision, ...state });
110
+ const targets = changed ? [...this.listeners] : [...this.fresh];
111
+ this.fresh.clear();
112
+ for (const listener of targets)
113
+ listener(snapshot);
114
+ }
115
+ }
@@ -0,0 +1,46 @@
1
+ import { readFile, stat } from "node:fs/promises";
2
+ import { extname, join, normalize, resolve, sep } from "node:path";
3
+ import { getMimeType } from "hono/utils/mime";
4
+ async function isFile(path) {
5
+ try {
6
+ return (await stat(path)).isFile();
7
+ }
8
+ catch {
9
+ return false;
10
+ }
11
+ }
12
+ /**
13
+ * Serves the built front end from `webDir`. Any GET that is not the API and does not name a
14
+ * file falls back to `index.html`, so the single-page app owns every other URL.
15
+ */
16
+ export function mountStatic(app, webDir) {
17
+ const root = resolve(webDir);
18
+ app.get("*", async (c) => {
19
+ let pathname;
20
+ try {
21
+ pathname = decodeURIComponent(new URL(c.req.url).pathname);
22
+ }
23
+ catch {
24
+ return c.notFound(); // A malformed percent escape names no file.
25
+ }
26
+ if (pathname.startsWith("/api/"))
27
+ return c.notFound();
28
+ const requested = resolve(join(root, normalize(pathname)));
29
+ const insideRoot = requested === root || requested.startsWith(root + sep);
30
+ const hasExtension = extname(pathname) !== "";
31
+ const file = insideRoot && (await isFile(requested)) ? requested : undefined;
32
+ if (!file && hasExtension)
33
+ return c.notFound();
34
+ const path = file ?? join(root, "index.html");
35
+ if (!(await isFile(path)))
36
+ return c.notFound();
37
+ const type = getMimeType(path) ?? "application/octet-stream";
38
+ return c.body(await readFile(path), 200, {
39
+ "content-type": type,
40
+ // Built assets are content-hashed; the HTML shell must always be revalidated.
41
+ "cache-control": file?.includes(`${sep}assets${sep}`)
42
+ ? "public, max-age=31536000, immutable"
43
+ : "no-cache",
44
+ });
45
+ });
46
+ }
@@ -0,0 +1,127 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdirSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { DatabaseSync } from "node:sqlite";
5
+ /**
6
+ * Migrations run in order on startup; `PRAGMA user_version` records how many have run.
7
+ * Append only. Per ADR-0002 nothing here records process IDs or running/Stopped status.
8
+ */
9
+ const MIGRATIONS = [
10
+ `
11
+ CREATE TABLE workspaces (
12
+ id TEXT PRIMARY KEY,
13
+ name TEXT NOT NULL UNIQUE,
14
+ folder TEXT NOT NULL,
15
+ position INTEGER NOT NULL
16
+ );
17
+ CREATE TABLE sessions (
18
+ id TEXT PRIMARY KEY,
19
+ workspace_id TEXT NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,
20
+ name TEXT NOT NULL,
21
+ created_at INTEGER NOT NULL,
22
+ UNIQUE (workspace_id, name)
23
+ );
24
+ `,
25
+ ];
26
+ export class Store {
27
+ db;
28
+ constructor(dataDir) {
29
+ mkdirSync(dataDir, { recursive: true });
30
+ this.db = new DatabaseSync(join(dataDir, "k-bench.db"));
31
+ this.db.exec("PRAGMA foreign_keys = ON; PRAGMA journal_mode = WAL;");
32
+ this.migrate();
33
+ }
34
+ migrate() {
35
+ const row = this.db.prepare("PRAGMA user_version").get();
36
+ for (let version = row.user_version; version < MIGRATIONS.length; version++) {
37
+ this.db.exec("BEGIN");
38
+ try {
39
+ this.db.exec(MIGRATIONS[version]);
40
+ this.db.exec(`PRAGMA user_version = ${version + 1}`);
41
+ this.db.exec("COMMIT");
42
+ }
43
+ catch (error) {
44
+ this.db.exec("ROLLBACK");
45
+ throw error;
46
+ }
47
+ }
48
+ }
49
+ close() {
50
+ this.db.close();
51
+ }
52
+ listWorkspaces() {
53
+ return this.db
54
+ .prepare("SELECT id, name, folder, position FROM workspaces ORDER BY position")
55
+ .all();
56
+ }
57
+ getWorkspace(id) {
58
+ return this.db
59
+ .prepare("SELECT id, name, folder, position FROM workspaces WHERE id = ?")
60
+ .get(id);
61
+ }
62
+ addWorkspace(input) {
63
+ const id = randomUUID();
64
+ const next = this.db
65
+ .prepare("SELECT COALESCE(MAX(position), -1) + 1 AS position FROM workspaces")
66
+ .get();
67
+ this.db
68
+ .prepare("INSERT INTO workspaces (id, name, folder, position) VALUES (?, ?, ?, ?)")
69
+ .run(id, input.name, input.folder, next.position);
70
+ return { id, name: input.name, folder: input.folder, position: next.position };
71
+ }
72
+ updateWorkspace(id, changes) {
73
+ if (changes.name !== undefined) {
74
+ this.db
75
+ .prepare("UPDATE workspaces SET name = ? WHERE id = ?")
76
+ .run(changes.name, id);
77
+ }
78
+ if (changes.folder !== undefined) {
79
+ this.db
80
+ .prepare("UPDATE workspaces SET folder = ? WHERE id = ?")
81
+ .run(changes.folder, id);
82
+ }
83
+ }
84
+ /** Sessions go with it (ON DELETE CASCADE). */
85
+ deleteWorkspace(id) {
86
+ this.db.prepare("DELETE FROM workspaces WHERE id = ?").run(id);
87
+ }
88
+ /** Gives each Workspace the position of its index in `ids`, in one transaction. */
89
+ setWorkspaceOrder(ids) {
90
+ const update = this.db.prepare("UPDATE workspaces SET position = ? WHERE id = ?");
91
+ this.db.exec("BEGIN");
92
+ try {
93
+ ids.forEach((id, index) => {
94
+ update.run(index, id);
95
+ });
96
+ this.db.exec("COMMIT");
97
+ }
98
+ catch (error) {
99
+ this.db.exec("ROLLBACK");
100
+ throw error;
101
+ }
102
+ }
103
+ listSessions(workspaceId) {
104
+ return this.db
105
+ .prepare(`SELECT id, workspace_id AS workspaceId, name FROM sessions
106
+ WHERE workspace_id = ? ORDER BY created_at, rowid`)
107
+ .all(workspaceId);
108
+ }
109
+ getSession(id) {
110
+ return this.db
111
+ .prepare(`SELECT s.id, s.workspace_id AS workspaceId, s.name, w.folder
112
+ FROM sessions s JOIN workspaces w ON w.id = s.workspace_id WHERE s.id = ?`)
113
+ .get(id);
114
+ }
115
+ renameSession(id, name) {
116
+ this.db.prepare("UPDATE sessions SET name = ? WHERE id = ?").run(name, id);
117
+ }
118
+ deleteSession(id) {
119
+ this.db.prepare("DELETE FROM sessions WHERE id = ?").run(id);
120
+ }
121
+ addSession(input) {
122
+ this.db
123
+ .prepare("INSERT INTO sessions (id, workspace_id, name, created_at) VALUES (?, ?, ?, ?)")
124
+ .run(input.id, input.workspaceId, input.name, Date.now());
125
+ return input;
126
+ }
127
+ }
@@ -0,0 +1,64 @@
1
+ import { WebSocketServer } from "ws";
2
+ import { CLOSE_INTERNAL_ERROR, CLOSE_SESSION_ENDED, decodeClientMessage, parseTerminalPath, } from "../shared/terminal-protocol.js";
3
+ /**
4
+ * The terminal WebSocket, one per open Pane, speaking the protocol in
5
+ * `src/shared/terminal-protocol.ts`. A thin adapter onto `Attachments`, which owns the
6
+ * terminal's whole life.
7
+ */
8
+ export class TerminalSockets {
9
+ attachments;
10
+ wss = new WebSocketServer({ noServer: true });
11
+ constructor(attachments) {
12
+ this.attachments = attachments;
13
+ }
14
+ /**
15
+ * The Session and size a terminal upgrade asks for, or undefined when `request` is not a
16
+ * terminal upgrade.
17
+ */
18
+ static match(request) {
19
+ return parseTerminalPath(request.url ?? "/");
20
+ }
21
+ handleUpgrade(request, socket, head, { sessionId, size }) {
22
+ this.wss.handleUpgrade(request, socket, head, (ws) => this.serve(ws, sessionId, size));
23
+ }
24
+ serve(ws, sessionId, size) {
25
+ // Attached before any message can arrive: what the client types the moment its socket
26
+ // opens is held by the attachment until its tmux client is ready.
27
+ const attachment = this.attachments.attach(sessionId, size, {
28
+ show: (output) => {
29
+ if (ws.readyState === ws.OPEN)
30
+ ws.send(output);
31
+ },
32
+ end: (reason) => endSocket(ws, reason),
33
+ });
34
+ ws.on("message", (raw) => {
35
+ const message = decodeClientMessage(raw.toString());
36
+ if (message?.type === "input") {
37
+ attachment.input(message.data, { automatic: message.automatic });
38
+ }
39
+ else if (message?.type === "resize") {
40
+ // The attachment ignores anything that is not a valid size.
41
+ attachment.resize(message.cols, message.rows);
42
+ }
43
+ });
44
+ ws.on("close", () => attachment.detach());
45
+ ws.on("error", () => ws.terminate());
46
+ }
47
+ /**
48
+ * Drops every terminal socket still open, including one that has ended and is waiting for
49
+ * its client to answer the close. Server stop calls it after `Attachments.stop`, so no
50
+ * socket outlives the server.
51
+ */
52
+ closeAll() {
53
+ for (const client of this.wss.clients)
54
+ client.terminate();
55
+ }
56
+ }
57
+ function endSocket(ws, reason) {
58
+ if (reason === "server-stopping")
59
+ ws.terminate();
60
+ else if (reason === "failed")
61
+ ws.close(CLOSE_INTERNAL_ERROR, "Could not attach");
62
+ else
63
+ ws.close(CLOSE_SESSION_ENDED, "Session ended");
64
+ }