@k-electron/k-bench 0.2.0 → 0.4.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/README.md +3 -3
- package/dist/js/src/server/app.js +37 -8
- package/dist/js/src/server/claude.js +45 -8
- package/dist/js/src/server/directories.js +6 -3
- package/dist/js/src/server/reconciler.js +13 -3
- package/dist/js/src/server/server.js +10 -0
- package/dist/js/src/server/service.js +238 -25
- package/dist/js/src/server/store.js +183 -20
- package/dist/js/src/server/tmux.js +53 -20
- package/dist/js/src/shared/launch-options.js +9 -0
- package/dist/js/src/shared/session-roles.js +11 -0
- package/dist/web/assets/index-Bwg64t6Z.css +1 -0
- package/dist/web/assets/index-tfq45JVL.js +74 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
- package/dist/web/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
- package/dist/web/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
- package/dist/web/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
- package/dist/web/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
- package/dist/web/index.html +2 -2
- package/package.json +3 -1
- package/dist/web/assets/index-BENZ0uzV.js +0 -68
- package/dist/web/assets/index-BFSRMRkk.css +0 -2
package/README.md
CHANGED
|
@@ -20,11 +20,11 @@ It is not only for Claude Code. **New shell** gives you a plain shell Session, s
|
|
|
20
20
|
## What you get
|
|
21
21
|
|
|
22
22
|
- **Sessions that keep running** when you close the tab, lock your phone or lose your connection. Come back from any device and pick up where you left off.
|
|
23
|
-
- **Claude Sessions.** Pick **New Claude…** from a Workspace's **+**, choose the model, effort, advisor and Focus view (a condensed view that suits a phone), and k-bench launches Claude Code for you. Restart a Stopped Claude Session, even after a reboot, and the
|
|
23
|
+
- **Claude Sessions.** Pick **New Claude…** from a Workspace's **+**, choose the model, effort, advisor and Focus view (a condensed view that suits a phone), and k-bench launches Claude Code for you. Restart a Stopped Claude Session, even after a reboot, and the conversation you were last in resumes, even after a `/clear`.
|
|
24
24
|
- **Workspaces per project.** A Workspace points at a project folder on your Mac, and its Sessions start there.
|
|
25
|
-
- **Two Panes** side by side
|
|
25
|
+
- **Two Panes** side by side for the Workspace you're in: its Prime on the left, and its Worker, or a dev server, on the right.
|
|
26
26
|
- **Bells.** When a Session rings the terminal bell, its row in the sidebar shows a Bell until you look at it.
|
|
27
|
-
- **A phone layout** with a drawer for your Workspaces and a row of extra keys (Esc, Tab, Shift-Tab, Ctrl
|
|
27
|
+
- **A phone layout** with a drawer for your Workspaces and a row of extra keys (Esc, Tab, Shift-Tab, Ctrl, the arrows and Enter) for the keys a phone keyboard lacks.
|
|
28
28
|
- **Access only for your tailnet login.** k-bench listens on localhost only and is published with `tailscale serve`. It admits only requests that carry your own tailnet login.
|
|
29
29
|
|
|
30
30
|

|
|
@@ -30,7 +30,7 @@ function optionalString(value) {
|
|
|
30
30
|
return typeof value === "string" ? value : undefined;
|
|
31
31
|
}
|
|
32
32
|
/** The JSON HTTP API. */
|
|
33
|
-
export function createApp(service, options
|
|
33
|
+
export function createApp(service, options) {
|
|
34
34
|
const app = new Hono();
|
|
35
35
|
app.onError((error, c) => {
|
|
36
36
|
if (error instanceof HTTPException) {
|
|
@@ -38,7 +38,7 @@ export function createApp(service, options = {}) {
|
|
|
38
38
|
}
|
|
39
39
|
if (error instanceof ServiceError) {
|
|
40
40
|
const status = error.kind === "not_found" ? 404 : error.kind === "conflict" ? 409 : 422;
|
|
41
|
-
return c.json({ error: error.message }, status);
|
|
41
|
+
return c.json({ ...error.details, error: error.message }, status);
|
|
42
42
|
}
|
|
43
43
|
console.error(error);
|
|
44
44
|
return c.json({ error: "Internal error" }, 500);
|
|
@@ -56,13 +56,14 @@ export function createApp(service, options = {}) {
|
|
|
56
56
|
// caller must send the owner's login.
|
|
57
57
|
app.get("/api/health", (c) => c.json({ status: "ok" }));
|
|
58
58
|
app.get("/api/state", async (c) => c.json(await service.getState()));
|
|
59
|
-
// The folder picker.
|
|
59
|
+
// The folder picker. Without a path it lists where the picker opens; every answer names
|
|
60
|
+
// the picker root (Home), which the picker shows among its Places.
|
|
60
61
|
app.get("/api/directories", (c) => {
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
throw new ServiceError("invalid", "path is required");
|
|
62
|
+
const root = options.pickerRoot;
|
|
63
|
+
const path = c.req.query("path") || service.pickerStart(root);
|
|
64
64
|
try {
|
|
65
|
-
|
|
65
|
+
const hidden = c.req.query("hidden") === "1";
|
|
66
|
+
return c.json({ ...listDirectories(path, { hidden }), root });
|
|
66
67
|
}
|
|
67
68
|
catch (error) {
|
|
68
69
|
if (error instanceof DirectoryError) {
|
|
@@ -79,6 +80,7 @@ export function createApp(service, options = {}) {
|
|
|
79
80
|
const workspace = service.createWorkspace({
|
|
80
81
|
folder,
|
|
81
82
|
name: optionalString(body.name),
|
|
83
|
+
createMissingFolders: body.createMissingFolders === true,
|
|
82
84
|
});
|
|
83
85
|
return c.json(workspace, 201);
|
|
84
86
|
});
|
|
@@ -93,16 +95,43 @@ export function createApp(service, options = {}) {
|
|
|
93
95
|
});
|
|
94
96
|
app.patch("/api/workspaces/:id", async (c) => {
|
|
95
97
|
const body = await jsonBody(c.req.raw);
|
|
96
|
-
const workspace = service.updateWorkspace(c.req.param("id"), {
|
|
98
|
+
const workspace = await service.updateWorkspace(c.req.param("id"), {
|
|
97
99
|
name: optionalString(body.name),
|
|
98
100
|
folder: optionalString(body.folder),
|
|
101
|
+
createMissingFolders: body.createMissingFolders === true,
|
|
99
102
|
});
|
|
100
103
|
return c.json(workspace);
|
|
101
104
|
});
|
|
105
|
+
app.post("/api/workspaces/:id/open", async (c) => {
|
|
106
|
+
const body = await jsonBody(c.req.raw);
|
|
107
|
+
return c.json(await service.openWorkspace(c.req.param("id"), {
|
|
108
|
+
showWorker: body.showWorker === true,
|
|
109
|
+
}));
|
|
110
|
+
});
|
|
111
|
+
// The whole record: the tabs in order, and the one shown (null for the Worker).
|
|
112
|
+
app.put("/api/workspaces/:id/right-pane", async (c) => {
|
|
113
|
+
const { shown, tabs } = await jsonBody(c.req.raw);
|
|
114
|
+
if (!Array.isArray(tabs) || !tabs.every((id) => typeof id === "string")) {
|
|
115
|
+
throw new ServiceError("invalid", "tabs must be a list of Session ids");
|
|
116
|
+
}
|
|
117
|
+
if (shown !== null && typeof shown !== "string") {
|
|
118
|
+
throw new ServiceError("invalid", "shown must be a Session id or null");
|
|
119
|
+
}
|
|
120
|
+
service.setRightPane(c.req.param("id"), { shown, tabs });
|
|
121
|
+
return c.json({ shown, tabs });
|
|
122
|
+
});
|
|
102
123
|
app.delete("/api/workspaces/:id", async (c) => {
|
|
103
124
|
await service.deleteWorkspace(c.req.param("id"));
|
|
104
125
|
return c.body(null, 204);
|
|
105
126
|
});
|
|
127
|
+
app.put("/api/workspaces/:id/sessions/order", async (c) => {
|
|
128
|
+
const { ids } = await jsonBody(c.req.raw);
|
|
129
|
+
if (!Array.isArray(ids) || !ids.every((id) => typeof id === "string")) {
|
|
130
|
+
throw new ServiceError("invalid", "ids must be a list of Session ids");
|
|
131
|
+
}
|
|
132
|
+
service.reorderSessions(c.req.param("id"), ids);
|
|
133
|
+
return c.json({ ids });
|
|
134
|
+
});
|
|
106
135
|
app.post("/api/workspaces/:id/sessions", async (c) => {
|
|
107
136
|
const body = await jsonBody(c.req.raw);
|
|
108
137
|
// `claude` makes it a Claude Session; its Launch options are checked before anything starts.
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Launching Claude Code for a Claude Session (ADR-0005). k-bench starts it through its
|
|
3
|
-
* documented command-line flags and
|
|
4
|
-
* k-bench knows about Claude Code is in this file: the
|
|
5
|
-
* script that runs it.
|
|
3
|
+
* documented command-line flags and learns which conversation it is on through a silent
|
|
4
|
+
* `SessionStart` hook, so everything k-bench knows about Claude Code is in this file: the
|
|
5
|
+
* flags it passes, the hook, and the launcher script that runs it.
|
|
6
6
|
*/
|
|
7
7
|
import { DEFAULT_LAUNCH_OPTIONS, LAUNCH_CHOICES, } from "../shared/launch-options.js";
|
|
8
8
|
/**
|
|
@@ -36,15 +36,51 @@ export function parseLaunchOptions(value) {
|
|
|
36
36
|
return { options };
|
|
37
37
|
}
|
|
38
38
|
/**
|
|
39
|
-
*
|
|
39
|
+
* The tmux pane user option the conversation hook writes the conversation ID to, on the pane
|
|
40
|
+
* Claude Code runs in, and the tmux `wait-for` channel it signals after (see `TmuxDriver`).
|
|
41
|
+
*/
|
|
42
|
+
export const CONVERSATION_OPTION = "@kb-conversation";
|
|
43
|
+
export const CONVERSATION_CHANNEL = "kb-conversation-changed";
|
|
44
|
+
/**
|
|
45
|
+
* Claude Code runs this `SessionStart` hook whenever a conversation starts in the Session,
|
|
46
|
+
* whatever started it: the launch, `/clear`, `/resume`, `/branch`, compaction (which keeps
|
|
47
|
+
* the ID) or a `/restart`. It takes `session_id` from the JSON on stdin and records it on its
|
|
48
|
+
* own tmux pane, then signals the channel, as the Bell does.
|
|
49
|
+
*
|
|
50
|
+
* Claude Code adds a `SessionStart` hook's output to the conversation, so it prints nothing,
|
|
51
|
+
* and it exits 0 whatever happens, so a missing tool never shows in Claude Code (ADR-0005).
|
|
52
|
+
* It is one line of plain POSIX `sh` with tools every Mac has (no `jq`), because it runs
|
|
53
|
+
* under the owner's own environment. Bare `tmux` reaches k-bench's socket through `$TMUX`,
|
|
54
|
+
* which tmux sets in the pane. The ID is passed as an argument, so it cannot inject into a
|
|
55
|
+
* tmux command; k-bench ignores one that isn't UUID-shaped.
|
|
56
|
+
*/
|
|
57
|
+
const CONVERSATION_HOOK = [
|
|
58
|
+
"{",
|
|
59
|
+
`id=$(tr -d '\\n' | sed -n 's/.*"session_id"[[:space:]]*:[[:space:]]*"\\([^"]*\\)".*/\\1/p');`,
|
|
60
|
+
'[ -n "$id" ] && [ -n "$TMUX_PANE" ] &&',
|
|
61
|
+
`tmux set-option -p -t "$TMUX_PANE" ${CONVERSATION_OPTION} "$id" &&`,
|
|
62
|
+
`tmux wait-for -S ${CONVERSATION_CHANNEL};`,
|
|
63
|
+
"} >/dev/null 2>&1; exit 0",
|
|
64
|
+
].join(" ");
|
|
65
|
+
/**
|
|
66
|
+
* The `--settings` every launch passes: the conversation hook and, with Focus view on, its
|
|
67
|
+
* keys. Focus view needs both keys: it does nothing without the fullscreen renderer, and
|
|
40
68
|
* fullscreen is not the default on every machine. `--settings` applies to that launch only
|
|
41
|
-
* and
|
|
69
|
+
* and adds to the owner's own settings and hooks, leaving their files unchanged.
|
|
42
70
|
*/
|
|
43
|
-
|
|
71
|
+
function launchSettings(focusView) {
|
|
72
|
+
return JSON.stringify({
|
|
73
|
+
hooks: {
|
|
74
|
+
SessionStart: [{ hooks: [{ type: "command", command: CONVERSATION_HOOK }] }],
|
|
75
|
+
},
|
|
76
|
+
...(focusView ? { viewMode: "focus", tui: "fullscreen" } : {}),
|
|
77
|
+
});
|
|
78
|
+
}
|
|
44
79
|
/**
|
|
45
80
|
* The flags that follow the one naming the conversation. This is where Launch options become
|
|
46
81
|
* flags: a Default option adds nothing. Advisor Off is not a flag (there is none): the
|
|
47
|
-
* launcher sets `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1` for it.
|
|
82
|
+
* launcher sets `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1` for it. `--settings` is always passed,
|
|
83
|
+
* for the conversation hook.
|
|
48
84
|
*/
|
|
49
85
|
function launchOptionArguments(options) {
|
|
50
86
|
const { model, effort, advisor, focusView } = options;
|
|
@@ -52,7 +88,8 @@ function launchOptionArguments(options) {
|
|
|
52
88
|
...(model === "default" ? [] : ["--model", model]),
|
|
53
89
|
...(effort === "default" ? [] : ["--effort", effort]),
|
|
54
90
|
...(advisor === "default" || advisor === "off" ? [] : ["--advisor", advisor]),
|
|
55
|
-
|
|
91
|
+
"--settings",
|
|
92
|
+
launchSettings(focusView),
|
|
56
93
|
];
|
|
57
94
|
}
|
|
58
95
|
/** Printed, and waited on, when Claude Code exits with an error. */
|
|
@@ -11,8 +11,11 @@ function isDirectory(path) {
|
|
|
11
11
|
return false;
|
|
12
12
|
}
|
|
13
13
|
}
|
|
14
|
-
/**
|
|
15
|
-
|
|
14
|
+
/**
|
|
15
|
+
* The subfolders of `path`, for the folder picker. Symlinks to folders count as folders.
|
|
16
|
+
* Hidden folders are left out unless `hidden` is set (for the path field's suggestions).
|
|
17
|
+
*/
|
|
18
|
+
export function listDirectories(path, { hidden = false } = {}) {
|
|
16
19
|
if (!isAbsolute(path))
|
|
17
20
|
throw new DirectoryError(`Path must be absolute: ${path}`);
|
|
18
21
|
const folder = resolve(path);
|
|
@@ -26,7 +29,7 @@ export function listDirectories(path) {
|
|
|
26
29
|
throw new DirectoryError(`Cannot read folder: ${folder}`);
|
|
27
30
|
}
|
|
28
31
|
const directories = names
|
|
29
|
-
.filter((name) => !name.startsWith(".") && isDirectory(join(folder, name)))
|
|
32
|
+
.filter((name) => (hidden || !name.startsWith(".")) && isDirectory(join(folder, name)))
|
|
30
33
|
.sort((a, b) => a.localeCompare(b, "en", { sensitivity: "base" }))
|
|
31
34
|
.map((name) => ({ name, path: join(folder, name) }));
|
|
32
35
|
const parent = dirname(folder);
|
|
@@ -1,7 +1,11 @@
|
|
|
1
|
+
/** A conversation ID as Claude Code makes them. Anything else a hook reports is ignored. */
|
|
2
|
+
const CONVERSATION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1
3
|
/**
|
|
2
4
|
* Compares the store with what is alive in tmux (ADR-0002). A Session in the store with no
|
|
3
5
|
* live tmux session is Stopped, which callers learn from the returned live ids. A live tmux
|
|
4
|
-
* session on this instance's socket with no store row is an orphan and is killed.
|
|
6
|
+
* session on this instance's socket with no store row is an orphan and is killed. A live
|
|
7
|
+
* Claude Session whose Claude Code reported moving to another conversation has the new one
|
|
8
|
+
* stored, so a restart resumes it (ADR-0005).
|
|
5
9
|
*/
|
|
6
10
|
export class Reconciler {
|
|
7
11
|
store;
|
|
@@ -26,10 +30,16 @@ export class Reconciler {
|
|
|
26
30
|
this.starting.delete(id);
|
|
27
31
|
}
|
|
28
32
|
}
|
|
29
|
-
/**
|
|
33
|
+
/**
|
|
34
|
+
* Kills orphans, stores the conversation each live Claude Session is on, and returns the
|
|
35
|
+
* Sessions that are alive, by id.
|
|
36
|
+
*/
|
|
30
37
|
async reconcile() {
|
|
31
38
|
const live = new Map((await this.tmux.listSessions()).map((s) => [s.id, s]));
|
|
32
|
-
for (const id of [...live
|
|
39
|
+
for (const [id, session] of [...live]) {
|
|
40
|
+
if (CONVERSATION_ID.test(session.conversation)) {
|
|
41
|
+
this.store.setConversationId(id, session.conversation);
|
|
42
|
+
}
|
|
33
43
|
// Order matters: a Session no longer starting already has its store row.
|
|
34
44
|
if (this.starting.has(id) || this.store.getSession(id))
|
|
35
45
|
continue;
|
|
@@ -24,6 +24,14 @@ export async function startServer(config, options = {}) {
|
|
|
24
24
|
});
|
|
25
25
|
const events = new EventSockets(feed);
|
|
26
26
|
const bells = tmux.watchBells(() => feed.notify());
|
|
27
|
+
// A Claude Session's new conversation is stored at once, whether or not anyone is viewing
|
|
28
|
+
// it. One reconcile at a time; stopping waits for the last before the database closes.
|
|
29
|
+
let following = Promise.resolve();
|
|
30
|
+
const conversations = tmux.watchConversations(() => {
|
|
31
|
+
following = following
|
|
32
|
+
.then(() => service.reconcile())
|
|
33
|
+
.catch((error) => console.error("could not follow a Claude conversation", error));
|
|
34
|
+
});
|
|
27
35
|
// The guard sits in front of everything the server answers, so no route or static file
|
|
28
36
|
// (now or added later) can be reached without the allowed login.
|
|
29
37
|
const guard = new AccessGuard(config.allowedLogin);
|
|
@@ -67,6 +75,8 @@ export async function startServer(config, options = {}) {
|
|
|
67
75
|
const stop = () => {
|
|
68
76
|
stopping ??= (async () => {
|
|
69
77
|
await bells.stop();
|
|
78
|
+
await conversations.stop();
|
|
79
|
+
await following;
|
|
70
80
|
events.closeAll();
|
|
71
81
|
// From here on no tmux client this server started is running or starting.
|
|
72
82
|
await attachments.stop();
|
|
@@ -1,15 +1,34 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { statSync } from "node:fs";
|
|
3
|
-
import { basename, resolve } from "node:path";
|
|
4
|
-
import { DEFAULT_LAUNCH_OPTIONS } from "../shared/launch-options.js";
|
|
2
|
+
import { mkdirSync, statSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, resolve } from "node:path";
|
|
4
|
+
import { DEFAULT_LAUNCH_OPTIONS, ROLE_LAUNCH_OPTIONS, } from "../shared/launch-options.js";
|
|
5
|
+
import { sessionsByRole } from "../shared/session-roles.js";
|
|
5
6
|
import { availableName } from "./naming.js";
|
|
6
7
|
import { Reconciler } from "./reconciler.js";
|
|
7
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* A failure the HTTP layer maps to a status code. `details` go into the response body
|
|
10
|
+
* next to the message, for a client that acts on the refusal.
|
|
11
|
+
*/
|
|
8
12
|
export class ServiceError extends Error {
|
|
9
13
|
kind;
|
|
10
|
-
|
|
14
|
+
details;
|
|
15
|
+
constructor(kind, message, details = {}) {
|
|
11
16
|
super(message);
|
|
12
17
|
this.kind = kind;
|
|
18
|
+
this.details = details;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** A Workspace's Prime and Worker, in the order they are listed. */
|
|
22
|
+
const ROLES = ["prime", "worker"];
|
|
23
|
+
/** The fixed names of the Prime and Worker, which no Other Session may take. */
|
|
24
|
+
const ROLE_NAMES = { prime: "Prime", worker: "Worker" };
|
|
25
|
+
function isRoleName(name) {
|
|
26
|
+
return ROLES.some((role) => ROLE_NAMES[role] === name);
|
|
27
|
+
}
|
|
28
|
+
/** The Prime and Worker last as long as their Workspace, under their fixed names. */
|
|
29
|
+
function assertNoRole(session, change) {
|
|
30
|
+
if (session.role) {
|
|
31
|
+
throw new ServiceError("conflict", `The ${ROLE_NAMES[session.role]} can't be ${change}`);
|
|
13
32
|
}
|
|
14
33
|
}
|
|
15
34
|
function isDirectory(path) {
|
|
@@ -20,6 +39,40 @@ function isDirectory(path) {
|
|
|
20
39
|
return false;
|
|
21
40
|
}
|
|
22
41
|
}
|
|
42
|
+
function assertDirectory(folder) {
|
|
43
|
+
if (!isDirectory(folder)) {
|
|
44
|
+
throw new ServiceError("invalid", `Folder does not exist: ${folder}`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Why a folder couldn't be made, in the owner's words. */
|
|
48
|
+
function mkdirFailure(error) {
|
|
49
|
+
const code = error.code;
|
|
50
|
+
if (code === "EEXIST" || code === "ENOTDIR")
|
|
51
|
+
return "a file is in the way";
|
|
52
|
+
if (code === "EACCES" || code === "EPERM")
|
|
53
|
+
return "permission denied";
|
|
54
|
+
if (code === "ENAMETOOLONG")
|
|
55
|
+
return "the name is too long";
|
|
56
|
+
return code ?? String(error);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Makes `folder` and any missing folders above it, from the top down. A failure names the
|
|
60
|
+
* folder that couldn't be made; the folders made before it stay.
|
|
61
|
+
*/
|
|
62
|
+
function makeFolders(folder) {
|
|
63
|
+
const missing = [];
|
|
64
|
+
for (let path = folder; !isDirectory(path) && path !== dirname(path); path = dirname(path)) {
|
|
65
|
+
missing.unshift(path);
|
|
66
|
+
}
|
|
67
|
+
for (const path of missing) {
|
|
68
|
+
try {
|
|
69
|
+
mkdirSync(path);
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
throw new ServiceError("invalid", `Couldn't make the folder ${path}: ${mkdirFailure(error)}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
23
76
|
/** The domain operations. The store holds what the owner chose; tmux says what is alive. */
|
|
24
77
|
export class Service {
|
|
25
78
|
store;
|
|
@@ -32,24 +85,62 @@ export class Service {
|
|
|
32
85
|
this.tmux = tmux;
|
|
33
86
|
this.reconciler = new Reconciler(store, tmux);
|
|
34
87
|
}
|
|
35
|
-
/**
|
|
88
|
+
/**
|
|
89
|
+
* Kills tmux sessions that have no store record and stores the conversation each Claude
|
|
90
|
+
* Session is on. Runs at startup, on every state read and whenever Claude Code reports a
|
|
91
|
+
* conversation.
|
|
92
|
+
*/
|
|
36
93
|
async reconcile() {
|
|
37
94
|
await this.reconciler.reconcile();
|
|
38
95
|
}
|
|
96
|
+
/**
|
|
97
|
+
* With `createMissingFolders`, a folder that doesn't exist yet is made (with any missing
|
|
98
|
+
* folders above it) once every other check has passed; without it, it is refused.
|
|
99
|
+
*/
|
|
39
100
|
createWorkspace(input) {
|
|
40
101
|
const folder = resolve(input.folder);
|
|
41
|
-
if (!
|
|
42
|
-
|
|
43
|
-
|
|
102
|
+
if (!input.createMissingFolders)
|
|
103
|
+
assertDirectory(folder);
|
|
104
|
+
this.assertFolderFree(folder);
|
|
44
105
|
const explicit = input.name?.trim();
|
|
45
106
|
if (explicit)
|
|
46
107
|
this.assertWorkspaceNameFree(explicit);
|
|
108
|
+
if (input.createMissingFolders)
|
|
109
|
+
makeFolders(folder);
|
|
47
110
|
const name = explicit || availableName(basename(folder), this.workspaceNames());
|
|
48
|
-
|
|
111
|
+
// The Prime and Worker are recorded with the Workspace and started only when asked to.
|
|
112
|
+
const { id } = this.store.transaction(() => {
|
|
113
|
+
const workspace = this.store.addWorkspace({ name, folder });
|
|
114
|
+
for (const role of ROLES) {
|
|
115
|
+
this.store.addSession({
|
|
116
|
+
id: randomUUID(),
|
|
117
|
+
workspaceId: workspace.id,
|
|
118
|
+
name: ROLE_NAMES[role],
|
|
119
|
+
role,
|
|
120
|
+
conversationId: randomUUID(),
|
|
121
|
+
launchOptions: ROLE_LAUNCH_OPTIONS[role],
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
return workspace;
|
|
125
|
+
});
|
|
49
126
|
return { id, name, folder };
|
|
50
127
|
}
|
|
51
|
-
/**
|
|
52
|
-
|
|
128
|
+
/**
|
|
129
|
+
* Where the folder picker opens: the parent of the most recently created Workspace's
|
|
130
|
+
* folder, or `root` (Home) when there is none or that parent is gone.
|
|
131
|
+
*/
|
|
132
|
+
pickerStart(root) {
|
|
133
|
+
const newest = this.store.newestWorkspace();
|
|
134
|
+
const parent = newest && dirname(newest.folder);
|
|
135
|
+
return parent && isDirectory(parent) ? parent : root;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Renames and/or re-folders a Workspace; both changes are checked before either is made.
|
|
139
|
+
* `createMissingFolders` works as in `createWorkspace`. Moving the Open Workspace onto a
|
|
140
|
+
* folder starts its Stopped Prime and Worker there, so fixing a Missing one needs no
|
|
141
|
+
* second open.
|
|
142
|
+
*/
|
|
143
|
+
async updateWorkspace(id, changes) {
|
|
53
144
|
const workspace = this.store.getWorkspace(id);
|
|
54
145
|
if (!workspace)
|
|
55
146
|
throw new ServiceError("not_found", "Unknown Workspace");
|
|
@@ -63,14 +154,85 @@ export class Service {
|
|
|
63
154
|
}
|
|
64
155
|
if (changes.folder !== undefined) {
|
|
65
156
|
const folder = resolve(changes.folder);
|
|
66
|
-
if (!
|
|
67
|
-
|
|
68
|
-
|
|
157
|
+
if (!changes.createMissingFolders)
|
|
158
|
+
assertDirectory(folder);
|
|
159
|
+
this.assertFolderFree(folder, id);
|
|
69
160
|
update.folder = folder;
|
|
70
161
|
}
|
|
162
|
+
if (update.folder !== undefined && changes.createMissingFolders) {
|
|
163
|
+
makeFolders(update.folder);
|
|
164
|
+
}
|
|
71
165
|
this.store.updateWorkspace(id, update);
|
|
166
|
+
if (update.folder !== undefined && this.openWorkspaceId() === id) {
|
|
167
|
+
await this.startRoles(id);
|
|
168
|
+
}
|
|
72
169
|
return { ...workspace, ...update };
|
|
73
170
|
}
|
|
171
|
+
/**
|
|
172
|
+
* Makes the Workspace the Open Workspace and, unless it is Missing, starts its Stopped
|
|
173
|
+
* Prime and Worker, resuming their conversations. Opening it again changes nothing that
|
|
174
|
+
* is running. With `showWorker` (the owner chose it by name), its right Pane shows the
|
|
175
|
+
* Worker again, keeping its tabs.
|
|
176
|
+
*/
|
|
177
|
+
async openWorkspace(id, options = {}) {
|
|
178
|
+
const workspace = this.store.getWorkspace(id);
|
|
179
|
+
if (!workspace)
|
|
180
|
+
throw new ServiceError("not_found", "Unknown Workspace");
|
|
181
|
+
this.store.transaction(() => {
|
|
182
|
+
this.store.setOpenWorkspaceId(id);
|
|
183
|
+
if (options.showWorker) {
|
|
184
|
+
this.store.setRightPane(id, { ...this.rightPane(id), shown: null });
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
if (isDirectory(workspace.folder))
|
|
188
|
+
await this.startRoles(id);
|
|
189
|
+
return { id };
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* The Open Workspace: the one last opened or, when none is set, the first by position.
|
|
193
|
+
* Null when there are no Workspaces.
|
|
194
|
+
*/
|
|
195
|
+
openWorkspaceId() {
|
|
196
|
+
return this.store.getOpenWorkspaceId() ?? this.store.listWorkspaces()[0]?.id ?? null;
|
|
197
|
+
}
|
|
198
|
+
/** Starts the Workspace's Prime and Worker, those that are Stopped, together. */
|
|
199
|
+
async startRoles(workspaceId) {
|
|
200
|
+
const { primeAndWorker } = sessionsByRole(this.store.listSessions(workspaceId));
|
|
201
|
+
await Promise.all(primeAndWorker.map((session) => this.restartSession(session.id)));
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Sets what the Workspace's right Pane holds. Every tab must be one of its Other Sessions,
|
|
205
|
+
* once, and what's shown must be one of the tabs, or null for the Worker.
|
|
206
|
+
*/
|
|
207
|
+
setRightPane(workspaceId, rightPane) {
|
|
208
|
+
if (!this.store.getWorkspace(workspaceId)) {
|
|
209
|
+
throw new ServiceError("not_found", "Unknown Workspace");
|
|
210
|
+
}
|
|
211
|
+
const others = this.otherSessionIds(workspaceId);
|
|
212
|
+
const { shown, tabs } = rightPane;
|
|
213
|
+
if (!tabs.every((id) => others.has(id)) || new Set(tabs).size !== tabs.length) {
|
|
214
|
+
throw new ServiceError("invalid", "tabs must list Other Sessions of the Workspace, each at most once");
|
|
215
|
+
}
|
|
216
|
+
if (shown !== null && !tabs.includes(shown)) {
|
|
217
|
+
throw new ServiceError("invalid", "shown must be null or one of the tabs");
|
|
218
|
+
}
|
|
219
|
+
this.store.setRightPane(workspaceId, { shown, tabs });
|
|
220
|
+
}
|
|
221
|
+
otherSessionIds(workspaceId) {
|
|
222
|
+
const { others } = sessionsByRole(this.store.listSessions(workspaceId));
|
|
223
|
+
return new Set(others.map((session) => session.id));
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* What the Workspace's right Pane holds, leaving out any Session that is no longer one of
|
|
227
|
+
* its Other Sessions.
|
|
228
|
+
*/
|
|
229
|
+
rightPane(workspaceId) {
|
|
230
|
+
const others = this.otherSessionIds(workspaceId);
|
|
231
|
+
const stored = this.store.getRightPane(workspaceId);
|
|
232
|
+
const tabs = stored.tabs.filter((id) => others.has(id));
|
|
233
|
+
const shown = stored.shown !== null && tabs.includes(stored.shown) ? stored.shown : null;
|
|
234
|
+
return { shown, tabs };
|
|
235
|
+
}
|
|
74
236
|
/** `ids` must be every Workspace exactly once, in the order the owner wants. */
|
|
75
237
|
reorderWorkspaces(ids) {
|
|
76
238
|
const known = this.store.listWorkspaces().map((w) => w.id);
|
|
@@ -79,7 +241,24 @@ export class Service {
|
|
|
79
241
|
}
|
|
80
242
|
this.store.setWorkspaceOrder(ids);
|
|
81
243
|
}
|
|
82
|
-
/**
|
|
244
|
+
/**
|
|
245
|
+
* `ids` must be every Other Session of the Workspace exactly once, in the order the owner
|
|
246
|
+
* wants. The Prime and Worker always come first, so they are never in it.
|
|
247
|
+
*/
|
|
248
|
+
reorderSessions(workspaceId, ids) {
|
|
249
|
+
if (!this.store.getWorkspace(workspaceId)) {
|
|
250
|
+
throw new ServiceError("not_found", "Unknown Workspace");
|
|
251
|
+
}
|
|
252
|
+
const known = [...this.otherSessionIds(workspaceId)];
|
|
253
|
+
if (ids.length !== known.length || !known.every((id) => ids.includes(id))) {
|
|
254
|
+
throw new ServiceError("invalid", "ids must list every Other Session of the Workspace exactly once");
|
|
255
|
+
}
|
|
256
|
+
this.store.setSessionOrder(workspaceId, ids);
|
|
257
|
+
}
|
|
258
|
+
/**
|
|
259
|
+
* Ends the Workspace's shells first, then forgets it. The folder on disk is never touched.
|
|
260
|
+
* Deleting the Open Workspace opens the first Workspace by position, or none.
|
|
261
|
+
*/
|
|
83
262
|
async deleteWorkspace(id) {
|
|
84
263
|
if (!this.store.getWorkspace(id))
|
|
85
264
|
throw new ServiceError("not_found", "Unknown Workspace");
|
|
@@ -90,7 +269,14 @@ export class Service {
|
|
|
90
269
|
const failed = kills.find((kill) => kill.status === "rejected");
|
|
91
270
|
if (failed)
|
|
92
271
|
throw failed.reason;
|
|
93
|
-
this.
|
|
272
|
+
const wasOpen = this.openWorkspaceId() === id;
|
|
273
|
+
this.store.transaction(() => {
|
|
274
|
+
this.store.deleteWorkspace(id);
|
|
275
|
+
// The first Workspace by position becomes open, and stays so through a reorder. It is
|
|
276
|
+
// not started: only opening it does that.
|
|
277
|
+
if (wasOpen)
|
|
278
|
+
this.store.setOpenWorkspaceId(this.store.listWorkspaces()[0]?.id ?? null);
|
|
279
|
+
});
|
|
94
280
|
}
|
|
95
281
|
workspaceNames(exceptId) {
|
|
96
282
|
return new Set(this.store
|
|
@@ -104,6 +290,19 @@ export class Service {
|
|
|
104
290
|
throw new ServiceError("conflict", `A Workspace named "${name}" already exists`);
|
|
105
291
|
}
|
|
106
292
|
}
|
|
293
|
+
/**
|
|
294
|
+
* A folder has at most one Workspace, so a project never gets two sets of Claudes. The
|
|
295
|
+
* refusal names the Workspace that has it, so a client can take the owner there.
|
|
296
|
+
* `folder` is already resolved. Changing a folder passes the Workspace being moved.
|
|
297
|
+
*/
|
|
298
|
+
assertFolderFree(folder, exceptId) {
|
|
299
|
+
const owner = this.store
|
|
300
|
+
.listWorkspaces()
|
|
301
|
+
.find((w) => w.id !== exceptId && resolve(w.folder) === folder);
|
|
302
|
+
if (owner) {
|
|
303
|
+
throw new ServiceError("conflict", `A Workspace for this folder already exists: "${owner.name}"`, { workspace: { id: owner.id, name: owner.name } });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
107
306
|
/**
|
|
108
307
|
* One at a time: choosing the name and storing the Session are separated by starting
|
|
109
308
|
* the shell, so overlapping creations would otherwise pick the same default name.
|
|
@@ -130,7 +329,7 @@ export class Service {
|
|
|
130
329
|
n++;
|
|
131
330
|
name = `session ${n}`;
|
|
132
331
|
}
|
|
133
|
-
else if (taken.has(name)) {
|
|
332
|
+
else if (taken.has(name) || isRoleName(name)) {
|
|
134
333
|
throw new ServiceError("conflict", `A Session named "${name}" already exists`);
|
|
135
334
|
}
|
|
136
335
|
const id = randomUUID();
|
|
@@ -169,29 +368,38 @@ export class Service {
|
|
|
169
368
|
const session = this.store.getSession(sessionId);
|
|
170
369
|
if (!session)
|
|
171
370
|
throw new ServiceError("not_found", "Unknown Session");
|
|
371
|
+
assertNoRole(session, "renamed");
|
|
172
372
|
const name = requestedName.trim();
|
|
173
373
|
if (!name)
|
|
174
374
|
throw new ServiceError("invalid", "name is required");
|
|
175
375
|
const clash = this.store
|
|
176
376
|
.listSessions(session.workspaceId)
|
|
177
377
|
.some((other) => other.id !== sessionId && other.name === name);
|
|
178
|
-
if (clash) {
|
|
378
|
+
if (clash || isRoleName(name)) {
|
|
179
379
|
throw new ServiceError("conflict", `A Session named "${name}" already exists`);
|
|
180
380
|
}
|
|
181
381
|
this.store.renameSession(sessionId, name);
|
|
182
382
|
return { id: sessionId, name };
|
|
183
383
|
}
|
|
184
|
-
/**
|
|
384
|
+
/**
|
|
385
|
+
* Ends the Session's shell and everything in it, then forgets the Session, and its tab in
|
|
386
|
+
* the right Pane, which shows the Worker if that tab was shown.
|
|
387
|
+
*/
|
|
185
388
|
async deleteSession(sessionId) {
|
|
186
|
-
|
|
389
|
+
const session = this.store.getSession(sessionId);
|
|
390
|
+
if (!session)
|
|
187
391
|
throw new ServiceError("not_found", "Unknown Session");
|
|
188
|
-
|
|
392
|
+
assertNoRole(session, "deleted");
|
|
189
393
|
await this.tmux.killSession(sessionId);
|
|
190
|
-
this.store.
|
|
394
|
+
this.store.transaction(() => {
|
|
395
|
+
this.store.deleteSession(sessionId);
|
|
396
|
+
this.store.setRightPane(session.workspaceId, this.rightPane(session.workspaceId));
|
|
397
|
+
});
|
|
191
398
|
}
|
|
192
399
|
async getState() {
|
|
193
400
|
const live = await this.reconciler.reconcile();
|
|
194
401
|
return {
|
|
402
|
+
openWorkspaceId: this.openWorkspaceId(),
|
|
195
403
|
workspaces: this.store.listWorkspaces().map((workspace) => ({
|
|
196
404
|
...workspace,
|
|
197
405
|
missing: !isDirectory(workspace.folder),
|
|
@@ -199,9 +407,11 @@ export class Service {
|
|
|
199
407
|
id: session.id,
|
|
200
408
|
name: session.name,
|
|
201
409
|
kind: session.kind,
|
|
410
|
+
role: session.role,
|
|
202
411
|
status: live.has(session.id) ? "running" : "stopped",
|
|
203
412
|
bell: live.get(session.id)?.bell ?? false,
|
|
204
413
|
})),
|
|
414
|
+
rightPane: this.rightPane(workspace.id),
|
|
205
415
|
})),
|
|
206
416
|
};
|
|
207
417
|
}
|
|
@@ -234,8 +444,11 @@ export class Service {
|
|
|
234
444
|
: {
|
|
235
445
|
conversationId: session.conversationId,
|
|
236
446
|
mode: "resume",
|
|
237
|
-
// Every Launch option is passed again each time (ADR-0005).
|
|
238
|
-
|
|
447
|
+
// Every Launch option is passed again each time (ADR-0005). A Prime's or
|
|
448
|
+
// Worker's are k-bench's fixed ones, whatever was stored with it.
|
|
449
|
+
options: session.role
|
|
450
|
+
? ROLE_LAUNCH_OPTIONS[session.role]
|
|
451
|
+
: (session.launchOptions ?? DEFAULT_LAUNCH_OPTIONS),
|
|
239
452
|
}));
|
|
240
453
|
}
|
|
241
454
|
/** Whether the terminal WebSocket has a shell to attach to: a known Session that is running. */
|