@k-electron/k-bench 0.1.3 → 0.3.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.
Files changed (38) hide show
  1. package/README.md +8 -7
  2. package/dist/js/scripts/install.js +2 -7
  3. package/dist/js/scripts/tailscale-serve.js +7 -0
  4. package/dist/js/src/server/app.js +13 -2
  5. package/dist/js/src/server/claude.js +145 -0
  6. package/dist/js/src/server/config.js +1 -0
  7. package/dist/js/src/server/events.js +1 -1
  8. package/dist/js/src/server/server.js +1 -1
  9. package/dist/js/src/server/service.js +38 -7
  10. package/dist/js/src/server/state-feed.js +2 -1
  11. package/dist/js/src/server/store.js +62 -8
  12. package/dist/js/src/server/tmux.js +36 -7
  13. package/dist/js/src/shared/launch-options.js +14 -0
  14. package/dist/js/src/shared/state-protocol.js +41 -0
  15. package/dist/web/assets/index-BStYcuMO.css +1 -0
  16. package/dist/web/assets/index-QWsANvSc.js +74 -0
  17. package/dist/web/assets/jetbrains-mono-cyrillic-400-normal-BEIGL1Tu.woff2 +0 -0
  18. package/dist/web/assets/jetbrains-mono-cyrillic-400-normal-ugxPyKxw.woff +0 -0
  19. package/dist/web/assets/jetbrains-mono-cyrillic-700-normal-BWTpRfYl.woff2 +0 -0
  20. package/dist/web/assets/jetbrains-mono-cyrillic-700-normal-CEoEElIJ.woff +0 -0
  21. package/dist/web/assets/jetbrains-mono-greek-400-normal-B9oWc5Lo.woff +0 -0
  22. package/dist/web/assets/jetbrains-mono-greek-400-normal-C190GLew.woff2 +0 -0
  23. package/dist/web/assets/jetbrains-mono-greek-700-normal-C6CZE3T8.woff2 +0 -0
  24. package/dist/web/assets/jetbrains-mono-greek-700-normal-DEigVDxa.woff +0 -0
  25. package/dist/web/assets/jetbrains-mono-latin-400-normal-6-qcROiO.woff +0 -0
  26. package/dist/web/assets/jetbrains-mono-latin-400-normal-V6pRDFza.woff2 +0 -0
  27. package/dist/web/assets/jetbrains-mono-latin-700-normal-BYuf6tUa.woff2 +0 -0
  28. package/dist/web/assets/jetbrains-mono-latin-700-normal-D3wTyLJW.woff +0 -0
  29. package/dist/web/assets/jetbrains-mono-latin-ext-400-normal-Bc8Ftmh3.woff2 +0 -0
  30. package/dist/web/assets/jetbrains-mono-latin-ext-400-normal-fXTG6kC5.woff +0 -0
  31. package/dist/web/assets/jetbrains-mono-latin-ext-700-normal-CZipNAKV.woff2 +0 -0
  32. package/dist/web/assets/jetbrains-mono-latin-ext-700-normal-CxPITLHs.woff +0 -0
  33. package/dist/web/assets/jetbrains-mono-vietnamese-400-normal-CqNFfHCs.woff +0 -0
  34. package/dist/web/assets/jetbrains-mono-vietnamese-700-normal-BDLVIk2r.woff +0 -0
  35. package/dist/web/index.html +2 -2
  36. package/package.json +8 -6
  37. package/dist/web/assets/index-BS0mVPHI.js +0 -68
  38. package/dist/web/assets/index-BrnEjylp.css +0 -2
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # k-bench
2
2
 
3
- Persistent terminal Sessions on your Mac, organised into Workspaces, reachable from any browser on your tailnet.
3
+ Persistent terminal Sessions on your Mac, organised into Workspaces, reachable from any browser on your tailnet. It launches Claude Code, and resumes it when you restart.
4
4
 
5
5
  ![Claude Code running in a k-bench Session, with the Workspaces and Sessions in the sidebar](docs/images/hero.png)
6
6
 
@@ -13,17 +13,18 @@ You can reach Claude Code on your Mac from another device in a few ways, and eac
13
13
  - **Claude Code's built-in remote mode.** [Remote Control](https://code.claude.com/docs/en/remote-control) shows a local Claude Code conversation in the Claude app or at claude.ai/code. It needs a claude.ai subscription (API keys are not supported), and some commands that only run in the terminal interface, such as `/plugin` and `/resume`, work only from the local terminal. You use Claude Code through a different interface from the one on your Mac.
14
14
  - **Tools that wrap Claude Code in their own UI.** Tools in this category give you a purpose-built interface in place of the terminal. That can be easier to use on a phone, but the interface only shows what the tool chose to build: parts of Claude Code, such as the full TUI, your slash commands and hooks, can be missing or behave differently.
15
15
 
16
- k-bench takes a third route. It gives you real Claude Code in a real terminal: persistent, and reachable from any browser on your tailnet. What runs in a Session is your own login shell with your own PATH and config, so Claude Code, its slash commands, its hooks and everything you have set up behave as they do in your local terminal.
16
+ k-bench takes a third route. It gives you real Claude Code in a real terminal: persistent, and reachable from any browser on your tailnet. A Session runs your own login shell, or Claude Code itself, with your own PATH and config, so Claude Code, its slash commands, its hooks and everything you have set up behave as they do in your local terminal.
17
17
 
18
- It is not only for Claude Code. A Session is a shell, so it works for any terminal workload: a dev server, a test watcher, a deploy, an editor.
18
+ It is not only for Claude Code. **New shell** gives you a plain shell Session, so it works for any terminal workload: a dev server, a test watcher, a deploy, an editor.
19
19
 
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 same conversation resumes.
23
24
  - **Workspaces per project.** A Workspace points at a project folder on your Mac, and its Sessions start there.
24
25
  - **Two Panes** side by side, for example Claude Code next to a dev server.
25
- - **Bells.** When a Session's shell rings the terminal bell, its row in the sidebar shows a Bell until you look at it.
26
- - **A phone layout** with a drawer for your Workspaces and a row of extra keys (Esc, Tab, Shift-Tab, Ctrl and the arrows) for the keys a phone keyboard lacks.
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, the arrows and Enter) for the keys a phone keyboard lacks.
27
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.
28
29
 
29
30
  ![Two Panes side by side on a desktop: a shell and a dev server](docs/images/desktop.png)
@@ -52,8 +53,8 @@ Something not working? Run `k-bench status`: it checks each part and says how to
52
53
 
53
54
  - [The guide](docs/guide/README.md), with
54
55
  - [Setup](docs/guide/setup.md): Tailscale, installing, updating, uninstalling.
55
- - [Using k-bench](docs/guide/using-k-bench.md): Workspaces, Sessions, Panes, Bells, scrolling and copying, the phone layout.
56
- - [Using k-bench with Claude Code](docs/guide/claude-code.md): making Claude Code ring the Bell, and working with several conversations.
56
+ - [Using k-bench](docs/guide/using-k-bench.md): Workspaces, Sessions, Claude Sessions, Panes, Bells, scrolling and copying, the phone layout.
57
+ - [Using k-bench with Claude Code](docs/guide/claude-code.md): Claude Sessions and the New Claude dialog, Focus view, resuming on restart, making Claude Code ring the Bell, and working with several conversations.
57
58
  - [Troubleshooting](docs/guide/troubleshooting.md): start from `k-bench status`.
58
59
  - [CHANGELOG](CHANGELOG.md): what changed in each version.
59
60
 
@@ -13,7 +13,7 @@ import { parseArgs } from "node:util";
13
13
  import { resolveConfig } from "../src/server/config.js";
14
14
  import { appDirIn, BUILD_INFO_FILE, LAUNCH_AGENT_LABEL, launchAgentPlistPath, launchdDomain, logPath, pathDirs as pathDirsOf, reporter, succeeds, } from "./command-lib.js";
15
15
  import { appManifest, buildLaunchAgentPlist, findExecutable, findPackageRoot, nodePtyProblems, nodeVersionProblem, parseTailscaleStatus, resolveTailscaleCli, stageApp, swapInStagedApp, } from "./install-lib.js";
16
- import { DEFAULT_HTTPS_PORT, portUse, readServeConfig, serveOffArgs, serveUrl, } from "./tailscale-serve.js";
16
+ import { DEFAULT_HTTPS_PORT, portUse, readServeConfig, serveOffArgs, servePublishArgs, serveUrl, } from "./tailscale-serve.js";
17
17
  export async function install(argv) {
18
18
  const { values: flags } = parseArgs({
19
19
  args: argv,
@@ -217,12 +217,7 @@ export async function install(argv) {
217
217
  execFileSync(tailscale, offArgs, { stdio: "inherit" });
218
218
  });
219
219
  }
220
- const serveArgs = [
221
- "serve",
222
- "--bg",
223
- `--https=${httpsPort}`,
224
- `http://127.0.0.1:${config.port}`,
225
- ];
220
+ const serveArgs = servePublishArgs(httpsPort, config.port);
226
221
  await step(`publish on the tailnet: ${tailscale} ${serveArgs.join(" ")}`, () => {
227
222
  execFileSync(tailscale, serveArgs, { stdio: "inherit" });
228
223
  });
@@ -66,6 +66,13 @@ export function parseServeConfig(json) {
66
66
  export function kBenchLocalUrl(localPort) {
67
67
  return `http://127.0.0.1:${localPort}`;
68
68
  }
69
+ /**
70
+ * The arguments that publish k-bench's server on `httpsPort`. Built from `kBenchLocalUrl`,
71
+ * so the entry they make is one that `findOwnEntries` recognises and uninstall can remove.
72
+ */
73
+ export function servePublishArgs(httpsPort, localPort) {
74
+ return ["serve", "--bg", `--https=${httpsPort}`, kBenchLocalUrl(localPort)];
75
+ }
69
76
  function isKBenchProxy(proxy, localPort) {
70
77
  if (proxy === undefined)
71
78
  return false;
@@ -1,5 +1,7 @@
1
1
  import { Hono } from "hono";
2
2
  import { HTTPException } from "hono/http-exception";
3
+ import { REVISION_HEADER } from "../shared/state-protocol.js";
4
+ import { parseLaunchOptions } from "./claude.js";
3
5
  import { DirectoryError, listDirectories } from "./directories.js";
4
6
  import { ServiceError } from "./service.js";
5
7
  import { mountStatic } from "./static.js";
@@ -48,7 +50,7 @@ export function createApp(service, options = {}) {
48
50
  return;
49
51
  const revision = options.onMutation?.();
50
52
  if (revision !== undefined)
51
- c.res.headers.set("State-Revision", String(revision));
53
+ c.res.headers.set(REVISION_HEADER, String(revision));
52
54
  });
53
55
  // `k-bench status` asks this. It is behind the access guard like everything else, so the
54
56
  // caller must send the owner's login.
@@ -103,9 +105,18 @@ export function createApp(service, options = {}) {
103
105
  });
104
106
  app.post("/api/workspaces/:id/sessions", async (c) => {
105
107
  const body = await jsonBody(c.req.raw);
106
- const session = await service.createSession(c.req.param("id"), optionalString(body.name));
108
+ // `claude` makes it a Claude Session; its Launch options are checked before anything starts.
109
+ let launchOptions;
110
+ if (body.claude !== undefined) {
111
+ const parsed = parseLaunchOptions(body.claude);
112
+ if ("error" in parsed)
113
+ throw new ServiceError("invalid", parsed.error);
114
+ launchOptions = parsed.options;
115
+ }
116
+ const session = await service.createSession(c.req.param("id"), optionalString(body.name), launchOptions);
107
117
  return c.json(session, 201);
108
118
  });
119
+ app.get("/api/claude/launch-options", (c) => c.json(service.lastLaunchOptions()));
109
120
  app.patch("/api/sessions/:id", async (c) => {
110
121
  const body = await jsonBody(c.req.raw);
111
122
  return c.json(service.renameSession(c.req.param("id"), optionalString(body.name) ?? ""));
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Launching Claude Code for a Claude Session (ADR-0005). k-bench starts it through its
3
+ * documented command-line flags and never reads its output or its files, so everything
4
+ * k-bench knows about Claude Code is in this file: the flags it passes and the launcher
5
+ * script that runs it.
6
+ */
7
+ import { DEFAULT_LAUNCH_OPTIONS, LAUNCH_CHOICES, } from "../shared/launch-options.js";
8
+ /**
9
+ * Reads Launch options from a request. A field left out is Default; a value that is not one
10
+ * of the choices is refused, naming the field (`claude.model`).
11
+ */
12
+ export function parseLaunchOptions(value) {
13
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
14
+ return { error: "claude must be an object" };
15
+ }
16
+ const given = value;
17
+ const options = { ...DEFAULT_LAUNCH_OPTIONS };
18
+ for (const field of ["model", "effort", "advisor"]) {
19
+ const choice = given[field];
20
+ if (choice === undefined)
21
+ continue;
22
+ const choices = LAUNCH_CHOICES[field];
23
+ if (!choices.includes(choice)) {
24
+ return {
25
+ error: `claude.${field} must be one of ${LAUNCH_CHOICES[field].join(", ")}`,
26
+ };
27
+ }
28
+ options[field] = choice;
29
+ }
30
+ if (given.focusView !== undefined) {
31
+ if (typeof given.focusView !== "boolean") {
32
+ return { error: "claude.focusView must be true or false" };
33
+ }
34
+ options.focusView = given.focusView;
35
+ }
36
+ return { options };
37
+ }
38
+ /**
39
+ * Both keys are needed: focus view does nothing without the fullscreen renderer, and
40
+ * fullscreen is not the default on every machine. `--settings` applies to that launch only
41
+ * and leaves the owner's settings files unchanged.
42
+ */
43
+ const FOCUS_VIEW_SETTINGS = '{"viewMode":"focus","tui":"fullscreen"}';
44
+ /**
45
+ * The flags that follow the one naming the conversation. This is where Launch options become
46
+ * 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.
48
+ */
49
+ function launchOptionArguments(options) {
50
+ const { model, effort, advisor, focusView } = options;
51
+ return [
52
+ ...(model === "default" ? [] : ["--model", model]),
53
+ ...(effort === "default" ? [] : ["--effort", effort]),
54
+ ...(advisor === "default" || advisor === "off" ? [] : ["--advisor", advisor]),
55
+ ...(focusView ? ["--settings", FOCUS_VIEW_SETTINGS] : []),
56
+ ];
57
+ }
58
+ /** Printed, and waited on, when Claude Code exits with an error. */
59
+ const ERROR_MESSAGE = "Claude Code exited with an error. Press any key to close.";
60
+ /**
61
+ * Runs Claude Code in the folder, then ends the pane on status 0. On any other status it holds
62
+ * the screen, so the error above it can be read, until a key is pressed. There is no shell
63
+ * underneath: whichever way it ends, the pane ends with it.
64
+ *
65
+ * A restart (mode "resume") tries `--resume <conversation ID>` first. Claude Code saves a
66
+ * conversation only after its first message, so with nothing to resume that fails with exit 1
67
+ * and the launcher tries once more with `--session-id <conversation ID>`. This is safe
68
+ * without looking at Claude Code's files (ADR-0005): `--session-id` fails with exit 1 on an
69
+ * ID that already has a conversation, so the two attempts can never both run one conversation
70
+ * and neither can fork or overwrite it. Both attempts get every Launch option, because
71
+ * `--resume` does not restore `--settings`. Advisor Off sets
72
+ * `CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1` for both, because leaving out `--advisor` is not
73
+ * enough when the owner's settings turn the advisor on.
74
+ *
75
+ * Arguments, never script text: the folder, the program, whether the advisor is off (1 or 0),
76
+ * the mode, the conversation ID, then the option flags. It is plain POSIX `sh` (the wait for
77
+ * a key uses `stty` and `dd`, not `read -n`, which zsh spells differently), so it runs the
78
+ * same under macOS's bash-as-sh and any `sh`. The `cd` is repeated because the owner's login
79
+ * startup files may change directory.
80
+ */
81
+ const LAUNCHER = `
82
+ cd -- "$1"
83
+ program=$2
84
+ advisor_off=$3
85
+ mode=$4
86
+ conversation=$5
87
+ shift 5
88
+ [ "$advisor_off" = 1 ] && export CLAUDE_CODE_DISABLE_ADVISOR_TOOL=1
89
+ if [ "$mode" = resume ]; then
90
+ "$program" --resume "$conversation" "$@"
91
+ [ "$?" -eq 0 ] && exit 0
92
+ fi
93
+ "$program" --session-id "$conversation" "$@"
94
+ status=$?
95
+ [ "$status" -eq 0 ] && exit 0
96
+ printf '\\n%s\\n' '${ERROR_MESSAGE}'
97
+ saved=$(stty -g)
98
+ stty -icanon -echo min 1 time 0
99
+ dd bs=1 count=1 >/dev/null 2>&1
100
+ stty "$saved"
101
+ exit "$status"
102
+ `;
103
+ /**
104
+ * What a Claude Session's pane runs, as an argument list for `tmux new-session`.
105
+ *
106
+ * Three programs, each there for a reason:
107
+ * 1. zsh with no startup files changes into `folder`. tmux ignores `-c` once its own working
108
+ * directory has been deleted (see `sessionCommand` in tmux.ts), and bash prints a
109
+ * `getcwd` error then.
110
+ * 2. The owner's login shell (`shell`) runs `exec "$@"`. It only exists to give the launcher
111
+ * the owner's PATH, so `claude` resolves as in a terminal on the Host, even though
112
+ * launchd provides a bare environment. It is interactive too, because the Claude Code
113
+ * installer adds itself to PATH in `.zshrc`, which a login shell alone does not read.
114
+ * 3. `/bin/sh` runs the launcher.
115
+ *
116
+ * The folder, the program and every flag are positional arguments, never spliced into a
117
+ * script, so nothing in them can break or inject into it.
118
+ */
119
+ export function claudeCommand(input) {
120
+ const { folder, shell, program, launch } = input;
121
+ return [
122
+ "/bin/zsh",
123
+ "-f",
124
+ "-c",
125
+ 'cd -- "$1"; shift; exec "$@"',
126
+ "zsh",
127
+ folder,
128
+ shell,
129
+ "-l",
130
+ "-i",
131
+ "-c",
132
+ 'exec "$@"',
133
+ "kb-login",
134
+ "/bin/sh",
135
+ "-c",
136
+ LAUNCHER,
137
+ "kb-launcher",
138
+ folder,
139
+ program,
140
+ launch.options.advisor === "off" ? "1" : "0",
141
+ launch.mode,
142
+ launch.conversationId,
143
+ ...launchOptionArguments(launch.options),
144
+ ];
145
+ }
@@ -38,5 +38,6 @@ export function resolveConfig(env = process.env) {
38
38
  port: parsePort(env.K_BENCH_PORT) ?? preset.port,
39
39
  allowedLogin: env.K_BENCH_ALLOWED_LOGIN ?? "",
40
40
  pickerRoot: resolve(env.K_BENCH_PICKER_ROOT ?? homedir()),
41
+ claudeProgram: "claude",
41
42
  };
42
43
  }
@@ -1,5 +1,5 @@
1
1
  import { WebSocketServer } from "ws";
2
- const EVENTS_PATH = "/api/events";
2
+ import { EVENTS_PATH } from "../shared/state-protocol.js";
3
3
  /**
4
4
  * The events WebSocket, one per browser tab: `GET /api/events`. The server sends the current
5
5
  * state as a JSON text frame on connect, then a fresh full snapshot whenever state changes.
@@ -11,7 +11,7 @@ import { TmuxDriver } from "./tmux.js";
11
11
  /** Boots a server for one instance config. Used by `main.ts` and by the test harness. */
12
12
  export async function startServer(config, options = {}) {
13
13
  const store = new Store(config.dataDir);
14
- const tmux = new TmuxDriver(config.tmuxSocket);
14
+ const tmux = new TmuxDriver(config.tmuxSocket, config.claudeProgram);
15
15
  const service = new Service(store, tmux);
16
16
  // Anything on the socket that the store does not know is left over: clean it up first.
17
17
  await service.reconcile();
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { statSync } from "node:fs";
3
3
  import { basename, resolve } from "node:path";
4
+ import { DEFAULT_LAUNCH_OPTIONS } from "../shared/launch-options.js";
4
5
  import { availableName } from "./naming.js";
5
6
  import { Reconciler } from "./reconciler.js";
6
7
  /** A failure the HTTP layer maps to a status code. */
@@ -107,12 +108,14 @@ export class Service {
107
108
  * One at a time: choosing the name and storing the Session are separated by starting
108
109
  * the shell, so overlapping creations would otherwise pick the same default name.
109
110
  */
110
- createSession(workspaceId, requestedName) {
111
- const result = this.sessionCreations.then(() => this.createSessionNow(workspaceId, requestedName));
111
+ createSession(workspaceId, requestedName,
112
+ /** Makes it a Claude Session started with these Launch options. */
113
+ launchOptions) {
114
+ const result = this.sessionCreations.then(() => this.createSessionNow(workspaceId, requestedName, launchOptions));
112
115
  this.sessionCreations = result.catch(() => undefined);
113
116
  return result;
114
117
  }
115
- async createSessionNow(workspaceId, requestedName) {
118
+ async createSessionNow(workspaceId, requestedName, launchOptions) {
116
119
  const workspace = this.store.getWorkspace(workspaceId);
117
120
  if (!workspace)
118
121
  throw new ServiceError("not_found", "Unknown Workspace");
@@ -131,18 +134,37 @@ export class Service {
131
134
  throw new ServiceError("conflict", `A Session named "${name}" already exists`);
132
135
  }
133
136
  const id = randomUUID();
137
+ // k-bench chooses the Claude conversation's ID, so a restart can name it (ADR-0005).
138
+ const claude = launchOptions && {
139
+ conversationId: randomUUID(),
140
+ options: launchOptions,
141
+ mode: "start",
142
+ };
134
143
  await this.reconciler.whileStarting(id, async () => {
135
- await this.tmux.createSession(id, workspace.folder);
144
+ await this.tmux.createSession(id, workspace.folder, claude);
136
145
  try {
137
- this.store.addSession({ id, workspaceId, name });
146
+ this.store.addSession({
147
+ id,
148
+ workspaceId,
149
+ name,
150
+ conversationId: claude?.conversationId,
151
+ launchOptions: claude?.options,
152
+ });
138
153
  }
139
154
  catch (error) {
140
155
  await this.tmux.killSession(id);
141
156
  throw error;
142
157
  }
143
158
  });
159
+ // Remembered for the next New Claude dialog, on any device.
160
+ if (launchOptions)
161
+ this.store.setLastLaunchOptions(launchOptions);
144
162
  return { id, name };
145
163
  }
164
+ /** The Launch options last used for a Claude Session; all Default, Focus view off, if none. */
165
+ lastLaunchOptions() {
166
+ return this.store.getLastLaunchOptions() ?? DEFAULT_LAUNCH_OPTIONS;
167
+ }
146
168
  renameSession(sessionId, requestedName) {
147
169
  const session = this.store.getSession(sessionId);
148
170
  if (!session)
@@ -176,6 +198,7 @@ export class Service {
176
198
  sessions: this.store.listSessions(workspace.id).map((session) => ({
177
199
  id: session.id,
178
200
  name: session.name,
201
+ kind: session.kind,
179
202
  status: live.has(session.id) ? "running" : "stopped",
180
203
  bell: live.get(session.id)?.bell ?? false,
181
204
  })),
@@ -183,7 +206,8 @@ export class Service {
183
206
  };
184
207
  }
185
208
  /**
186
- * Gives a Stopped Session a fresh shell in its Workspace folder, keeping its id and name.
209
+ * Gives a Stopped Session a fresh program in its Workspace folder, keeping its id and name:
210
+ * a shell, or Claude Code for a Claude Session.
187
211
  * A Session that is already running is left alone.
188
212
  */
189
213
  async restartSession(sessionId) {
@@ -205,7 +229,14 @@ export class Service {
205
229
  if (!isDirectory(session.folder)) {
206
230
  throw new ServiceError("invalid", `Folder does not exist: ${session.folder}`);
207
231
  }
208
- await this.reconciler.whileStarting(session.id, () => this.tmux.createSession(session.id, session.folder));
232
+ await this.reconciler.whileStarting(session.id, () => this.tmux.createSession(session.id, session.folder, session.conversationId === null
233
+ ? undefined
234
+ : {
235
+ conversationId: session.conversationId,
236
+ mode: "resume",
237
+ // Every Launch option is passed again each time (ADR-0005).
238
+ options: session.launchOptions ?? DEFAULT_LAUNCH_OPTIONS,
239
+ }));
209
240
  }
210
241
  /** Whether the terminal WebSocket has a shell to attach to: a known Session that is running. */
211
242
  async hasRunningShell(sessionId) {
@@ -1,3 +1,4 @@
1
+ import { encodeSnapshot } from "../shared/state-protocol.js";
1
2
  /**
2
3
  * Change detection for the events WebSocket. It reads the state, and whenever the result
3
4
  * differs from the last one sent, pushes the fresh snapshot to every subscriber.
@@ -106,7 +107,7 @@ export class StateFeed {
106
107
  const changed = body !== this.last || revision !== this.sentRevision;
107
108
  this.last = body;
108
109
  this.sentRevision = revision;
109
- const snapshot = JSON.stringify({ revision, ...state });
110
+ const snapshot = encodeSnapshot(state, revision);
110
111
  const targets = changed ? [...this.listeners] : [...this.fresh];
111
112
  this.fresh.clear();
112
113
  for (const listener of targets)
@@ -21,8 +21,32 @@ const MIGRATIONS = [
21
21
  created_at INTEGER NOT NULL,
22
22
  UNIQUE (workspace_id, name)
23
23
  );
24
+ `,
25
+ // A Session's kind (every row so far is a shell Session) and, for a Claude Session, the
26
+ // conversation ID k-bench generated for it.
27
+ `
28
+ ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'shell';
29
+ ALTER TABLE sessions ADD COLUMN conversation_id TEXT;
30
+ `,
31
+ // A Claude Session's Launch options, as JSON, so a restart can pass them again.
32
+ `
33
+ ALTER TABLE sessions ADD COLUMN launch_options TEXT;
34
+ `,
35
+ // The Host's one record of the Launch options last used to create a Claude Session; the id
36
+ // check keeps it to one row.
37
+ `
38
+ CREATE TABLE claude_last_launch_options (
39
+ id INTEGER PRIMARY KEY CHECK (id = 1),
40
+ options TEXT NOT NULL
41
+ );
24
42
  `,
25
43
  ];
44
+ function sessionRow(raw) {
45
+ return {
46
+ ...raw,
47
+ launchOptions: raw.launchOptions === null ? null : JSON.parse(raw.launchOptions),
48
+ };
49
+ }
26
50
  export class Store {
27
51
  db;
28
52
  constructor(dataDir) {
@@ -101,16 +125,34 @@ export class Store {
101
125
  }
102
126
  }
103
127
  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`)
128
+ const rows = this.db
129
+ .prepare(`SELECT id, workspace_id AS workspaceId, name, kind,
130
+ conversation_id AS conversationId, launch_options AS launchOptions
131
+ FROM sessions WHERE workspace_id = ? ORDER BY created_at, rowid`)
107
132
  .all(workspaceId);
133
+ return rows.map(sessionRow);
108
134
  }
109
135
  getSession(id) {
110
- return this.db
111
- .prepare(`SELECT s.id, s.workspace_id AS workspaceId, s.name, w.folder
136
+ const row = this.db
137
+ .prepare(`SELECT s.id, s.workspace_id AS workspaceId, s.name, s.kind,
138
+ s.conversation_id AS conversationId,
139
+ s.launch_options AS launchOptions, w.folder
112
140
  FROM sessions s JOIN workspaces w ON w.id = s.workspace_id WHERE s.id = ?`)
113
141
  .get(id);
142
+ return row && sessionRow(row);
143
+ }
144
+ /** The Launch options last used to create a Claude Session, if any has been created. */
145
+ getLastLaunchOptions() {
146
+ const row = this.db
147
+ .prepare("SELECT options FROM claude_last_launch_options WHERE id = 1")
148
+ .get();
149
+ return row && JSON.parse(row.options);
150
+ }
151
+ setLastLaunchOptions(options) {
152
+ this.db
153
+ .prepare(`INSERT INTO claude_last_launch_options (id, options) VALUES (1, ?)
154
+ ON CONFLICT (id) DO UPDATE SET options = excluded.options`)
155
+ .run(JSON.stringify(options));
114
156
  }
115
157
  renameSession(id, name) {
116
158
  this.db.prepare("UPDATE sessions SET name = ? WHERE id = ?").run(name, id);
@@ -119,9 +161,21 @@ export class Store {
119
161
  this.db.prepare("DELETE FROM sessions WHERE id = ?").run(id);
120
162
  }
121
163
  addSession(input) {
164
+ const conversationId = input.conversationId ?? null;
165
+ const launchOptions = conversationId === null ? null : (input.launchOptions ?? null);
166
+ const kind = conversationId === null ? "shell" : "claude";
122
167
  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;
168
+ .prepare(`INSERT INTO sessions
169
+ (id, workspace_id, name, created_at, kind, conversation_id, launch_options)
170
+ VALUES (?, ?, ?, ?, ?, ?, ?)`)
171
+ .run(input.id, input.workspaceId, input.name, Date.now(), kind, conversationId, launchOptions && JSON.stringify(launchOptions));
172
+ return {
173
+ id: input.id,
174
+ workspaceId: input.workspaceId,
175
+ name: input.name,
176
+ kind,
177
+ conversationId,
178
+ launchOptions,
179
+ };
126
180
  }
127
181
  }
@@ -2,6 +2,7 @@ import { execFile, spawn } from "node:child_process";
2
2
  import { userInfo } from "node:os";
3
3
  import { promisify } from "node:util";
4
4
  import * as pty from "node-pty";
5
+ import { claudeCommand } from "./claude.js";
5
6
  const execFileAsync = promisify(execFile);
6
7
  /** Every Session is a tmux session named `kb-<session id>` on the instance's socket. */
7
8
  const PREFIX = "kb-";
@@ -93,12 +94,22 @@ export class TmuxDriver {
93
94
  socket;
94
95
  /** Bell watches, which a new tmux server must wake (see `watchBells`). */
95
96
  bellWatches = new Set();
96
- constructor(socket) {
97
+ /** The program a Claude Session runs (`InstanceConfig.claudeProgram`). */
98
+ claudeProgram;
99
+ constructor(socket, claudeProgram = "claude") {
97
100
  this.socket = socket;
101
+ this.claudeProgram = claudeProgram;
98
102
  }
99
103
  env() {
100
- // A k-bench server started from inside a tmux pane must not think it is nested.
104
+ // A k-bench server started from inside a tmux pane must not think it is nested, and
105
+ // one started by Claude Code (a Dev instance an agent runs) must not hand Claude Code's
106
+ // own session variables, such as CLAUDE_CODE_DISABLE_ADVISOR_TOOL, to every Session.
107
+ // The owner's own settings come back from their login shell, which each Session runs.
101
108
  const { TMUX: _tmux, TMUX_PANE: _pane, ...env } = process.env;
109
+ for (const name of Object.keys(env)) {
110
+ if (name === "CLAUDECODE" || name.startsWith("CLAUDE_"))
111
+ delete env[name];
112
+ }
102
113
  return env;
103
114
  }
104
115
  baseArgs() {
@@ -114,8 +125,19 @@ export class TmuxDriver {
114
125
  const { stdout } = await execFileAsync("tmux", args, { env: this.env() });
115
126
  return stdout;
116
127
  }
117
- /** Starts a shell for the Session in `folder`, configuring the tmux server as needed. */
118
- async createSession(id, folder) {
128
+ /**
129
+ * Starts the Session in `folder`, configuring the tmux server as needed: the owner's shell,
130
+ * or, given `claude`, Claude Code.
131
+ */
132
+ async createSession(id, folder, claude) {
133
+ const command = claude
134
+ ? claudeCommand({
135
+ folder,
136
+ shell: ownerShell(),
137
+ program: this.claudeProgram,
138
+ launch: claude,
139
+ })
140
+ : sessionCommand(folder);
119
141
  await this.run(...serverConfiguration(), [
120
142
  "new-session",
121
143
  "-d",
@@ -124,7 +146,7 @@ export class TmuxDriver {
124
146
  "-c",
125
147
  folder,
126
148
  "--",
127
- ...sessionCommand(folder),
149
+ ...command,
128
150
  ]);
129
151
  // This may have started the tmux server, which a Bell watch idles without.
130
152
  for (const watch of this.bellWatches)
@@ -325,10 +347,17 @@ function isNoServer(error) {
325
347
  return isNoServerMessage(stderrOf(error));
326
348
  }
327
349
  function isNoServerMessage(stderr) {
328
- return stderr.includes("no server running") || stderr.includes("error connecting to");
350
+ return (stderr.includes("no server running") ||
351
+ stderr.includes("error connecting to") ||
352
+ // The server was shutting down as the command reached it: its last Session had just
353
+ // ended, which is no server at all a moment later.
354
+ stderr.includes("server exited unexpectedly"));
329
355
  }
330
356
  function isNoSuchSession(error) {
331
357
  return (isNoServer(error) ||
332
358
  stderrOf(error).includes("can't find") ||
333
- stderrOf(error).includes("no such session"));
359
+ stderrOf(error).includes("no such session") ||
360
+ // Said when the last Session of the tmux server ended an instant before: there is
361
+ // nothing left to be the target.
362
+ stderrOf(error).includes("no current target"));
334
363
  }
@@ -0,0 +1,14 @@
1
+ /** The Launch options of a Claude Session, shared by the server and the New Claude dialog. */
2
+ /** The choices for each Launch option; what the API accepts. */
3
+ export const LAUNCH_CHOICES = {
4
+ model: ["default", "fable", "opus", "sonnet", "haiku"],
5
+ effort: ["default", "low", "medium", "high", "xhigh", "max"],
6
+ advisor: ["default", "off", "fable", "opus", "sonnet"],
7
+ };
8
+ /** All Default, Focus view off: what a Claude Session gets for a Launch option not given. */
9
+ export const DEFAULT_LAUNCH_OPTIONS = {
10
+ model: "default",
11
+ effort: "default",
12
+ advisor: "default",
13
+ focusView: false,
14
+ };
@@ -0,0 +1,41 @@
1
+ /**
2
+ * The state protocol, the one definition the server, the browser and the test harness all
3
+ * use. The server pushes the Workspaces and Sessions as full snapshots on the events
4
+ * WebSocket (`GET /api/events`), and answers every successful change request with a
5
+ * `State-Revision` header naming the snapshot from which the change shows (see `StateFeed`
6
+ * on the server).
7
+ *
8
+ * Imported by the browser too, so this file has no imports and no Node APIs.
9
+ */
10
+ /** The header a successful change request answers with: the revision that shows it. */
11
+ export const REVISION_HEADER = "State-Revision";
12
+ /** The path of the events WebSocket. */
13
+ export const EVENTS_PATH = "/api/events";
14
+ /** The text frame the server sends for `state` at `revision`. */
15
+ export function encodeSnapshot(state, revision) {
16
+ return JSON.stringify({ revision, ...state });
17
+ }
18
+ /** The snapshot a text frame holds, or undefined when it is not one. */
19
+ export function decodeSnapshot(text) {
20
+ let snapshot;
21
+ try {
22
+ snapshot = JSON.parse(text);
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ if (typeof snapshot !== "object" ||
28
+ snapshot === null ||
29
+ typeof snapshot.revision !== "number" ||
30
+ !Array.isArray(snapshot.workspaces)) {
31
+ return undefined;
32
+ }
33
+ return snapshot;
34
+ }
35
+ /**
36
+ * The revision a response's headers name, from which snapshots show its change. NaN when
37
+ * the header is missing: no snapshot reaches NaN, so a wait for it times out.
38
+ */
39
+ export function revisionOf(headers) {
40
+ return Number(headers.get(REVISION_HEADER) ?? Number.NaN);
41
+ }